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

1.220     brouard     1: /* $Id: imach.c,v 1.219 2016/02/15 00:48:12 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.220     brouard     4:   Revision 1.219  2016/02/15 00:48:12  brouard
                      5:   *** empty log message ***
                      6: 
1.219     brouard     7:   Revision 1.218  2016/02/12 11:29:23  brouard
                      8:   Summary: 0.99 Back projections
                      9: 
1.218     brouard    10:   Revision 1.217  2015/12/23 17:18:31  brouard
                     11:   Summary: Experimental backcast
                     12: 
1.217     brouard    13:   Revision 1.216  2015/12/18 17:32:11  brouard
                     14:   Summary: 0.98r4 Warning and status=-2
                     15: 
                     16:   Version 0.98r4 is now:
                     17:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     18:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     19:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     20: 
1.216     brouard    21:   Revision 1.215  2015/12/16 08:52:24  brouard
                     22:   Summary: 0.98r4 working
                     23: 
1.215     brouard    24:   Revision 1.214  2015/12/16 06:57:54  brouard
                     25:   Summary: temporary not working
                     26: 
1.214     brouard    27:   Revision 1.213  2015/12/11 18:22:17  brouard
                     28:   Summary: 0.98r4
                     29: 
1.213     brouard    30:   Revision 1.212  2015/11/21 12:47:24  brouard
                     31:   Summary: minor typo
                     32: 
1.212     brouard    33:   Revision 1.211  2015/11/21 12:41:11  brouard
                     34:   Summary: 0.98r3 with some graph of projected cross-sectional
                     35: 
                     36:   Author: Nicolas Brouard
                     37: 
1.211     brouard    38:   Revision 1.210  2015/11/18 17:41:20  brouard
                     39:   Summary: Start working on projected prevalences
                     40: 
1.210     brouard    41:   Revision 1.209  2015/11/17 22:12:03  brouard
                     42:   Summary: Adding ftolpl parameter
                     43:   Author: N Brouard
                     44: 
                     45:   We had difficulties to get smoothed confidence intervals. It was due
                     46:   to the period prevalence which wasn't computed accurately. The inner
                     47:   parameter ftolpl is now an outer parameter of the .imach parameter
                     48:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     49:   computation are long.
                     50: 
1.209     brouard    51:   Revision 1.208  2015/11/17 14:31:57  brouard
                     52:   Summary: temporary
                     53: 
1.208     brouard    54:   Revision 1.207  2015/10/27 17:36:57  brouard
                     55:   *** empty log message ***
                     56: 
1.207     brouard    57:   Revision 1.206  2015/10/24 07:14:11  brouard
                     58:   *** empty log message ***
                     59: 
1.206     brouard    60:   Revision 1.205  2015/10/23 15:50:53  brouard
                     61:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     62: 
1.205     brouard    63:   Revision 1.204  2015/10/01 16:20:26  brouard
                     64:   Summary: Some new graphs of contribution to likelihood
                     65: 
1.204     brouard    66:   Revision 1.203  2015/09/30 17:45:14  brouard
                     67:   Summary: looking at better estimation of the hessian
                     68: 
                     69:   Also a better criteria for convergence to the period prevalence And
                     70:   therefore adding the number of years needed to converge. (The
                     71:   prevalence in any alive state shold sum to one
                     72: 
1.203     brouard    73:   Revision 1.202  2015/09/22 19:45:16  brouard
                     74:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     75: 
1.202     brouard    76:   Revision 1.201  2015/09/15 17:34:58  brouard
                     77:   Summary: 0.98r0
                     78: 
                     79:   - Some new graphs like suvival functions
                     80:   - Some bugs fixed like model=1+age+V2.
                     81: 
1.201     brouard    82:   Revision 1.200  2015/09/09 16:53:55  brouard
                     83:   Summary: Big bug thanks to Flavia
                     84: 
                     85:   Even model=1+age+V2. did not work anymore
                     86: 
1.200     brouard    87:   Revision 1.199  2015/09/07 14:09:23  brouard
                     88:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     89: 
1.199     brouard    90:   Revision 1.198  2015/09/03 07:14:39  brouard
                     91:   Summary: 0.98q5 Flavia
                     92: 
1.198     brouard    93:   Revision 1.197  2015/09/01 18:24:39  brouard
                     94:   *** empty log message ***
                     95: 
1.197     brouard    96:   Revision 1.196  2015/08/18 23:17:52  brouard
                     97:   Summary: 0.98q5
                     98: 
1.196     brouard    99:   Revision 1.195  2015/08/18 16:28:39  brouard
                    100:   Summary: Adding a hack for testing purpose
                    101: 
                    102:   After reading the title, ftol and model lines, if the comment line has
                    103:   a q, starting with #q, the answer at the end of the run is quit. It
                    104:   permits to run test files in batch with ctest. The former workaround was
                    105:   $ echo q | imach foo.imach
                    106: 
1.195     brouard   107:   Revision 1.194  2015/08/18 13:32:00  brouard
                    108:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    109: 
1.194     brouard   110:   Revision 1.193  2015/08/04 07:17:42  brouard
                    111:   Summary: 0.98q4
                    112: 
1.193     brouard   113:   Revision 1.192  2015/07/16 16:49:02  brouard
                    114:   Summary: Fixing some outputs
                    115: 
1.192     brouard   116:   Revision 1.191  2015/07/14 10:00:33  brouard
                    117:   Summary: Some fixes
                    118: 
1.191     brouard   119:   Revision 1.190  2015/05/05 08:51:13  brouard
                    120:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    121: 
                    122:   Fix 1+age+.
                    123: 
1.190     brouard   124:   Revision 1.189  2015/04/30 14:45:16  brouard
                    125:   Summary: 0.98q2
                    126: 
1.189     brouard   127:   Revision 1.188  2015/04/30 08:27:53  brouard
                    128:   *** empty log message ***
                    129: 
1.188     brouard   130:   Revision 1.187  2015/04/29 09:11:15  brouard
                    131:   *** empty log message ***
                    132: 
1.187     brouard   133:   Revision 1.186  2015/04/23 12:01:52  brouard
                    134:   Summary: V1*age is working now, version 0.98q1
                    135: 
                    136:   Some codes had been disabled in order to simplify and Vn*age was
                    137:   working in the optimization phase, ie, giving correct MLE parameters,
                    138:   but, as usual, outputs were not correct and program core dumped.
                    139: 
1.186     brouard   140:   Revision 1.185  2015/03/11 13:26:42  brouard
                    141:   Summary: Inclusion of compile and links command line for Intel Compiler
                    142: 
1.185     brouard   143:   Revision 1.184  2015/03/11 11:52:39  brouard
                    144:   Summary: Back from Windows 8. Intel Compiler
                    145: 
1.184     brouard   146:   Revision 1.183  2015/03/10 20:34:32  brouard
                    147:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    148: 
                    149:   We use directest instead of original Powell test; probably no
                    150:   incidence on the results, but better justifications;
                    151:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    152:   wrong results.
                    153: 
1.183     brouard   154:   Revision 1.182  2015/02/12 08:19:57  brouard
                    155:   Summary: Trying to keep directest which seems simpler and more general
                    156:   Author: Nicolas Brouard
                    157: 
1.182     brouard   158:   Revision 1.181  2015/02/11 23:22:24  brouard
                    159:   Summary: Comments on Powell added
                    160: 
                    161:   Author:
                    162: 
1.181     brouard   163:   Revision 1.180  2015/02/11 17:33:45  brouard
                    164:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    165: 
1.180     brouard   166:   Revision 1.179  2015/01/04 09:57:06  brouard
                    167:   Summary: back to OS/X
                    168: 
1.179     brouard   169:   Revision 1.178  2015/01/04 09:35:48  brouard
                    170:   *** empty log message ***
                    171: 
1.178     brouard   172:   Revision 1.177  2015/01/03 18:40:56  brouard
                    173:   Summary: Still testing ilc32 on OSX
                    174: 
1.177     brouard   175:   Revision 1.176  2015/01/03 16:45:04  brouard
                    176:   *** empty log message ***
                    177: 
1.176     brouard   178:   Revision 1.175  2015/01/03 16:33:42  brouard
                    179:   *** empty log message ***
                    180: 
1.175     brouard   181:   Revision 1.174  2015/01/03 16:15:49  brouard
                    182:   Summary: Still in cross-compilation
                    183: 
1.174     brouard   184:   Revision 1.173  2015/01/03 12:06:26  brouard
                    185:   Summary: trying to detect cross-compilation
                    186: 
1.173     brouard   187:   Revision 1.172  2014/12/27 12:07:47  brouard
                    188:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    189: 
1.172     brouard   190:   Revision 1.171  2014/12/23 13:26:59  brouard
                    191:   Summary: Back from Visual C
                    192: 
                    193:   Still problem with utsname.h on Windows
                    194: 
1.171     brouard   195:   Revision 1.170  2014/12/23 11:17:12  brouard
                    196:   Summary: Cleaning some \%% back to %%
                    197: 
                    198:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    199: 
1.170     brouard   200:   Revision 1.169  2014/12/22 23:08:31  brouard
                    201:   Summary: 0.98p
                    202: 
                    203:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    204: 
1.169     brouard   205:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   206:   Summary: update
1.169     brouard   207: 
1.168     brouard   208:   Revision 1.167  2014/12/22 13:50:56  brouard
                    209:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    210: 
                    211:   Testing on Linux 64
                    212: 
1.167     brouard   213:   Revision 1.166  2014/12/22 11:40:47  brouard
                    214:   *** empty log message ***
                    215: 
1.166     brouard   216:   Revision 1.165  2014/12/16 11:20:36  brouard
                    217:   Summary: After compiling on Visual C
                    218: 
                    219:   * imach.c (Module): Merging 1.61 to 1.162
                    220: 
1.165     brouard   221:   Revision 1.164  2014/12/16 10:52:11  brouard
                    222:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    223: 
                    224:   * imach.c (Module): Merging 1.61 to 1.162
                    225: 
1.164     brouard   226:   Revision 1.163  2014/12/16 10:30:11  brouard
                    227:   * imach.c (Module): Merging 1.61 to 1.162
                    228: 
1.163     brouard   229:   Revision 1.162  2014/09/25 11:43:39  brouard
                    230:   Summary: temporary backup 0.99!
                    231: 
1.162     brouard   232:   Revision 1.1  2014/09/16 11:06:58  brouard
                    233:   Summary: With some code (wrong) for nlopt
                    234: 
                    235:   Author:
                    236: 
                    237:   Revision 1.161  2014/09/15 20:41:41  brouard
                    238:   Summary: Problem with macro SQR on Intel compiler
                    239: 
1.161     brouard   240:   Revision 1.160  2014/09/02 09:24:05  brouard
                    241:   *** empty log message ***
                    242: 
1.160     brouard   243:   Revision 1.159  2014/09/01 10:34:10  brouard
                    244:   Summary: WIN32
                    245:   Author: Brouard
                    246: 
1.159     brouard   247:   Revision 1.158  2014/08/27 17:11:51  brouard
                    248:   *** empty log message ***
                    249: 
1.158     brouard   250:   Revision 1.157  2014/08/27 16:26:55  brouard
                    251:   Summary: Preparing windows Visual studio version
                    252:   Author: Brouard
                    253: 
                    254:   In order to compile on Visual studio, time.h is now correct and time_t
                    255:   and tm struct should be used. difftime should be used but sometimes I
                    256:   just make the differences in raw time format (time(&now).
                    257:   Trying to suppress #ifdef LINUX
                    258:   Add xdg-open for __linux in order to open default browser.
                    259: 
1.157     brouard   260:   Revision 1.156  2014/08/25 20:10:10  brouard
                    261:   *** empty log message ***
                    262: 
1.156     brouard   263:   Revision 1.155  2014/08/25 18:32:34  brouard
                    264:   Summary: New compile, minor changes
                    265:   Author: Brouard
                    266: 
1.155     brouard   267:   Revision 1.154  2014/06/20 17:32:08  brouard
                    268:   Summary: Outputs now all graphs of convergence to period prevalence
                    269: 
1.154     brouard   270:   Revision 1.153  2014/06/20 16:45:46  brouard
                    271:   Summary: If 3 live state, convergence to period prevalence on same graph
                    272:   Author: Brouard
                    273: 
1.153     brouard   274:   Revision 1.152  2014/06/18 17:54:09  brouard
                    275:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    276: 
1.152     brouard   277:   Revision 1.151  2014/06/18 16:43:30  brouard
                    278:   *** empty log message ***
                    279: 
1.151     brouard   280:   Revision 1.150  2014/06/18 16:42:35  brouard
                    281:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    282:   Author: brouard
                    283: 
1.150     brouard   284:   Revision 1.149  2014/06/18 15:51:14  brouard
                    285:   Summary: Some fixes in parameter files errors
                    286:   Author: Nicolas Brouard
                    287: 
1.149     brouard   288:   Revision 1.148  2014/06/17 17:38:48  brouard
                    289:   Summary: Nothing new
                    290:   Author: Brouard
                    291: 
                    292:   Just a new packaging for OS/X version 0.98nS
                    293: 
1.148     brouard   294:   Revision 1.147  2014/06/16 10:33:11  brouard
                    295:   *** empty log message ***
                    296: 
1.147     brouard   297:   Revision 1.146  2014/06/16 10:20:28  brouard
                    298:   Summary: Merge
                    299:   Author: Brouard
                    300: 
                    301:   Merge, before building revised version.
                    302: 
1.146     brouard   303:   Revision 1.145  2014/06/10 21:23:15  brouard
                    304:   Summary: Debugging with valgrind
                    305:   Author: Nicolas Brouard
                    306: 
                    307:   Lot of changes in order to output the results with some covariates
                    308:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    309:   improve the code.
                    310:   No more memory valgrind error but a lot has to be done in order to
                    311:   continue the work of splitting the code into subroutines.
                    312:   Also, decodemodel has been improved. Tricode is still not
                    313:   optimal. nbcode should be improved. Documentation has been added in
                    314:   the source code.
                    315: 
1.144     brouard   316:   Revision 1.143  2014/01/26 09:45:38  brouard
                    317:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    318: 
                    319:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    320:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    321: 
1.143     brouard   322:   Revision 1.142  2014/01/26 03:57:36  brouard
                    323:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    324: 
                    325:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    326: 
1.142     brouard   327:   Revision 1.141  2014/01/26 02:42:01  brouard
                    328:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    329: 
1.141     brouard   330:   Revision 1.140  2011/09/02 10:37:54  brouard
                    331:   Summary: times.h is ok with mingw32 now.
                    332: 
1.140     brouard   333:   Revision 1.139  2010/06/14 07:50:17  brouard
                    334:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    335:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    336: 
1.139     brouard   337:   Revision 1.138  2010/04/30 18:19:40  brouard
                    338:   *** empty log message ***
                    339: 
1.138     brouard   340:   Revision 1.137  2010/04/29 18:11:38  brouard
                    341:   (Module): Checking covariates for more complex models
                    342:   than V1+V2. A lot of change to be done. Unstable.
                    343: 
1.137     brouard   344:   Revision 1.136  2010/04/26 20:30:53  brouard
                    345:   (Module): merging some libgsl code. Fixing computation
                    346:   of likelione (using inter/intrapolation if mle = 0) in order to
                    347:   get same likelihood as if mle=1.
                    348:   Some cleaning of code and comments added.
                    349: 
1.136     brouard   350:   Revision 1.135  2009/10/29 15:33:14  brouard
                    351:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    352: 
1.135     brouard   353:   Revision 1.134  2009/10/29 13:18:53  brouard
                    354:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    355: 
1.134     brouard   356:   Revision 1.133  2009/07/06 10:21:25  brouard
                    357:   just nforces
                    358: 
1.133     brouard   359:   Revision 1.132  2009/07/06 08:22:05  brouard
                    360:   Many tings
                    361: 
1.132     brouard   362:   Revision 1.131  2009/06/20 16:22:47  brouard
                    363:   Some dimensions resccaled
                    364: 
1.131     brouard   365:   Revision 1.130  2009/05/26 06:44:34  brouard
                    366:   (Module): Max Covariate is now set to 20 instead of 8. A
                    367:   lot of cleaning with variables initialized to 0. Trying to make
                    368:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    369: 
1.130     brouard   370:   Revision 1.129  2007/08/31 13:49:27  lievre
                    371:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    372: 
1.129     lievre    373:   Revision 1.128  2006/06/30 13:02:05  brouard
                    374:   (Module): Clarifications on computing e.j
                    375: 
1.128     brouard   376:   Revision 1.127  2006/04/28 18:11:50  brouard
                    377:   (Module): Yes the sum of survivors was wrong since
                    378:   imach-114 because nhstepm was no more computed in the age
                    379:   loop. Now we define nhstepma in the age loop.
                    380:   (Module): In order to speed up (in case of numerous covariates) we
                    381:   compute health expectancies (without variances) in a first step
                    382:   and then all the health expectancies with variances or standard
                    383:   deviation (needs data from the Hessian matrices) which slows the
                    384:   computation.
                    385:   In the future we should be able to stop the program is only health
                    386:   expectancies and graph are needed without standard deviations.
                    387: 
1.127     brouard   388:   Revision 1.126  2006/04/28 17:23:28  brouard
                    389:   (Module): Yes the sum of survivors was wrong since
                    390:   imach-114 because nhstepm was no more computed in the age
                    391:   loop. Now we define nhstepma in the age loop.
                    392:   Version 0.98h
                    393: 
1.126     brouard   394:   Revision 1.125  2006/04/04 15:20:31  lievre
                    395:   Errors in calculation of health expectancies. Age was not initialized.
                    396:   Forecasting file added.
                    397: 
                    398:   Revision 1.124  2006/03/22 17:13:53  lievre
                    399:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    400:   The log-likelihood is printed in the log file
                    401: 
                    402:   Revision 1.123  2006/03/20 10:52:43  brouard
                    403:   * imach.c (Module): <title> changed, corresponds to .htm file
                    404:   name. <head> headers where missing.
                    405: 
                    406:   * imach.c (Module): Weights can have a decimal point as for
                    407:   English (a comma might work with a correct LC_NUMERIC environment,
                    408:   otherwise the weight is truncated).
                    409:   Modification of warning when the covariates values are not 0 or
                    410:   1.
                    411:   Version 0.98g
                    412: 
                    413:   Revision 1.122  2006/03/20 09:45:41  brouard
                    414:   (Module): Weights can have a decimal point as for
                    415:   English (a comma might work with a correct LC_NUMERIC environment,
                    416:   otherwise the weight is truncated).
                    417:   Modification of warning when the covariates values are not 0 or
                    418:   1.
                    419:   Version 0.98g
                    420: 
                    421:   Revision 1.121  2006/03/16 17:45:01  lievre
                    422:   * imach.c (Module): Comments concerning covariates added
                    423: 
                    424:   * imach.c (Module): refinements in the computation of lli if
                    425:   status=-2 in order to have more reliable computation if stepm is
                    426:   not 1 month. Version 0.98f
                    427: 
                    428:   Revision 1.120  2006/03/16 15:10:38  lievre
                    429:   (Module): refinements in the computation of lli if
                    430:   status=-2 in order to have more reliable computation if stepm is
                    431:   not 1 month. Version 0.98f
                    432: 
                    433:   Revision 1.119  2006/03/15 17:42:26  brouard
                    434:   (Module): Bug if status = -2, the loglikelihood was
                    435:   computed as likelihood omitting the logarithm. Version O.98e
                    436: 
                    437:   Revision 1.118  2006/03/14 18:20:07  brouard
                    438:   (Module): varevsij Comments added explaining the second
                    439:   table of variances if popbased=1 .
                    440:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    441:   (Module): Function pstamp added
                    442:   (Module): Version 0.98d
                    443: 
                    444:   Revision 1.117  2006/03/14 17:16:22  brouard
                    445:   (Module): varevsij Comments added explaining the second
                    446:   table of variances if popbased=1 .
                    447:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    448:   (Module): Function pstamp added
                    449:   (Module): Version 0.98d
                    450: 
                    451:   Revision 1.116  2006/03/06 10:29:27  brouard
                    452:   (Module): Variance-covariance wrong links and
                    453:   varian-covariance of ej. is needed (Saito).
                    454: 
                    455:   Revision 1.115  2006/02/27 12:17:45  brouard
                    456:   (Module): One freematrix added in mlikeli! 0.98c
                    457: 
                    458:   Revision 1.114  2006/02/26 12:57:58  brouard
                    459:   (Module): Some improvements in processing parameter
                    460:   filename with strsep.
                    461: 
                    462:   Revision 1.113  2006/02/24 14:20:24  brouard
                    463:   (Module): Memory leaks checks with valgrind and:
                    464:   datafile was not closed, some imatrix were not freed and on matrix
                    465:   allocation too.
                    466: 
                    467:   Revision 1.112  2006/01/30 09:55:26  brouard
                    468:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    469: 
                    470:   Revision 1.111  2006/01/25 20:38:18  brouard
                    471:   (Module): Lots of cleaning and bugs added (Gompertz)
                    472:   (Module): Comments can be added in data file. Missing date values
                    473:   can be a simple dot '.'.
                    474: 
                    475:   Revision 1.110  2006/01/25 00:51:50  brouard
                    476:   (Module): Lots of cleaning and bugs added (Gompertz)
                    477: 
                    478:   Revision 1.109  2006/01/24 19:37:15  brouard
                    479:   (Module): Comments (lines starting with a #) are allowed in data.
                    480: 
                    481:   Revision 1.108  2006/01/19 18:05:42  lievre
                    482:   Gnuplot problem appeared...
                    483:   To be fixed
                    484: 
                    485:   Revision 1.107  2006/01/19 16:20:37  brouard
                    486:   Test existence of gnuplot in imach path
                    487: 
                    488:   Revision 1.106  2006/01/19 13:24:36  brouard
                    489:   Some cleaning and links added in html output
                    490: 
                    491:   Revision 1.105  2006/01/05 20:23:19  lievre
                    492:   *** empty log message ***
                    493: 
                    494:   Revision 1.104  2005/09/30 16:11:43  lievre
                    495:   (Module): sump fixed, loop imx fixed, and simplifications.
                    496:   (Module): If the status is missing at the last wave but we know
                    497:   that the person is alive, then we can code his/her status as -2
                    498:   (instead of missing=-1 in earlier versions) and his/her
                    499:   contributions to the likelihood is 1 - Prob of dying from last
                    500:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    501:   the healthy state at last known wave). Version is 0.98
                    502: 
                    503:   Revision 1.103  2005/09/30 15:54:49  lievre
                    504:   (Module): sump fixed, loop imx fixed, and simplifications.
                    505: 
                    506:   Revision 1.102  2004/09/15 17:31:30  brouard
                    507:   Add the possibility to read data file including tab characters.
                    508: 
                    509:   Revision 1.101  2004/09/15 10:38:38  brouard
                    510:   Fix on curr_time
                    511: 
                    512:   Revision 1.100  2004/07/12 18:29:06  brouard
                    513:   Add version for Mac OS X. Just define UNIX in Makefile
                    514: 
                    515:   Revision 1.99  2004/06/05 08:57:40  brouard
                    516:   *** empty log message ***
                    517: 
                    518:   Revision 1.98  2004/05/16 15:05:56  brouard
                    519:   New version 0.97 . First attempt to estimate force of mortality
                    520:   directly from the data i.e. without the need of knowing the health
                    521:   state at each age, but using a Gompertz model: log u =a + b*age .
                    522:   This is the basic analysis of mortality and should be done before any
                    523:   other analysis, in order to test if the mortality estimated from the
                    524:   cross-longitudinal survey is different from the mortality estimated
                    525:   from other sources like vital statistic data.
                    526: 
                    527:   The same imach parameter file can be used but the option for mle should be -3.
                    528: 
1.133     brouard   529:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   530:   former routines in order to include the new code within the former code.
                    531: 
                    532:   The output is very simple: only an estimate of the intercept and of
                    533:   the slope with 95% confident intervals.
                    534: 
                    535:   Current limitations:
                    536:   A) Even if you enter covariates, i.e. with the
                    537:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    538:   B) There is no computation of Life Expectancy nor Life Table.
                    539: 
                    540:   Revision 1.97  2004/02/20 13:25:42  lievre
                    541:   Version 0.96d. Population forecasting command line is (temporarily)
                    542:   suppressed.
                    543: 
                    544:   Revision 1.96  2003/07/15 15:38:55  brouard
                    545:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    546:   rewritten within the same printf. Workaround: many printfs.
                    547: 
                    548:   Revision 1.95  2003/07/08 07:54:34  brouard
                    549:   * imach.c (Repository):
                    550:   (Repository): Using imachwizard code to output a more meaningful covariance
                    551:   matrix (cov(a12,c31) instead of numbers.
                    552: 
                    553:   Revision 1.94  2003/06/27 13:00:02  brouard
                    554:   Just cleaning
                    555: 
                    556:   Revision 1.93  2003/06/25 16:33:55  brouard
                    557:   (Module): On windows (cygwin) function asctime_r doesn't
                    558:   exist so I changed back to asctime which exists.
                    559:   (Module): Version 0.96b
                    560: 
                    561:   Revision 1.92  2003/06/25 16:30:45  brouard
                    562:   (Module): On windows (cygwin) function asctime_r doesn't
                    563:   exist so I changed back to asctime which exists.
                    564: 
                    565:   Revision 1.91  2003/06/25 15:30:29  brouard
                    566:   * imach.c (Repository): Duplicated warning errors corrected.
                    567:   (Repository): Elapsed time after each iteration is now output. It
                    568:   helps to forecast when convergence will be reached. Elapsed time
                    569:   is stamped in powell.  We created a new html file for the graphs
                    570:   concerning matrix of covariance. It has extension -cov.htm.
                    571: 
                    572:   Revision 1.90  2003/06/24 12:34:15  brouard
                    573:   (Module): Some bugs corrected for windows. Also, when
                    574:   mle=-1 a template is output in file "or"mypar.txt with the design
                    575:   of the covariance matrix to be input.
                    576: 
                    577:   Revision 1.89  2003/06/24 12:30:52  brouard
                    578:   (Module): Some bugs corrected for windows. Also, when
                    579:   mle=-1 a template is output in file "or"mypar.txt with the design
                    580:   of the covariance matrix to be input.
                    581: 
                    582:   Revision 1.88  2003/06/23 17:54:56  brouard
                    583:   * 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.
                    584: 
                    585:   Revision 1.87  2003/06/18 12:26:01  brouard
                    586:   Version 0.96
                    587: 
                    588:   Revision 1.86  2003/06/17 20:04:08  brouard
                    589:   (Module): Change position of html and gnuplot routines and added
                    590:   routine fileappend.
                    591: 
                    592:   Revision 1.85  2003/06/17 13:12:43  brouard
                    593:   * imach.c (Repository): Check when date of death was earlier that
                    594:   current date of interview. It may happen when the death was just
                    595:   prior to the death. In this case, dh was negative and likelihood
                    596:   was wrong (infinity). We still send an "Error" but patch by
                    597:   assuming that the date of death was just one stepm after the
                    598:   interview.
                    599:   (Repository): Because some people have very long ID (first column)
                    600:   we changed int to long in num[] and we added a new lvector for
                    601:   memory allocation. But we also truncated to 8 characters (left
                    602:   truncation)
                    603:   (Repository): No more line truncation errors.
                    604: 
                    605:   Revision 1.84  2003/06/13 21:44:43  brouard
                    606:   * imach.c (Repository): Replace "freqsummary" at a correct
                    607:   place. It differs from routine "prevalence" which may be called
                    608:   many times. Probs is memory consuming and must be used with
                    609:   parcimony.
                    610:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    611: 
                    612:   Revision 1.83  2003/06/10 13:39:11  lievre
                    613:   *** empty log message ***
                    614: 
                    615:   Revision 1.82  2003/06/05 15:57:20  brouard
                    616:   Add log in  imach.c and  fullversion number is now printed.
                    617: 
                    618: */
                    619: /*
                    620:    Interpolated Markov Chain
                    621: 
                    622:   Short summary of the programme:
                    623:   
                    624:   This program computes Healthy Life Expectancies from
                    625:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    626:   first survey ("cross") where individuals from different ages are
                    627:   interviewed on their health status or degree of disability (in the
                    628:   case of a health survey which is our main interest) -2- at least a
                    629:   second wave of interviews ("longitudinal") which measure each change
                    630:   (if any) in individual health status.  Health expectancies are
                    631:   computed from the time spent in each health state according to a
                    632:   model. More health states you consider, more time is necessary to reach the
                    633:   Maximum Likelihood of the parameters involved in the model.  The
                    634:   simplest model is the multinomial logistic model where pij is the
                    635:   probability to be observed in state j at the second wave
                    636:   conditional to be observed in state i at the first wave. Therefore
                    637:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    638:   'age' is age and 'sex' is a covariate. If you want to have a more
                    639:   complex model than "constant and age", you should modify the program
                    640:   where the markup *Covariates have to be included here again* invites
                    641:   you to do it.  More covariates you add, slower the
                    642:   convergence.
                    643: 
                    644:   The advantage of this computer programme, compared to a simple
                    645:   multinomial logistic model, is clear when the delay between waves is not
                    646:   identical for each individual. Also, if a individual missed an
                    647:   intermediate interview, the information is lost, but taken into
                    648:   account using an interpolation or extrapolation.  
                    649: 
                    650:   hPijx is the probability to be observed in state i at age x+h
                    651:   conditional to the observed state i at age x. The delay 'h' can be
                    652:   split into an exact number (nh*stepm) of unobserved intermediate
                    653:   states. This elementary transition (by month, quarter,
                    654:   semester or year) is modelled as a multinomial logistic.  The hPx
                    655:   matrix is simply the matrix product of nh*stepm elementary matrices
                    656:   and the contribution of each individual to the likelihood is simply
                    657:   hPijx.
                    658: 
                    659:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   660:   of the life expectancies. It also computes the period (stable) prevalence.
                    661: 
                    662: Back prevalence and projections:
                    663:  - 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)
                    664:     Computes the back prevalence limit  for any combination    of covariate values k
                    665:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    666:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    667:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    668:    Computes for any combination of covariates k and any age between bage and fage 
                    669:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    670:                        oldm=oldms;savm=savms;
                    671:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    672:      Computes the transition matrix starting at age 'age' over
                    673:      'nhstepm*hstepm*stepm' months (i.e. until
                    674:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    675:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    676:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    677:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    678: 
1.133     brouard   679:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    680:            Institut national d'études démographiques, Paris.
1.126     brouard   681:   This software have been partly granted by Euro-REVES, a concerted action
                    682:   from the European Union.
                    683:   It is copyrighted identically to a GNU software product, ie programme and
                    684:   software can be distributed freely for non commercial use. Latest version
                    685:   can be accessed at http://euroreves.ined.fr/imach .
                    686: 
                    687:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    688:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    689:   
                    690:   **********************************************************************/
                    691: /*
                    692:   main
                    693:   read parameterfile
                    694:   read datafile
                    695:   concatwav
                    696:   freqsummary
                    697:   if (mle >= 1)
                    698:     mlikeli
                    699:   print results files
                    700:   if mle==1 
                    701:      computes hessian
                    702:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    703:       begin-prev-date,...
                    704:   open gnuplot file
                    705:   open html file
1.145     brouard   706:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    707:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    708:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    709:     freexexit2 possible for memory heap.
                    710: 
                    711:   h Pij x                         | pij_nom  ficrestpij
                    712:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    713:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    714:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    715: 
                    716:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    717:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    718:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    719:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    720:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    721: 
1.126     brouard   722:   forecasting if prevfcast==1 prevforecast call prevalence()
                    723:   health expectancies
                    724:   Variance-covariance of DFLE
                    725:   prevalence()
                    726:    movingaverage()
                    727:   varevsij() 
                    728:   if popbased==1 varevsij(,popbased)
                    729:   total life expectancies
                    730:   Variance of period (stable) prevalence
                    731:  end
                    732: */
                    733: 
1.187     brouard   734: /* #define DEBUG */
                    735: /* #define DEBUGBRENT */
1.203     brouard   736: /* #define DEBUGLINMIN */
                    737: /* #define DEBUGHESS */
                    738: #define DEBUGHESSIJ
1.220     brouard   739: #define LINMINORIGINAL  /* Don't use loop on scale in linmin (accepting nan)*/
1.165     brouard   740: #define POWELL /* Instead of NLOPT */
1.192     brouard   741: #define POWELLF1F3 /* Skip test */
1.186     brouard   742: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    743: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   744: 
                    745: #include <math.h>
                    746: #include <stdio.h>
                    747: #include <stdlib.h>
                    748: #include <string.h>
1.159     brouard   749: 
                    750: #ifdef _WIN32
                    751: #include <io.h>
1.172     brouard   752: #include <windows.h>
                    753: #include <tchar.h>
1.159     brouard   754: #else
1.126     brouard   755: #include <unistd.h>
1.159     brouard   756: #endif
1.126     brouard   757: 
                    758: #include <limits.h>
                    759: #include <sys/types.h>
1.171     brouard   760: 
                    761: #if defined(__GNUC__)
                    762: #include <sys/utsname.h> /* Doesn't work on Windows */
                    763: #endif
                    764: 
1.126     brouard   765: #include <sys/stat.h>
                    766: #include <errno.h>
1.159     brouard   767: /* extern int errno; */
1.126     brouard   768: 
1.157     brouard   769: /* #ifdef LINUX */
                    770: /* #include <time.h> */
                    771: /* #include "timeval.h" */
                    772: /* #else */
                    773: /* #include <sys/time.h> */
                    774: /* #endif */
                    775: 
1.126     brouard   776: #include <time.h>
                    777: 
1.136     brouard   778: #ifdef GSL
                    779: #include <gsl/gsl_errno.h>
                    780: #include <gsl/gsl_multimin.h>
                    781: #endif
                    782: 
1.167     brouard   783: 
1.162     brouard   784: #ifdef NLOPT
                    785: #include <nlopt.h>
                    786: typedef struct {
                    787:   double (* function)(double [] );
                    788: } myfunc_data ;
                    789: #endif
                    790: 
1.126     brouard   791: /* #include <libintl.h> */
                    792: /* #define _(String) gettext (String) */
                    793: 
1.141     brouard   794: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   795: 
                    796: #define GNUPLOTPROGRAM "gnuplot"
                    797: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    798: #define FILENAMELENGTH 132
                    799: 
                    800: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    801: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    802: 
1.144     brouard   803: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    804: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   805: 
                    806: #define NINTERVMAX 8
1.144     brouard   807: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    808: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    809: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   810: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   811: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    812: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   813: #define MAXN 20000
1.144     brouard   814: #define YEARM 12. /**< Number of months per year */
1.218     brouard   815: /* #define AGESUP 130 */
                    816: #define AGESUP 150
                    817: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   818: #define AGEBASE 40
1.194     brouard   819: #define AGEOVERFLOW 1.e20
1.164     brouard   820: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   821: #ifdef _WIN32
                    822: #define DIRSEPARATOR '\\'
                    823: #define CHARSEPARATOR "\\"
                    824: #define ODIRSEPARATOR '/'
                    825: #else
1.126     brouard   826: #define DIRSEPARATOR '/'
                    827: #define CHARSEPARATOR "/"
                    828: #define ODIRSEPARATOR '\\'
                    829: #endif
                    830: 
1.220     brouard   831: /* $Id: imach.c,v 1.219 2016/02/15 00:48:12 brouard Exp $ */
1.126     brouard   832: /* $State: Exp $ */
1.196     brouard   833: #include "version.h"
                    834: char version[]=__IMACH_VERSION__;
1.204     brouard   835: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.220     brouard   836: char fullversion[]="$Revision: 1.219 $ $Date: 2016/02/15 00:48:12 $"; 
1.126     brouard   837: char strstart[80];
                    838: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   839: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   840: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   841: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    842: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    843: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    844: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    845: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    846: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    847: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    848: int cptcov=0; /* Working variable */
1.218     brouard   849: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   850: int npar=NPARMAX;
                    851: int nlstate=2; /* Number of live states */
                    852: int ndeath=1; /* Number of dead states */
1.130     brouard   853: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   854: int popbased=0;
                    855: 
                    856: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   857: int maxwav=0; /* Maxim number of waves */
                    858: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    859: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    860: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   861:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   862: int mle=1, weightopt=0;
1.126     brouard   863: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    864: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    865: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    866:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   867: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   868: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   869: double **matprod2(); /* test */
1.126     brouard   870: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    871: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   872: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    873: 
1.136     brouard   874: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   875: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   876: FILE *ficlog, *ficrespow;
1.130     brouard   877: int globpr=0; /* Global variable for printing or not */
1.126     brouard   878: double fretone; /* Only one call to likelihood */
1.130     brouard   879: long ipmx=0; /* Number of contributions */
1.126     brouard   880: double sw; /* Sum of weights */
                    881: char filerespow[FILENAMELENGTH];
                    882: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    883: FILE *ficresilk;
                    884: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    885: FILE *ficresprobmorprev;
                    886: FILE *fichtm, *fichtmcov; /* Html File */
                    887: FILE *ficreseij;
                    888: char filerese[FILENAMELENGTH];
                    889: FILE *ficresstdeij;
                    890: char fileresstde[FILENAMELENGTH];
                    891: FILE *ficrescveij;
                    892: char filerescve[FILENAMELENGTH];
                    893: FILE  *ficresvij;
                    894: char fileresv[FILENAMELENGTH];
                    895: FILE  *ficresvpl;
                    896: char fileresvpl[FILENAMELENGTH];
                    897: char title[MAXLINE];
1.217     brouard   898: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   899: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    900: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    901: char command[FILENAMELENGTH];
                    902: int  outcmd=0;
                    903: 
1.217     brouard   904: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   905: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   906: char filelog[FILENAMELENGTH]; /* Log file */
                    907: char filerest[FILENAMELENGTH];
                    908: char fileregp[FILENAMELENGTH];
                    909: char popfile[FILENAMELENGTH];
                    910: 
                    911: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    912: 
1.157     brouard   913: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    914: /* struct timezone tzp; */
                    915: /* extern int gettimeofday(); */
                    916: struct tm tml, *gmtime(), *localtime();
                    917: 
                    918: extern time_t time();
                    919: 
                    920: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    921: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    922: struct tm tm;
                    923: 
1.126     brouard   924: char strcurr[80], strfor[80];
                    925: 
                    926: char *endptr;
                    927: long lval;
                    928: double dval;
                    929: 
                    930: #define NR_END 1
                    931: #define FREE_ARG char*
                    932: #define FTOL 1.0e-10
                    933: 
                    934: #define NRANSI 
                    935: #define ITMAX 200 
                    936: 
                    937: #define TOL 2.0e-4 
                    938: 
                    939: #define CGOLD 0.3819660 
                    940: #define ZEPS 1.0e-10 
                    941: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    942: 
                    943: #define GOLD 1.618034 
                    944: #define GLIMIT 100.0 
                    945: #define TINY 1.0e-20 
                    946: 
                    947: static double maxarg1,maxarg2;
                    948: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    949: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    950:   
                    951: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    952: #define rint(a) floor(a+0.5)
1.166     brouard   953: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   954: #define mytinydouble 1.0e-16
1.166     brouard   955: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    956: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    957: /* static double dsqrarg; */
                    958: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   959: static double sqrarg;
                    960: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    961: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    962: int agegomp= AGEGOMP;
                    963: 
                    964: int imx; 
                    965: int stepm=1;
                    966: /* Stepm, step in month: minimum step interpolation*/
                    967: 
                    968: int estepm;
                    969: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    970: 
                    971: int m,nb;
                    972: long *num;
1.197     brouard   973: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   974: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    975:                   covariate for which somebody answered excluding 
                    976:                   undefined. Usually 2: 0 and 1. */
                    977: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    978:                             covariate for which somebody answered including 
                    979:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   980: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard   981: double **pmmij, ***probs; /* Global pointer */
1.219     brouard   982: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard   983: double *ageexmed,*agecens;
                    984: double dateintmean=0;
                    985: 
                    986: double *weight;
                    987: int **s; /* Status */
1.141     brouard   988: double *agedc;
1.145     brouard   989: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   990:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   991:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   992: double  idx; 
                    993: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   994: int *Tage;
1.145     brouard   995: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   996: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.220     brouard   997: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard   998: double *lsurv, *lpop, *tpop;
                    999: 
1.143     brouard  1000: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1001: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1002: 
                   1003: /**************** split *************************/
                   1004: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1005: {
                   1006:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1007:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1008:   */ 
                   1009:   char *ss;                            /* pointer */
1.186     brouard  1010:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1011: 
                   1012:   l1 = strlen(path );                  /* length of path */
                   1013:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1014:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1015:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1016:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1017:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1018:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1019:     /* get current working directory */
                   1020:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1021: #ifdef WIN32
                   1022:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1023: #else
                   1024:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1025: #endif
1.126     brouard  1026:       return( GLOCK_ERROR_GETCWD );
                   1027:     }
                   1028:     /* got dirc from getcwd*/
                   1029:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1030:   } else {                             /* strip directory from path */
1.126     brouard  1031:     ss++;                              /* after this, the filename */
                   1032:     l2 = strlen( ss );                 /* length of filename */
                   1033:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1034:     strcpy( name, ss );                /* save file name */
                   1035:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1036:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1037:     printf(" DIRC2 = %s \n",dirc);
                   1038:   }
                   1039:   /* We add a separator at the end of dirc if not exists */
                   1040:   l1 = strlen( dirc );                 /* length of directory */
                   1041:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1042:     dirc[l1] =  DIRSEPARATOR;
                   1043:     dirc[l1+1] = 0; 
                   1044:     printf(" DIRC3 = %s \n",dirc);
                   1045:   }
                   1046:   ss = strrchr( name, '.' );           /* find last / */
                   1047:   if (ss >0){
                   1048:     ss++;
                   1049:     strcpy(ext,ss);                    /* save extension */
                   1050:     l1= strlen( name);
                   1051:     l2= strlen(ss)+1;
                   1052:     strncpy( finame, name, l1-l2);
                   1053:     finame[l1-l2]= 0;
                   1054:   }
                   1055: 
                   1056:   return( 0 );                         /* we're done */
                   1057: }
                   1058: 
                   1059: 
                   1060: /******************************************/
                   1061: 
                   1062: void replace_back_to_slash(char *s, char*t)
                   1063: {
                   1064:   int i;
                   1065:   int lg=0;
                   1066:   i=0;
                   1067:   lg=strlen(t);
                   1068:   for(i=0; i<= lg; i++) {
                   1069:     (s[i] = t[i]);
                   1070:     if (t[i]== '\\') s[i]='/';
                   1071:   }
                   1072: }
                   1073: 
1.132     brouard  1074: char *trimbb(char *out, char *in)
1.137     brouard  1075: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1076:   char *s;
                   1077:   s=out;
                   1078:   while (*in != '\0'){
1.137     brouard  1079:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1080:       in++;
                   1081:     }
                   1082:     *out++ = *in++;
                   1083:   }
                   1084:   *out='\0';
                   1085:   return s;
                   1086: }
                   1087: 
1.187     brouard  1088: /* char *substrchaine(char *out, char *in, char *chain) */
                   1089: /* { */
                   1090: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1091: /*   char *s, *t; */
                   1092: /*   t=in;s=out; */
                   1093: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1094: /*     *out++ = *in++; */
                   1095: /*   } */
                   1096: 
                   1097: /*   /\* *in matches *chain *\/ */
                   1098: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1099: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1100: /*   } */
                   1101: /*   in--; chain--; */
                   1102: /*   while ( (*in != '\0')){ */
                   1103: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1104: /*     *out++ = *in++; */
                   1105: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1106: /*   } */
                   1107: /*   *out='\0'; */
                   1108: /*   out=s; */
                   1109: /*   return out; */
                   1110: /* } */
                   1111: char *substrchaine(char *out, char *in, char *chain)
                   1112: {
                   1113:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1114:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1115: 
                   1116:   char *strloc;
                   1117: 
                   1118:   strcpy (out, in); 
                   1119:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1120:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1121:   if(strloc != NULL){ 
                   1122:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1123:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1124:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1125:   }
                   1126:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1127:   return out;
                   1128: }
                   1129: 
                   1130: 
1.145     brouard  1131: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1132: {
1.187     brouard  1133:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1134:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1135:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1136:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1137:   */
1.160     brouard  1138:   char *s, *t;
1.145     brouard  1139:   t=in;s=in;
                   1140:   while ((*in != occ) && (*in != '\0')){
                   1141:     *alocc++ = *in++;
                   1142:   }
                   1143:   if( *in == occ){
                   1144:     *(alocc)='\0';
                   1145:     s=++in;
                   1146:   }
                   1147:  
                   1148:   if (s == t) {/* occ not found */
                   1149:     *(alocc-(in-s))='\0';
                   1150:     in=s;
                   1151:   }
                   1152:   while ( *in != '\0'){
                   1153:     *blocc++ = *in++;
                   1154:   }
                   1155: 
                   1156:   *blocc='\0';
                   1157:   return t;
                   1158: }
1.137     brouard  1159: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1160: {
1.187     brouard  1161:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1162:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1163:      gives blocc="abcdef2ghi" and alocc="j".
                   1164:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1165:   */
                   1166:   char *s, *t;
                   1167:   t=in;s=in;
                   1168:   while (*in != '\0'){
                   1169:     while( *in == occ){
                   1170:       *blocc++ = *in++;
                   1171:       s=in;
                   1172:     }
                   1173:     *blocc++ = *in++;
                   1174:   }
                   1175:   if (s == t) /* occ not found */
                   1176:     *(blocc-(in-s))='\0';
                   1177:   else
                   1178:     *(blocc-(in-s)-1)='\0';
                   1179:   in=s;
                   1180:   while ( *in != '\0'){
                   1181:     *alocc++ = *in++;
                   1182:   }
                   1183: 
                   1184:   *alocc='\0';
                   1185:   return s;
                   1186: }
                   1187: 
1.126     brouard  1188: int nbocc(char *s, char occ)
                   1189: {
                   1190:   int i,j=0;
                   1191:   int lg=20;
                   1192:   i=0;
                   1193:   lg=strlen(s);
                   1194:   for(i=0; i<= lg; i++) {
                   1195:   if  (s[i] == occ ) j++;
                   1196:   }
                   1197:   return j;
                   1198: }
                   1199: 
1.137     brouard  1200: /* void cutv(char *u,char *v, char*t, char occ) */
                   1201: /* { */
                   1202: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1203: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1204: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1205: /*   int i,lg,j,p=0; */
                   1206: /*   i=0; */
                   1207: /*   lg=strlen(t); */
                   1208: /*   for(j=0; j<=lg-1; j++) { */
                   1209: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1210: /*   } */
1.126     brouard  1211: 
1.137     brouard  1212: /*   for(j=0; j<p; j++) { */
                   1213: /*     (u[j] = t[j]); */
                   1214: /*   } */
                   1215: /*      u[p]='\0'; */
1.126     brouard  1216: 
1.137     brouard  1217: /*    for(j=0; j<= lg; j++) { */
                   1218: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1219: /*   } */
                   1220: /* } */
1.126     brouard  1221: 
1.160     brouard  1222: #ifdef _WIN32
                   1223: char * strsep(char **pp, const char *delim)
                   1224: {
                   1225:   char *p, *q;
                   1226:          
                   1227:   if ((p = *pp) == NULL)
                   1228:     return 0;
                   1229:   if ((q = strpbrk (p, delim)) != NULL)
                   1230:   {
                   1231:     *pp = q + 1;
                   1232:     *q = '\0';
                   1233:   }
                   1234:   else
                   1235:     *pp = 0;
                   1236:   return p;
                   1237: }
                   1238: #endif
                   1239: 
1.126     brouard  1240: /********************** nrerror ********************/
                   1241: 
                   1242: void nrerror(char error_text[])
                   1243: {
                   1244:   fprintf(stderr,"ERREUR ...\n");
                   1245:   fprintf(stderr,"%s\n",error_text);
                   1246:   exit(EXIT_FAILURE);
                   1247: }
                   1248: /*********************** vector *******************/
                   1249: double *vector(int nl, int nh)
                   1250: {
                   1251:   double *v;
                   1252:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1253:   if (!v) nrerror("allocation failure in vector");
                   1254:   return v-nl+NR_END;
                   1255: }
                   1256: 
                   1257: /************************ free vector ******************/
                   1258: void free_vector(double*v, int nl, int nh)
                   1259: {
                   1260:   free((FREE_ARG)(v+nl-NR_END));
                   1261: }
                   1262: 
                   1263: /************************ivector *******************************/
                   1264: int *ivector(long nl,long nh)
                   1265: {
                   1266:   int *v;
                   1267:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1268:   if (!v) nrerror("allocation failure in ivector");
                   1269:   return v-nl+NR_END;
                   1270: }
                   1271: 
                   1272: /******************free ivector **************************/
                   1273: void free_ivector(int *v, long nl, long nh)
                   1274: {
                   1275:   free((FREE_ARG)(v+nl-NR_END));
                   1276: }
                   1277: 
                   1278: /************************lvector *******************************/
                   1279: long *lvector(long nl,long nh)
                   1280: {
                   1281:   long *v;
                   1282:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1283:   if (!v) nrerror("allocation failure in ivector");
                   1284:   return v-nl+NR_END;
                   1285: }
                   1286: 
                   1287: /******************free lvector **************************/
                   1288: void free_lvector(long *v, long nl, long nh)
                   1289: {
                   1290:   free((FREE_ARG)(v+nl-NR_END));
                   1291: }
                   1292: 
                   1293: /******************* imatrix *******************************/
                   1294: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1295:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1296: { 
                   1297:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1298:   int **m; 
                   1299:   
                   1300:   /* allocate pointers to rows */ 
                   1301:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1302:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1303:   m += NR_END; 
                   1304:   m -= nrl; 
                   1305:   
                   1306:   
                   1307:   /* allocate rows and set pointers to them */ 
                   1308:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1309:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1310:   m[nrl] += NR_END; 
                   1311:   m[nrl] -= ncl; 
                   1312:   
                   1313:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1314:   
                   1315:   /* return pointer to array of pointers to rows */ 
                   1316:   return m; 
                   1317: } 
                   1318: 
                   1319: /****************** free_imatrix *************************/
                   1320: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1321:       int **m;
                   1322:       long nch,ncl,nrh,nrl; 
                   1323:      /* free an int matrix allocated by imatrix() */ 
                   1324: { 
                   1325:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1326:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1327: } 
                   1328: 
                   1329: /******************* matrix *******************************/
                   1330: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1331: {
                   1332:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1333:   double **m;
                   1334: 
                   1335:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1336:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1337:   m += NR_END;
                   1338:   m -= nrl;
                   1339: 
                   1340:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1341:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1342:   m[nrl] += NR_END;
                   1343:   m[nrl] -= ncl;
                   1344: 
                   1345:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1346:   return m;
1.145     brouard  1347:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1348: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1349: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1350:    */
                   1351: }
                   1352: 
                   1353: /*************************free matrix ************************/
                   1354: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1355: {
                   1356:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1357:   free((FREE_ARG)(m+nrl-NR_END));
                   1358: }
                   1359: 
                   1360: /******************* ma3x *******************************/
                   1361: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1362: {
                   1363:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1364:   double ***m;
                   1365: 
                   1366:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1367:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1368:   m += NR_END;
                   1369:   m -= nrl;
                   1370: 
                   1371:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1372:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1373:   m[nrl] += NR_END;
                   1374:   m[nrl] -= ncl;
                   1375: 
                   1376:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1377: 
                   1378:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1379:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1380:   m[nrl][ncl] += NR_END;
                   1381:   m[nrl][ncl] -= nll;
                   1382:   for (j=ncl+1; j<=nch; j++) 
                   1383:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1384:   
                   1385:   for (i=nrl+1; i<=nrh; i++) {
                   1386:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1387:     for (j=ncl+1; j<=nch; j++) 
                   1388:       m[i][j]=m[i][j-1]+nlay;
                   1389:   }
                   1390:   return m; 
                   1391:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1392:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1393:   */
                   1394: }
                   1395: 
                   1396: /*************************free ma3x ************************/
                   1397: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1398: {
                   1399:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1400:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1401:   free((FREE_ARG)(m+nrl-NR_END));
                   1402: }
                   1403: 
                   1404: /*************** function subdirf ***********/
                   1405: char *subdirf(char fileres[])
                   1406: {
                   1407:   /* Caution optionfilefiname is hidden */
                   1408:   strcpy(tmpout,optionfilefiname);
                   1409:   strcat(tmpout,"/"); /* Add to the right */
                   1410:   strcat(tmpout,fileres);
                   1411:   return tmpout;
                   1412: }
                   1413: 
                   1414: /*************** function subdirf2 ***********/
                   1415: char *subdirf2(char fileres[], char *preop)
                   1416: {
                   1417:   
                   1418:   /* Caution optionfilefiname is hidden */
                   1419:   strcpy(tmpout,optionfilefiname);
                   1420:   strcat(tmpout,"/");
                   1421:   strcat(tmpout,preop);
                   1422:   strcat(tmpout,fileres);
                   1423:   return tmpout;
                   1424: }
                   1425: 
                   1426: /*************** function subdirf3 ***********/
                   1427: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1428: {
                   1429:   
                   1430:   /* Caution optionfilefiname is hidden */
                   1431:   strcpy(tmpout,optionfilefiname);
                   1432:   strcat(tmpout,"/");
                   1433:   strcat(tmpout,preop);
                   1434:   strcat(tmpout,preop2);
                   1435:   strcat(tmpout,fileres);
                   1436:   return tmpout;
                   1437: }
1.213     brouard  1438:  
                   1439: /*************** function subdirfext ***********/
                   1440: char *subdirfext(char fileres[], char *preop, char *postop)
                   1441: {
                   1442:   
                   1443:   strcpy(tmpout,preop);
                   1444:   strcat(tmpout,fileres);
                   1445:   strcat(tmpout,postop);
                   1446:   return tmpout;
                   1447: }
1.126     brouard  1448: 
1.213     brouard  1449: /*************** function subdirfext3 ***********/
                   1450: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1451: {
                   1452:   
                   1453:   /* Caution optionfilefiname is hidden */
                   1454:   strcpy(tmpout,optionfilefiname);
                   1455:   strcat(tmpout,"/");
                   1456:   strcat(tmpout,preop);
                   1457:   strcat(tmpout,fileres);
                   1458:   strcat(tmpout,postop);
                   1459:   return tmpout;
                   1460: }
                   1461:  
1.162     brouard  1462: char *asc_diff_time(long time_sec, char ascdiff[])
                   1463: {
                   1464:   long sec_left, days, hours, minutes;
                   1465:   days = (time_sec) / (60*60*24);
                   1466:   sec_left = (time_sec) % (60*60*24);
                   1467:   hours = (sec_left) / (60*60) ;
                   1468:   sec_left = (sec_left) %(60*60);
                   1469:   minutes = (sec_left) /60;
                   1470:   sec_left = (sec_left) % (60);
                   1471:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1472:   return ascdiff;
                   1473: }
                   1474: 
1.126     brouard  1475: /***************** f1dim *************************/
                   1476: extern int ncom; 
                   1477: extern double *pcom,*xicom;
                   1478: extern double (*nrfunc)(double []); 
                   1479:  
                   1480: double f1dim(double x) 
                   1481: { 
                   1482:   int j; 
                   1483:   double f;
                   1484:   double *xt; 
                   1485:  
                   1486:   xt=vector(1,ncom); 
                   1487:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1488:   f=(*nrfunc)(xt); 
                   1489:   free_vector(xt,1,ncom); 
                   1490:   return f; 
                   1491: } 
                   1492: 
                   1493: /*****************brent *************************/
                   1494: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1495: {
                   1496:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1497:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1498:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1499:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1500:    * returned function value. 
                   1501:   */
1.126     brouard  1502:   int iter; 
                   1503:   double a,b,d,etemp;
1.159     brouard  1504:   double fu=0,fv,fw,fx;
1.164     brouard  1505:   double ftemp=0.;
1.126     brouard  1506:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1507:   double e=0.0; 
                   1508:  
                   1509:   a=(ax < cx ? ax : cx); 
                   1510:   b=(ax > cx ? ax : cx); 
                   1511:   x=w=v=bx; 
                   1512:   fw=fv=fx=(*f)(x); 
                   1513:   for (iter=1;iter<=ITMAX;iter++) { 
                   1514:     xm=0.5*(a+b); 
                   1515:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1516:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1517:     printf(".");fflush(stdout);
                   1518:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1519: #ifdef DEBUGBRENT
1.126     brouard  1520:     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);
                   1521:     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);
                   1522:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1523: #endif
                   1524:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1525:       *xmin=x; 
                   1526:       return fx; 
                   1527:     } 
                   1528:     ftemp=fu;
                   1529:     if (fabs(e) > tol1) { 
                   1530:       r=(x-w)*(fx-fv); 
                   1531:       q=(x-v)*(fx-fw); 
                   1532:       p=(x-v)*q-(x-w)*r; 
                   1533:       q=2.0*(q-r); 
                   1534:       if (q > 0.0) p = -p; 
                   1535:       q=fabs(q); 
                   1536:       etemp=e; 
                   1537:       e=d; 
                   1538:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1539:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1540:       else { 
                   1541:        d=p/q; 
                   1542:        u=x+d; 
                   1543:        if (u-a < tol2 || b-u < tol2) 
                   1544:          d=SIGN(tol1,xm-x); 
                   1545:       } 
                   1546:     } else { 
                   1547:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1548:     } 
                   1549:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1550:     fu=(*f)(u); 
                   1551:     if (fu <= fx) { 
                   1552:       if (u >= x) a=x; else b=x; 
                   1553:       SHFT(v,w,x,u) 
1.183     brouard  1554:       SHFT(fv,fw,fx,fu) 
                   1555:     } else { 
                   1556:       if (u < x) a=u; else b=u; 
                   1557:       if (fu <= fw || w == x) { 
                   1558:        v=w; 
                   1559:        w=u; 
                   1560:        fv=fw; 
                   1561:        fw=fu; 
                   1562:       } else if (fu <= fv || v == x || v == w) { 
                   1563:        v=u; 
                   1564:        fv=fu; 
                   1565:       } 
                   1566:     } 
1.126     brouard  1567:   } 
                   1568:   nrerror("Too many iterations in brent"); 
                   1569:   *xmin=x; 
                   1570:   return fx; 
                   1571: } 
                   1572: 
                   1573: /****************** mnbrak ***********************/
                   1574: 
                   1575: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1576:            double (*func)(double)) 
1.183     brouard  1577: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1578: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1579: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1580: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1581:    */
1.126     brouard  1582:   double ulim,u,r,q, dum;
                   1583:   double fu; 
1.187     brouard  1584: 
                   1585:   double scale=10.;
                   1586:   int iterscale=0;
                   1587: 
                   1588:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1589:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1590: 
                   1591: 
                   1592:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1593:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1594:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1595:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1596:   /* } */
                   1597: 
1.126     brouard  1598:   if (*fb > *fa) { 
                   1599:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1600:     SHFT(dum,*fb,*fa,dum) 
                   1601:   } 
1.126     brouard  1602:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1603:   *fc=(*func)(*cx); 
1.183     brouard  1604: #ifdef DEBUG
                   1605:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1606:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1607: #endif
                   1608:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1609:     r=(*bx-*ax)*(*fb-*fc); 
                   1610:     q=(*bx-*cx)*(*fb-*fa); 
                   1611:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1612:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1613:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1614:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1615:       fu=(*func)(u); 
1.163     brouard  1616: #ifdef DEBUG
                   1617:       /* f(x)=A(x-u)**2+f(u) */
                   1618:       double A, fparabu; 
                   1619:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1620:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1621:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1622:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1.183     brouard  1623:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1624:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1625:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1626:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1627: #endif 
1.184     brouard  1628: #ifdef MNBRAKORIGINAL
1.183     brouard  1629: #else
1.191     brouard  1630: /*       if (fu > *fc) { */
                   1631: /* #ifdef DEBUG */
                   1632: /*       printf("mnbrak4  fu > fc \n"); */
                   1633: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1634: /* #endif */
                   1635: /*     /\* 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 *\\/  *\/ */
                   1636: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1637: /*     dum=u; /\* Shifting c and u *\/ */
                   1638: /*     u = *cx; */
                   1639: /*     *cx = dum; */
                   1640: /*     dum = fu; */
                   1641: /*     fu = *fc; */
                   1642: /*     *fc =dum; */
                   1643: /*       } else { /\* end *\/ */
                   1644: /* #ifdef DEBUG */
                   1645: /*       printf("mnbrak3  fu < fc \n"); */
                   1646: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1647: /* #endif */
                   1648: /*     dum=u; /\* Shifting c and u *\/ */
                   1649: /*     u = *cx; */
                   1650: /*     *cx = dum; */
                   1651: /*     dum = fu; */
                   1652: /*     fu = *fc; */
                   1653: /*     *fc =dum; */
                   1654: /*       } */
1.183     brouard  1655: #ifdef DEBUG
1.191     brouard  1656:       printf("mnbrak34  fu < or >= fc \n");
                   1657:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1658: #endif
1.191     brouard  1659:       dum=u; /* Shifting c and u */
                   1660:       u = *cx;
                   1661:       *cx = dum;
                   1662:       dum = fu;
                   1663:       fu = *fc;
                   1664:       *fc =dum;
1.183     brouard  1665: #endif
1.162     brouard  1666:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1667: #ifdef DEBUG
                   1668:       printf("mnbrak2  u after c but before ulim\n");
                   1669:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1670: #endif
1.126     brouard  1671:       fu=(*func)(u); 
                   1672:       if (fu < *fc) { 
1.183     brouard  1673: #ifdef DEBUG
                   1674:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1675:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1676: #endif
1.126     brouard  1677:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1678:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1679:       } 
1.162     brouard  1680:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1681: #ifdef DEBUG
                   1682:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1683:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1684: #endif
1.126     brouard  1685:       u=ulim; 
                   1686:       fu=(*func)(u); 
1.183     brouard  1687:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1688: #ifdef DEBUG
                   1689:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1690:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1691: #endif
1.126     brouard  1692:       u=(*cx)+GOLD*(*cx-*bx); 
                   1693:       fu=(*func)(u); 
1.183     brouard  1694:     } /* end tests */
1.126     brouard  1695:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1696:     SHFT(*fa,*fb,*fc,fu) 
                   1697: #ifdef DEBUG
                   1698:       printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1699:       fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1700: #endif
                   1701:   } /* 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  1702: } 
                   1703: 
                   1704: /*************** linmin ************************/
1.162     brouard  1705: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1706: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1707: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1708: the value of func at the returned location p . This is actually all accomplished by calling the
                   1709: routines mnbrak and brent .*/
1.126     brouard  1710: int ncom; 
                   1711: double *pcom,*xicom;
                   1712: double (*nrfunc)(double []); 
                   1713:  
                   1714: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1715: { 
                   1716:   double brent(double ax, double bx, double cx, 
                   1717:               double (*f)(double), double tol, double *xmin); 
                   1718:   double f1dim(double x); 
                   1719:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1720:              double *fc, double (*func)(double)); 
                   1721:   int j; 
                   1722:   double xx,xmin,bx,ax; 
                   1723:   double fx,fb,fa;
1.187     brouard  1724: 
1.203     brouard  1725: #ifdef LINMINORIGINAL
                   1726: #else
                   1727:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1728: #endif
                   1729:   
1.126     brouard  1730:   ncom=n; 
                   1731:   pcom=vector(1,n); 
                   1732:   xicom=vector(1,n); 
                   1733:   nrfunc=func; 
                   1734:   for (j=1;j<=n;j++) { 
                   1735:     pcom[j]=p[j]; 
1.202     brouard  1736:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1737:   } 
1.187     brouard  1738: 
1.203     brouard  1739: #ifdef LINMINORIGINAL
                   1740:   xx=1.;
                   1741: #else
                   1742:   axs=0.0;
                   1743:   xxs=1.;
                   1744:   do{
                   1745:     xx= xxs;
                   1746: #endif
1.187     brouard  1747:     ax=0.;
                   1748:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1749:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1750:     /* 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))   */
                   1751:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1752:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1753:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1754:     /* 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  1755: #ifdef LINMINORIGINAL
                   1756: #else
                   1757:     if (fx != fx){
                   1758:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1759:        printf("|");
                   1760:        fprintf(ficlog,"|");
                   1761: #ifdef DEBUGLINMIN
                   1762:        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);
                   1763: #endif
                   1764:     }
                   1765:   }while(fx != fx);
                   1766: #endif
                   1767:   
1.191     brouard  1768: #ifdef DEBUGLINMIN
                   1769:   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  1770:   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  1771: #endif
1.187     brouard  1772:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1773:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1774:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1775:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1776:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1777: #ifdef DEBUG
                   1778:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1779:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1780: #endif
1.191     brouard  1781: #ifdef DEBUGLINMIN
                   1782:   printf("linmin end ");
1.202     brouard  1783:   fprintf(ficlog,"linmin end ");
1.191     brouard  1784: #endif
1.126     brouard  1785:   for (j=1;j<=n;j++) { 
1.203     brouard  1786: #ifdef LINMINORIGINAL
                   1787:     xi[j] *= xmin; 
                   1788: #else
                   1789: #ifdef DEBUGLINMIN
                   1790:     if(xxs <1.0)
                   1791:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1792: #endif
                   1793:     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) */
                   1794: #ifdef DEBUGLINMIN
                   1795:     if(xxs <1.0)
                   1796:       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 );
                   1797: #endif
                   1798: #endif
1.187     brouard  1799:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1800:   } 
1.191     brouard  1801: #ifdef DEBUGLINMIN
1.203     brouard  1802:   printf("\n");
1.191     brouard  1803:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1804:   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  1805:   for (j=1;j<=n;j++) { 
1.202     brouard  1806:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1807:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1808:     if(j % ncovmodel == 0){
1.191     brouard  1809:       printf("\n");
1.202     brouard  1810:       fprintf(ficlog,"\n");
                   1811:     }
1.191     brouard  1812:   }
1.203     brouard  1813: #else
1.191     brouard  1814: #endif
1.126     brouard  1815:   free_vector(xicom,1,n); 
                   1816:   free_vector(pcom,1,n); 
                   1817: } 
                   1818: 
                   1819: 
                   1820: /*************** powell ************************/
1.162     brouard  1821: /*
                   1822: Minimization of a function func of n variables. Input consists of an initial starting point
                   1823: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1824: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1825: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1826: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1827: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1828:  */
1.126     brouard  1829: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1830:            double (*func)(double [])) 
                   1831: { 
                   1832:   void linmin(double p[], double xi[], int n, double *fret, 
                   1833:              double (*func)(double [])); 
                   1834:   int i,ibig,j; 
                   1835:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1836:   double directest;
1.126     brouard  1837:   double fp,fptt;
                   1838:   double *xits;
                   1839:   int niterf, itmp;
                   1840: 
                   1841:   pt=vector(1,n); 
                   1842:   ptt=vector(1,n); 
                   1843:   xit=vector(1,n); 
                   1844:   xits=vector(1,n); 
                   1845:   *fret=(*func)(p); 
                   1846:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1847:   rcurr_time = time(NULL);  
1.126     brouard  1848:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1849:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1850:     ibig=0; 
                   1851:     del=0.0; 
1.157     brouard  1852:     rlast_time=rcurr_time;
                   1853:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1854:     rcurr_time = time(NULL);  
                   1855:     curr_time = *localtime(&rcurr_time);
                   1856:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1857:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1858: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1859:     for (i=1;i<=n;i++) {
1.126     brouard  1860:       printf(" %d %.12f",i, p[i]);
                   1861:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1862:       fprintf(ficrespow," %.12lf", p[i]);
                   1863:     }
                   1864:     printf("\n");
                   1865:     fprintf(ficlog,"\n");
                   1866:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1867:     if(*iter <=3){
1.157     brouard  1868:       tml = *localtime(&rcurr_time);
                   1869:       strcpy(strcurr,asctime(&tml));
                   1870:       rforecast_time=rcurr_time; 
1.126     brouard  1871:       itmp = strlen(strcurr);
                   1872:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1873:        strcurr[itmp-1]='\0';
1.162     brouard  1874:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1875:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1876:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1877:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1878:        forecast_time = *localtime(&rforecast_time);
                   1879:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1880:        itmp = strlen(strfor);
                   1881:        if(strfor[itmp-1]=='\n')
                   1882:        strfor[itmp-1]='\0';
1.157     brouard  1883:        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);
                   1884:        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  1885:       }
                   1886:     }
1.187     brouard  1887:     for (i=1;i<=n;i++) { /* For each direction i */
                   1888:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1889:       fptt=(*fret); 
                   1890: #ifdef DEBUG
1.203     brouard  1891:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1892:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1893: #endif
1.203     brouard  1894:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1895:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1896:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1897:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1898:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1899:        /* because that direction will be replaced unless the gain del is small */
                   1900:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1901:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1902:        /* with the new direction. */
1.126     brouard  1903:        del=fabs(fptt-(*fret)); 
                   1904:        ibig=i; 
                   1905:       } 
                   1906: #ifdef DEBUG
                   1907:       printf("%d %.12e",i,(*fret));
                   1908:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1909:       for (j=1;j<=n;j++) {
                   1910:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1911:        printf(" x(%d)=%.12e",j,xit[j]);
                   1912:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1913:       }
                   1914:       for(j=1;j<=n;j++) {
1.162     brouard  1915:        printf(" p(%d)=%.12e",j,p[j]);
                   1916:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1917:       }
                   1918:       printf("\n");
                   1919:       fprintf(ficlog,"\n");
                   1920: #endif
1.187     brouard  1921:     } /* end loop on each direction i */
                   1922:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1923:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1924:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1925:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1926:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1927:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1928:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1929:       /* decreased of more than 3.84  */
                   1930:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1931:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1932:       /* By adding 10 parameters more the gain should be 18.31 */
                   1933: 
                   1934:       /* Starting the program with initial values given by a former maximization will simply change */
                   1935:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1936:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1937:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1938: #ifdef DEBUG
                   1939:       int k[2],l;
                   1940:       k[0]=1;
                   1941:       k[1]=-1;
                   1942:       printf("Max: %.12e",(*func)(p));
                   1943:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1944:       for (j=1;j<=n;j++) {
                   1945:        printf(" %.12e",p[j]);
                   1946:        fprintf(ficlog," %.12e",p[j]);
                   1947:       }
                   1948:       printf("\n");
                   1949:       fprintf(ficlog,"\n");
                   1950:       for(l=0;l<=1;l++) {
                   1951:        for (j=1;j<=n;j++) {
                   1952:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1953:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1954:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1955:        }
                   1956:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1957:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1958:       }
                   1959: #endif
                   1960: 
                   1961: 
                   1962:       free_vector(xit,1,n); 
                   1963:       free_vector(xits,1,n); 
                   1964:       free_vector(ptt,1,n); 
                   1965:       free_vector(pt,1,n); 
                   1966:       return; 
1.192     brouard  1967:     } /* enough precision */ 
1.126     brouard  1968:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1969:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1970:       ptt[j]=2.0*p[j]-pt[j]; 
                   1971:       xit[j]=p[j]-pt[j]; 
                   1972:       pt[j]=p[j]; 
                   1973:     } 
1.181     brouard  1974:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1975: #ifdef POWELLF1F3
                   1976: #else
1.161     brouard  1977:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1978: #endif
1.162     brouard  1979:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1980:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1981:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1982:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1983:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1984:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1985:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1986: #ifdef NRCORIGINAL
                   1987:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1988: #else
                   1989:       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  1990:       t= t- del*SQR(fp-fptt);
1.183     brouard  1991: #endif
1.202     brouard  1992:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1993: #ifdef DEBUG
1.181     brouard  1994:       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);
                   1995:       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  1996:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1997:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1998:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1999:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2000:       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);
                   2001:       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);
                   2002: #endif
1.183     brouard  2003: #ifdef POWELLORIGINAL
                   2004:       if (t < 0.0) { /* Then we use it for new direction */
                   2005: #else
1.182     brouard  2006:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  2007:        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  2008:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202     brouard  2009:         fprintf(ficlog,"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  2010:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2011:       } 
1.181     brouard  2012:       if (directest < 0.0) { /* Then we use it for new direction */
                   2013: #endif
1.191     brouard  2014: #ifdef DEBUGLINMIN
                   2015:        printf("Before linmin in direction P%d-P0\n",n);
                   2016:        for (j=1;j<=n;j++) { 
1.202     brouard  2017:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2018:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2019:          if(j % ncovmodel == 0){
1.191     brouard  2020:            printf("\n");
1.202     brouard  2021:            fprintf(ficlog,"\n");
                   2022:          }
1.191     brouard  2023:        }
                   2024: #endif
1.187     brouard  2025:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  2026: #ifdef DEBUGLINMIN
                   2027:        for (j=1;j<=n;j++) { 
                   2028:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  2029:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2030:          if(j % ncovmodel == 0){
1.191     brouard  2031:            printf("\n");
1.202     brouard  2032:            fprintf(ficlog,"\n");
                   2033:          }
1.191     brouard  2034:        }
                   2035: #endif
1.126     brouard  2036:        for (j=1;j<=n;j++) { 
1.181     brouard  2037:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2038:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  2039:        }
1.181     brouard  2040:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2041:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2042: 
1.126     brouard  2043: #ifdef DEBUG
1.164     brouard  2044:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2045:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2046:        for(j=1;j<=n;j++){
                   2047:          printf(" %.12e",xit[j]);
                   2048:          fprintf(ficlog," %.12e",xit[j]);
                   2049:        }
                   2050:        printf("\n");
                   2051:        fprintf(ficlog,"\n");
                   2052: #endif
1.192     brouard  2053:       } /* end of t or directest negative */
                   2054: #ifdef POWELLF1F3
                   2055: #else
1.162     brouard  2056:     } /* end if (fptt < fp)  */
1.192     brouard  2057: #endif
                   2058:   } /* loop iteration */ 
1.126     brouard  2059: } 
                   2060: 
                   2061: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2062: 
1.203     brouard  2063: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2064: {
1.218     brouard  2065:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2066:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2067:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2068:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2069:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2070:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2071:   /* Initial matrix pimij */
                   2072:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2073:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2074:   /*  0,                   0                  , 1} */
                   2075:   /*
                   2076:    * and after some iteration: */
                   2077:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2078:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2079:   /*  0,                   0                  , 1} */
                   2080:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2081:   /* {0.51571254859325999, 0.4842874514067399, */
                   2082:   /*  0.51326036147820708, 0.48673963852179264} */
                   2083:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2084: 
1.126     brouard  2085:   int i, ii,j,k;
1.209     brouard  2086:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2087:   /* double **matprod2(); */ /* test */
1.218     brouard  2088:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2089:   double **newm;
1.209     brouard  2090:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2091:   int ncvloop=0;
1.169     brouard  2092:   
1.209     brouard  2093:   min=vector(1,nlstate);
                   2094:   max=vector(1,nlstate);
                   2095:   meandiff=vector(1,nlstate);
                   2096: 
1.218     brouard  2097:        /* Starting with matrix unity */
1.126     brouard  2098:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2099:     for (j=1;j<=nlstate+ndeath;j++){
                   2100:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2101:     }
1.169     brouard  2102:   
                   2103:   cov[1]=1.;
                   2104:   
                   2105:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2106:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2107:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2108:     ncvloop++;
1.126     brouard  2109:     newm=savm;
                   2110:     /* Covariates have to be included here again */
1.138     brouard  2111:     cov[2]=agefin;
1.187     brouard  2112:     if(nagesqr==1)
                   2113:       cov[3]= agefin*agefin;;
1.138     brouard  2114:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2115:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2116:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2117:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2118:       /* 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])]); */
1.138     brouard  2119:     }
1.186     brouard  2120:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2121:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2122:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2123:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2124:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2125:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2126:     
                   2127:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2128:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2129:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2130:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2131:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2132:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2133:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2134:     
1.126     brouard  2135:     savm=oldm;
                   2136:     oldm=newm;
1.209     brouard  2137: 
                   2138:     for(j=1; j<=nlstate; j++){
                   2139:       max[j]=0.;
                   2140:       min[j]=1.;
                   2141:     }
                   2142:     for(i=1;i<=nlstate;i++){
                   2143:       sumnew=0;
                   2144:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2145:       for(j=1; j<=nlstate; j++){ 
                   2146:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2147:        max[j]=FMAX(max[j],prlim[i][j]);
                   2148:        min[j]=FMIN(min[j],prlim[i][j]);
                   2149:       }
                   2150:     }
                   2151: 
1.126     brouard  2152:     maxmax=0.;
1.209     brouard  2153:     for(j=1; j<=nlstate; j++){
                   2154:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2155:       maxmax=FMAX(maxmax,meandiff[j]);
                   2156:       /* 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  2157:     } /* j loop */
1.203     brouard  2158:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2159:     /* 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  2160:     if(maxmax < ftolpl){
1.209     brouard  2161:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2162:       free_vector(min,1,nlstate);
                   2163:       free_vector(max,1,nlstate);
                   2164:       free_vector(meandiff,1,nlstate);
1.126     brouard  2165:       return prlim;
                   2166:     }
1.169     brouard  2167:   } /* age loop */
1.208     brouard  2168:     /* After some age loop it doesn't converge */
1.209     brouard  2169:   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  2170: 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  2171:   /* 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); */
                   2172:   free_vector(min,1,nlstate);
                   2173:   free_vector(max,1,nlstate);
                   2174:   free_vector(meandiff,1,nlstate);
1.208     brouard  2175:   
1.169     brouard  2176:   return prlim; /* should not reach here */
1.126     brouard  2177: }
                   2178: 
1.217     brouard  2179: 
                   2180:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2181: 
1.218     brouard  2182:  /* 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) */
                   2183:  /* 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) */
                   2184:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2185: {
1.218     brouard  2186:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2187:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2188:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2189:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2190:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2191:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2192:   /* Initial matrix pimij */
                   2193:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2194:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2195:   /*  0,                   0                  , 1} */
                   2196:   /*
                   2197:    * and after some iteration: */
                   2198:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2199:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2200:   /*  0,                   0                  , 1} */
                   2201:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2202:   /* {0.51571254859325999, 0.4842874514067399, */
                   2203:   /*  0.51326036147820708, 0.48673963852179264} */
                   2204:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2205: 
                   2206:   int i, ii,j,k;
                   2207:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2208:   /* double **matprod2(); */ /* test */
                   2209:   double **out, cov[NCOVMAX+1], **bmij();
                   2210:   double **newm;
1.218     brouard  2211:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2212:   double        **oldm, **savm;  /* for use */
                   2213: 
1.217     brouard  2214:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2215:   int ncvloop=0;
                   2216:   
                   2217:   min=vector(1,nlstate);
                   2218:   max=vector(1,nlstate);
                   2219:   meandiff=vector(1,nlstate);
                   2220: 
1.218     brouard  2221:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2222:        oldm=oldms; savm=savms;
                   2223: 
                   2224:        /* Starting with matrix unity */
                   2225:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2226:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2227:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2228:     }
                   2229:   
                   2230:   cov[1]=1.;
                   2231:   
                   2232:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2233:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2234:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2235:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2236:     ncvloop++;
1.218     brouard  2237:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2238:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2239:     /* Covariates have to be included here again */
                   2240:     cov[2]=agefin;
                   2241:     if(nagesqr==1)
                   2242:       cov[3]= agefin*agefin;;
                   2243:     for (k=1; k<=cptcovn;k++) {
                   2244:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2245:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2246:       /* 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])]); */
                   2247:     }
                   2248:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2249:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2250:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2251:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2252:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2253:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2254:     
                   2255:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2256:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2257:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2258:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2259:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2260:                /* ij should be linked to the correct index of cov */
                   2261:                /* age and covariate values ij are in 'cov', but we need to pass
                   2262:                 * ij for the observed prevalence at age and status and covariate
                   2263:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2264:                 */
                   2265:     /* 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 *\/ */
                   2266:     /* 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 *\/ */
                   2267:     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  2268:     savm=oldm;
                   2269:     oldm=newm;
                   2270:     for(j=1; j<=nlstate; j++){
                   2271:       max[j]=0.;
                   2272:       min[j]=1.;
                   2273:     }
                   2274:     for(j=1; j<=nlstate; j++){ 
                   2275:       for(i=1;i<=nlstate;i++){
1.218     brouard  2276:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2277:                                bprlim[i][j]= newm[i][j];
                   2278:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2279:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2280:       }
                   2281:     }
1.218     brouard  2282:                
1.217     brouard  2283:     maxmax=0.;
                   2284:     for(i=1; i<=nlstate; i++){
                   2285:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2286:       maxmax=FMAX(maxmax,meandiff[i]);
                   2287:       /* 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); */
                   2288:     } /* j loop */
                   2289:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2290:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2291:     if(maxmax < ftolpl){
1.220     brouard  2292:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2293:       free_vector(min,1,nlstate);
                   2294:       free_vector(max,1,nlstate);
                   2295:       free_vector(meandiff,1,nlstate);
                   2296:       return bprlim;
                   2297:     }
                   2298:   } /* age loop */
                   2299:     /* After some age loop it doesn't converge */
                   2300:   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\
                   2301: 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);
                   2302:   /* 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); */
                   2303:   free_vector(min,1,nlstate);
                   2304:   free_vector(max,1,nlstate);
                   2305:   free_vector(meandiff,1,nlstate);
                   2306:   
                   2307:   return bprlim; /* should not reach here */
                   2308: }
                   2309: 
1.126     brouard  2310: /*************** transition probabilities ***************/ 
                   2311: 
                   2312: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2313: {
1.138     brouard  2314:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2315:      computes the probability to be observed in state j being in state i by appying the
                   2316:      model to the ncovmodel covariates (including constant and age).
                   2317:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2318:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2319:      ncth covariate in the global vector x is given by the formula:
                   2320:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2321:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2322:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2323:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2324:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2325:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2326:   */
                   2327:   double s1, lnpijopii;
1.126     brouard  2328:   /*double t34;*/
1.164     brouard  2329:   int i,j, nc, ii, jj;
1.126     brouard  2330: 
1.218     brouard  2331:        for(i=1; i<= nlstate; i++){
                   2332:                for(j=1; j<i;j++){
                   2333:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2334:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2335:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2336:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2337:                        }
                   2338:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2339:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2340:                }
                   2341:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2342:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2343:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2344:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2345:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2346:                        }
                   2347:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2348:                }
                   2349:        }
                   2350:   
                   2351:        for(i=1; i<= nlstate; i++){
                   2352:                s1=0;
                   2353:                for(j=1; j<i; j++){
                   2354:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2355:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2356:                }
                   2357:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2358:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2359:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2360:                }
                   2361:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2362:                ps[i][i]=1./(s1+1.);
                   2363:                /* Computing other pijs */
                   2364:                for(j=1; j<i; j++)
                   2365:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2366:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2367:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2368:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2369:        } /* end i */
                   2370:   
                   2371:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2372:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2373:                        ps[ii][jj]=0;
                   2374:                        ps[ii][ii]=1;
                   2375:                }
                   2376:        }
                   2377:   
                   2378:   
                   2379:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2380:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2381:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2382:        /*   } */
                   2383:        /*   printf("\n "); */
                   2384:        /* } */
                   2385:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2386:        /*
                   2387:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2388:                goto end;*/
                   2389:        return ps;
1.126     brouard  2390: }
                   2391: 
1.218     brouard  2392: /*************** backward transition probabilities ***************/ 
                   2393: 
                   2394:  /* 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 ) */
                   2395: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2396:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2397: {
                   2398:        /* Computes the backward probability at age agefin and covariate ij
                   2399:         * and returns in **ps as well as **bmij.
                   2400:         */
                   2401:   int i, ii, j,k;
                   2402: 
                   2403:        double **out, **pmij();
                   2404:        double sumnew=0.;
                   2405:   double agefin;
                   2406: 
                   2407:        double **dnewm, **dsavm, **doldm;
                   2408:        double **bbmij;
                   2409: 
                   2410:   doldm=ddoldms; /* global pointers */
                   2411:        dnewm=ddnewms;
                   2412:        dsavm=ddsavms;
                   2413: 
                   2414:        agefin=cov[2];
                   2415:        /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2416:                 the observed prevalence (with this covariate ij) */
                   2417:        dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2418:        /* We do have the matrix Px in savm  and we need pij */
                   2419:        for (j=1;j<=nlstate+ndeath;j++){
                   2420:                sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2421:                for (ii=1;ii<=nlstate;ii++){
                   2422:                        sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2423:                } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2424:                for (ii=1;ii<=nlstate+ndeath;ii++){
                   2425:                        if(sumnew >= 1.e-10){
                   2426:                                /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2427:                                /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2428:                                /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2429:                                /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2430:                                /* }else */
                   2431:                                        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2432:                        }else{
                   2433:                                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);
                   2434:                        }
                   2435:                } /*End ii */
                   2436:        } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2437:                /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2438:        bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2439:        /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2440:        /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2441:        /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2442:        /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2443:        for (j=1;j<=nlstate+ndeath;j++){
                   2444:                for (ii=1;ii<=nlstate+ndeath;ii++){
                   2445:                        dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2446:                }
                   2447:        } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2448:        ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2449:        /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2450:        /* end bmij */
                   2451:        return ps; 
                   2452: }
1.217     brouard  2453: /*************** transition probabilities ***************/ 
                   2454: 
1.218     brouard  2455: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2456: {
                   2457:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2458:      computes the probability to be observed in state j being in state i by appying the
                   2459:      model to the ncovmodel covariates (including constant and age).
                   2460:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2461:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2462:      ncth covariate in the global vector x is given by the formula:
                   2463:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2464:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2465:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2466:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2467:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2468:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2469:   */
                   2470:   double s1, lnpijopii;
                   2471:   /*double t34;*/
                   2472:   int i,j, nc, ii, jj;
                   2473: 
1.218     brouard  2474:        for(i=1; i<= nlstate; i++){
                   2475:                for(j=1; j<i;j++){
                   2476:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2477:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2478:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2479:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2480:                        }
                   2481:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2482:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2483:                }
                   2484:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2485:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2486:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2487:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2488:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2489:                        }
                   2490:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2491:                }
                   2492:        }
                   2493:        
                   2494:        for(i=1; i<= nlstate; i++){
                   2495:                s1=0;
                   2496:                for(j=1; j<i; j++){
                   2497:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2498:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2499:                }
                   2500:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2501:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2502:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2503:                }
                   2504:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2505:                ps[i][i]=1./(s1+1.);
                   2506:                /* Computing other pijs */
                   2507:                for(j=1; j<i; j++)
                   2508:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2509:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2510:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2511:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2512:        } /* end i */
                   2513:        
                   2514:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2515:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2516:                        ps[ii][jj]=0;
                   2517:                        ps[ii][ii]=1;
                   2518:                }
                   2519:        }
                   2520:        /* Added for backcast */ /* Transposed matrix too */
                   2521:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2522:                s1=0.;
                   2523:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2524:                        s1+=ps[ii][jj];
                   2525:                }
                   2526:                for(ii=1; ii<= nlstate; ii++){
                   2527:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2528:                }
                   2529:        }
                   2530:        /* Transposition */
                   2531:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2532:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2533:                        s1=ps[ii][jj];
                   2534:                        ps[ii][jj]=ps[jj][ii];
                   2535:                        ps[jj][ii]=s1;
                   2536:                }
                   2537:        }
                   2538:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2539:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2540:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2541:        /*   } */
                   2542:        /*   printf("\n "); */
                   2543:        /* } */
                   2544:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2545:        /*
                   2546:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2547:                goto end;*/
                   2548:        return ps;
1.217     brouard  2549: }
                   2550: 
                   2551: 
1.126     brouard  2552: /**************** Product of 2 matrices ******************/
                   2553: 
1.145     brouard  2554: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2555: {
                   2556:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2557:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2558:   /* in, b, out are matrice of pointers which should have been initialized 
                   2559:      before: only the contents of out is modified. The function returns
                   2560:      a pointer to pointers identical to out */
1.145     brouard  2561:   int i, j, k;
1.126     brouard  2562:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2563:     for(k=ncolol; k<=ncoloh; k++){
                   2564:       out[i][k]=0.;
                   2565:       for(j=ncl; j<=nch; j++)
                   2566:        out[i][k] +=in[i][j]*b[j][k];
                   2567:     }
1.126     brouard  2568:   return out;
                   2569: }
                   2570: 
                   2571: 
                   2572: /************* Higher Matrix Product ***************/
                   2573: 
                   2574: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2575: {
1.218     brouard  2576:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2577:      'nhstepm*hstepm*stepm' months (i.e. until
                   2578:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2579:      nhstepm*hstepm matrices. 
                   2580:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2581:      (typically every 2 years instead of every month which is too big 
                   2582:      for the memory).
                   2583:      Model is determined by parameters x and covariates have to be 
                   2584:      included manually here. 
                   2585: 
                   2586:      */
                   2587: 
                   2588:   int i, j, d, h, k;
1.131     brouard  2589:   double **out, cov[NCOVMAX+1];
1.126     brouard  2590:   double **newm;
1.187     brouard  2591:   double agexact;
1.214     brouard  2592:   double agebegin, ageend;
1.126     brouard  2593: 
                   2594:   /* Hstepm could be zero and should return the unit matrix */
                   2595:   for (i=1;i<=nlstate+ndeath;i++)
                   2596:     for (j=1;j<=nlstate+ndeath;j++){
                   2597:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2598:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2599:     }
                   2600:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2601:   for(h=1; h <=nhstepm; h++){
                   2602:     for(d=1; d <=hstepm; d++){
                   2603:       newm=savm;
                   2604:       /* Covariates have to be included here again */
                   2605:       cov[1]=1.;
1.214     brouard  2606:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2607:       cov[2]=agexact;
                   2608:       if(nagesqr==1)
1.218     brouard  2609:                                cov[3]= agexact*agexact;
1.131     brouard  2610:       for (k=1; k<=cptcovn;k++) 
1.218     brouard  2611:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2612:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2613:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2614:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2615:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2616:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2617:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2618:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2619:                        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126     brouard  2620: 
                   2621: 
                   2622:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2623:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2624:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2625:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2626:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2627:       /* if((int)age == 70){ */
                   2628:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2629:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2630:       /*         printf("%d pmmij ",i); */
                   2631:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2632:       /*           printf("%f ",pmmij[i][j]); */
                   2633:       /*         } */
                   2634:       /*         printf(" oldm "); */
                   2635:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2636:       /*           printf("%f ",oldm[i][j]); */
                   2637:       /*         } */
                   2638:       /*         printf("\n"); */
                   2639:       /*       } */
                   2640:       /* } */
1.126     brouard  2641:       savm=oldm;
                   2642:       oldm=newm;
                   2643:     }
                   2644:     for(i=1; i<=nlstate+ndeath; i++)
                   2645:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2646:                                po[i][j][h]=newm[i][j];
                   2647:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2648:       }
1.128     brouard  2649:     /*printf("h=%d ",h);*/
1.126     brouard  2650:   } /* end h */
1.218     brouard  2651:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2652:   return po;
                   2653: }
                   2654: 
1.217     brouard  2655: /************* Higher Back Matrix Product ***************/
1.218     brouard  2656: /* 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 ) */
                   2657:  double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2658: {
1.218     brouard  2659:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2660:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2661:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2662:      nhstepm*hstepm matrices.
                   2663:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2664:      (typically every 2 years instead of every month which is too big
1.217     brouard  2665:      for the memory).
1.218     brouard  2666:      Model is determined by parameters x and covariates have to be
                   2667:      included manually here.
1.217     brouard  2668: 
                   2669:      */
                   2670: 
                   2671:   int i, j, d, h, k;
                   2672:   double **out, cov[NCOVMAX+1];
                   2673:   double **newm;
                   2674:   double agexact;
                   2675:   double agebegin, ageend;
1.218     brouard  2676:        double **oldm, **savm;
1.217     brouard  2677: 
1.218     brouard  2678:        oldm=oldms;savm=savms;
1.217     brouard  2679:   /* Hstepm could be zero and should return the unit matrix */
                   2680:   for (i=1;i<=nlstate+ndeath;i++)
                   2681:     for (j=1;j<=nlstate+ndeath;j++){
                   2682:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2683:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2684:     }
                   2685:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2686:   for(h=1; h <=nhstepm; h++){
                   2687:     for(d=1; d <=hstepm; d++){
                   2688:       newm=savm;
                   2689:       /* Covariates have to be included here again */
                   2690:       cov[1]=1.;
                   2691:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2692:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2693:       cov[2]=agexact;
                   2694:       if(nagesqr==1)
1.218     brouard  2695:                                cov[3]= agexact*agexact;
                   2696:       for (k=1; k<=cptcovn;k++)
                   2697:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2698:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2699:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2700:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2701:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2702:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2703:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2704:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2705:                        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2706:                        
                   2707:                        
1.217     brouard  2708:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2709:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2710:       /* Careful transposed matrix */
                   2711:                        /* age is in cov[2] */
                   2712:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                   2713:                        /*                                               1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
                   2714:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                   2715:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2716:       /* if((int)age == 70){ */
                   2717:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2718:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2719:       /*         printf("%d pmmij ",i); */
                   2720:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2721:       /*           printf("%f ",pmmij[i][j]); */
                   2722:       /*         } */
                   2723:       /*         printf(" oldm "); */
                   2724:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2725:       /*           printf("%f ",oldm[i][j]); */
                   2726:       /*         } */
                   2727:       /*         printf("\n"); */
                   2728:       /*       } */
                   2729:       /* } */
                   2730:       savm=oldm;
                   2731:       oldm=newm;
                   2732:     }
                   2733:     for(i=1; i<=nlstate+ndeath; i++)
                   2734:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2735:                                po[i][j][h]=newm[i][j];
                   2736:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2737:       }
                   2738:     /*printf("h=%d ",h);*/
                   2739:   } /* end h */
1.218     brouard  2740:        /*     printf("\n H=%d \n",h); */
1.217     brouard  2741:   return po;
                   2742: }
                   2743: 
                   2744: 
1.162     brouard  2745: #ifdef NLOPT
                   2746:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2747:   double fret;
                   2748:   double *xt;
                   2749:   int j;
                   2750:   myfunc_data *d2 = (myfunc_data *) pd;
                   2751: /* xt = (p1-1); */
                   2752:   xt=vector(1,n); 
                   2753:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2754: 
                   2755:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2756:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2757:   printf("Function = %.12lf ",fret);
                   2758:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2759:   printf("\n");
                   2760:  free_vector(xt,1,n);
                   2761:   return fret;
                   2762: }
                   2763: #endif
1.126     brouard  2764: 
                   2765: /*************** log-likelihood *************/
                   2766: double func( double *x)
                   2767: {
                   2768:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2769:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2770:   double **out;
                   2771:   double sw; /* Sum of weights */
                   2772:   double lli; /* Individual log likelihood */
                   2773:   int s1, s2;
                   2774:   double bbh, survp;
                   2775:   long ipmx;
1.187     brouard  2776:   double agexact;
1.126     brouard  2777:   /*extern weight */
                   2778:   /* We are differentiating ll according to initial status */
                   2779:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2780:   /*for(i=1;i<imx;i++) 
                   2781:     printf(" %d\n",s[4][i]);
                   2782:   */
1.162     brouard  2783: 
                   2784:   ++countcallfunc;
                   2785: 
1.126     brouard  2786:   cov[1]=1.;
                   2787: 
                   2788:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2789: 
                   2790:   if(mle==1){
                   2791:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2792:       /* Computes the values of the ncovmodel covariates of the model
                   2793:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2794:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2795:         to be observed in j being in i according to the model.
                   2796:        */
1.145     brouard  2797:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2798:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2799:       }
1.137     brouard  2800:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2801:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2802:         has been calculated etc */
1.126     brouard  2803:       for(mi=1; mi<= wav[i]-1; mi++){
                   2804:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2805:          for (j=1;j<=nlstate+ndeath;j++){
                   2806:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2807:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2808:          }
                   2809:        for(d=0; d<dh[mi][i]; d++){
                   2810:          newm=savm;
1.187     brouard  2811:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2812:          cov[2]=agexact;
                   2813:          if(nagesqr==1)
                   2814:            cov[3]= agexact*agexact;
1.126     brouard  2815:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2816:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2817:          }
                   2818:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2819:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2820:          savm=oldm;
                   2821:          oldm=newm;
                   2822:        } /* end mult */
                   2823:       
                   2824:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2825:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2826:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2827:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2828:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2829:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2830:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2831:         * probability in order to take into account the bias as a fraction of the way
                   2832:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2833:         * -stepm/2 to stepm/2 .
                   2834:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2835:         * For stepm > 1 the results are less biased than in previous versions. 
                   2836:         */
                   2837:        s1=s[mw[mi][i]][i];
                   2838:        s2=s[mw[mi+1][i]][i];
                   2839:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2840:        /* bias bh is positive if real duration
                   2841:         * is higher than the multiple of stepm and negative otherwise.
                   2842:         */
                   2843:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2844:        if( s2 > nlstate){ 
                   2845:          /* i.e. if s2 is a death state and if the date of death is known 
                   2846:             then the contribution to the likelihood is the probability to 
                   2847:             die between last step unit time and current  step unit time, 
                   2848:             which is also equal to probability to die before dh 
                   2849:             minus probability to die before dh-stepm . 
                   2850:             In version up to 0.92 likelihood was computed
                   2851:        as if date of death was unknown. Death was treated as any other
                   2852:        health state: the date of the interview describes the actual state
                   2853:        and not the date of a change in health state. The former idea was
                   2854:        to consider that at each interview the state was recorded
                   2855:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2856:        introduced the exact date of death then we should have modified
                   2857:        the contribution of an exact death to the likelihood. This new
                   2858:        contribution is smaller and very dependent of the step unit
                   2859:        stepm. It is no more the probability to die between last interview
                   2860:        and month of death but the probability to survive from last
                   2861:        interview up to one month before death multiplied by the
                   2862:        probability to die within a month. Thanks to Chris
                   2863:        Jackson for correcting this bug.  Former versions increased
                   2864:        mortality artificially. The bad side is that we add another loop
                   2865:        which slows down the processing. The difference can be up to 10%
                   2866:        lower mortality.
                   2867:          */
1.183     brouard  2868:        /* If, at the beginning of the maximization mostly, the
                   2869:           cumulative probability or probability to be dead is
                   2870:           constant (ie = 1) over time d, the difference is equal to
                   2871:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2872:           s1 at precedent wave, to be dead a month before current
                   2873:           wave is equal to probability, being at state s1 at
                   2874:           precedent wave, to be dead at mont of the current
                   2875:           wave. Then the observed probability (that this person died)
                   2876:           is null according to current estimated parameter. In fact,
                   2877:           it should be very low but not zero otherwise the log go to
                   2878:           infinity.
                   2879:        */
                   2880: /* #ifdef INFINITYORIGINAL */
                   2881: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2882: /* #else */
                   2883: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2884: /*         lli=log(mytinydouble); */
                   2885: /*       else */
                   2886: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2887: /* #endif */
1.216     brouard  2888:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2889:          
                   2890:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2891:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2892:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2893:          /*survp += out[s1][j]; */
                   2894:          lli= log(survp);
                   2895:        }
                   2896:        else if  (s2==-4) { 
                   2897:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2898:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2899:          lli= log(survp); 
                   2900:        } 
                   2901:        else if  (s2==-5) { 
                   2902:          for (j=1,survp=0. ; j<=2; j++)  
                   2903:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2904:          lli= log(survp); 
                   2905:        } 
                   2906:        else{
                   2907:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2908:          /*  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 */
                   2909:        } 
                   2910:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2911:        /*if(lli ==000.0)*/
                   2912:        /*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); */
                   2913:        ipmx +=1;
                   2914:        sw += weight[i];
                   2915:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2916:        /* if (lli < log(mytinydouble)){ */
                   2917:        /*   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); */
                   2918:        /*   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]); */
                   2919:        /* } */
1.126     brouard  2920:       } /* end of wave */
                   2921:     } /* end of individual */
                   2922:   }  else if(mle==2){
                   2923:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2924:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2925:       for(mi=1; mi<= wav[i]-1; mi++){
                   2926:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2927:          for (j=1;j<=nlstate+ndeath;j++){
                   2928:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2929:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2930:          }
                   2931:        for(d=0; d<=dh[mi][i]; d++){
                   2932:          newm=savm;
1.187     brouard  2933:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2934:          cov[2]=agexact;
                   2935:          if(nagesqr==1)
                   2936:            cov[3]= agexact*agexact;
1.126     brouard  2937:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2938:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2939:          }
                   2940:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2941:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2942:          savm=oldm;
                   2943:          oldm=newm;
                   2944:        } /* end mult */
                   2945:       
                   2946:        s1=s[mw[mi][i]][i];
                   2947:        s2=s[mw[mi+1][i]][i];
                   2948:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2949:        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 */
                   2950:        ipmx +=1;
                   2951:        sw += weight[i];
                   2952:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2953:       } /* end of wave */
                   2954:     } /* end of individual */
                   2955:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2956:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2957:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2958:       for(mi=1; mi<= wav[i]-1; mi++){
                   2959:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2960:          for (j=1;j<=nlstate+ndeath;j++){
                   2961:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2962:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2963:          }
                   2964:        for(d=0; d<dh[mi][i]; d++){
                   2965:          newm=savm;
1.187     brouard  2966:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2967:          cov[2]=agexact;
                   2968:          if(nagesqr==1)
                   2969:            cov[3]= agexact*agexact;
1.126     brouard  2970:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2971:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2972:          }
                   2973:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2974:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2975:          savm=oldm;
                   2976:          oldm=newm;
                   2977:        } /* end mult */
                   2978:       
                   2979:        s1=s[mw[mi][i]][i];
                   2980:        s2=s[mw[mi+1][i]][i];
                   2981:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2982:        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 */
                   2983:        ipmx +=1;
                   2984:        sw += weight[i];
                   2985:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2986:       } /* end of wave */
                   2987:     } /* end of individual */
                   2988:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2989:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2990:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2991:       for(mi=1; mi<= wav[i]-1; mi++){
                   2992:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2993:          for (j=1;j<=nlstate+ndeath;j++){
                   2994:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2995:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2996:          }
                   2997:        for(d=0; d<dh[mi][i]; d++){
                   2998:          newm=savm;
1.187     brouard  2999:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3000:          cov[2]=agexact;
                   3001:          if(nagesqr==1)
                   3002:            cov[3]= agexact*agexact;
1.126     brouard  3003:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3004:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3005:          }
                   3006:        
                   3007:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3008:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3009:          savm=oldm;
                   3010:          oldm=newm;
                   3011:        } /* end mult */
                   3012:       
                   3013:        s1=s[mw[mi][i]][i];
                   3014:        s2=s[mw[mi+1][i]][i];
                   3015:        if( s2 > nlstate){ 
                   3016:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3017:        } else if  ( s2==-1 ) { /* alive */
                   3018:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3019:            survp += out[s1][j];
                   3020:          lli= log(survp);
1.126     brouard  3021:        }else{
                   3022:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3023:        }
                   3024:        ipmx +=1;
                   3025:        sw += weight[i];
                   3026:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3027: /*     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]); */
                   3028:       } /* end of wave */
                   3029:     } /* end of individual */
                   3030:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3031:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3032:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3033:       for(mi=1; mi<= wav[i]-1; mi++){
                   3034:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3035:          for (j=1;j<=nlstate+ndeath;j++){
                   3036:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3037:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3038:          }
                   3039:        for(d=0; d<dh[mi][i]; d++){
                   3040:          newm=savm;
1.187     brouard  3041:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3042:          cov[2]=agexact;
                   3043:          if(nagesqr==1)
                   3044:            cov[3]= agexact*agexact;
1.126     brouard  3045:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3046:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3047:          }
                   3048:        
                   3049:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3050:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3051:          savm=oldm;
                   3052:          oldm=newm;
                   3053:        } /* end mult */
                   3054:       
                   3055:        s1=s[mw[mi][i]][i];
                   3056:        s2=s[mw[mi+1][i]][i];
                   3057:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3058:        ipmx +=1;
                   3059:        sw += weight[i];
                   3060:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3061:        /*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]);*/
                   3062:       } /* end of wave */
                   3063:     } /* end of individual */
                   3064:   } /* End of if */
                   3065:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3066:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3067:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3068:   return -l;
                   3069: }
                   3070: 
                   3071: /*************** log-likelihood *************/
                   3072: double funcone( double *x)
                   3073: {
                   3074:   /* Same as likeli but slower because of a lot of printf and if */
                   3075:   int i, ii, j, k, mi, d, kk;
1.131     brouard  3076:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3077:   double **out;
                   3078:   double lli; /* Individual log likelihood */
                   3079:   double llt;
                   3080:   int s1, s2;
                   3081:   double bbh, survp;
1.187     brouard  3082:   double agexact;
1.214     brouard  3083:   double agebegin, ageend;
1.126     brouard  3084:   /*extern weight */
                   3085:   /* We are differentiating ll according to initial status */
                   3086:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3087:   /*for(i=1;i<imx;i++) 
                   3088:     printf(" %d\n",s[4][i]);
                   3089:   */
                   3090:   cov[1]=1.;
                   3091: 
                   3092:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   3093: 
                   3094:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3095:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3096:     for(mi=1; mi<= wav[i]-1; mi++){
                   3097:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   3098:        for (j=1;j<=nlstate+ndeath;j++){
                   3099:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3100:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3101:        }
1.214     brouard  3102:       
                   3103:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3104:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3105:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   3106:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3107:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  3108:        newm=savm;
1.187     brouard  3109:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3110:        cov[2]=agexact;
                   3111:        if(nagesqr==1)
                   3112:          cov[3]= agexact*agexact;
1.126     brouard  3113:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3114:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3115:        }
1.187     brouard  3116: 
1.145     brouard  3117:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  3118:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3119:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  3120:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3121:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  3122:        savm=oldm;
                   3123:        oldm=newm;
                   3124:       } /* end mult */
                   3125:       
                   3126:       s1=s[mw[mi][i]][i];
                   3127:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3128:       /* if(s2==-1){ */
                   3129:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3130:       /*       /\* exit(1); *\/ */
                   3131:       /* } */
1.126     brouard  3132:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3133:       /* bias is positive if real duration
                   3134:        * is higher than the multiple of stepm and negative otherwise.
                   3135:        */
                   3136:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   3137:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3138:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  3139:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3140:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3141:        lli= log(survp);
                   3142:       }else if (mle==1){
                   3143:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3144:       } else if(mle==2){
                   3145:        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 */
                   3146:       } else if(mle==3){  /* exponential inter-extrapolation */
                   3147:        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 */
                   3148:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   3149:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3150:       } else{  /* mle=0 back to 1 */
                   3151:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3152:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3153:       } /* End of if */
                   3154:       ipmx +=1;
                   3155:       sw += weight[i];
                   3156:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3157:       /*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  3158:       if(globpr){
1.214     brouard  3159:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  3160:  %11.6f %11.6f %11.6f ", \
1.214     brouard  3161:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  3162:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3163:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3164:          llt +=ll[k]*gipmx/gsw;
                   3165:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3166:        }
                   3167:        fprintf(ficresilk," %10.6f\n", -llt);
                   3168:       }
                   3169:     } /* end of wave */
                   3170:   } /* end of individual */
                   3171:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3172:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3173:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3174:   if(globpr==0){ /* First time we count the contributions and weights */
                   3175:     gipmx=ipmx;
                   3176:     gsw=sw;
                   3177:   }
                   3178:   return -l;
                   3179: }
                   3180: 
                   3181: 
                   3182: /*************** function likelione ***********/
                   3183: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3184: {
                   3185:   /* This routine should help understanding what is done with 
                   3186:      the selection of individuals/waves and
                   3187:      to check the exact contribution to the likelihood.
                   3188:      Plotting could be done.
                   3189:    */
                   3190:   int k;
                   3191: 
                   3192:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3193:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3194:     strcat(fileresilk,fileresu);
1.126     brouard  3195:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3196:       printf("Problem with resultfile: %s\n", fileresilk);
                   3197:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3198:     }
1.214     brouard  3199:     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");
                   3200:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3201:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3202:     for(k=1; k<=nlstate; k++) 
                   3203:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3204:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3205:   }
                   3206: 
                   3207:   *fretone=(*funcone)(p);
                   3208:   if(*globpri !=0){
                   3209:     fclose(ficresilk);
1.205     brouard  3210:     if (mle ==0)
                   3211:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3212:     else if(mle >=1)
                   3213:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3214:     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  3215:     
1.208     brouard  3216:       
                   3217:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3218:       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  3219: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3220:     }
1.207     brouard  3221:     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  3222: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3223:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3224: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3225:     fflush(fichtm);
1.205     brouard  3226:   }
1.126     brouard  3227:   return;
                   3228: }
                   3229: 
                   3230: 
                   3231: /*********** Maximum Likelihood Estimation ***************/
                   3232: 
                   3233: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3234: {
1.165     brouard  3235:   int i,j, iter=0;
1.126     brouard  3236:   double **xi;
                   3237:   double fret;
                   3238:   double fretone; /* Only one call to likelihood */
                   3239:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3240: 
                   3241: #ifdef NLOPT
                   3242:   int creturn;
                   3243:   nlopt_opt opt;
                   3244:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3245:   double *lb;
                   3246:   double minf; /* the minimum objective value, upon return */
                   3247:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3248:   myfunc_data dinst, *d = &dinst;
                   3249: #endif
                   3250: 
                   3251: 
1.126     brouard  3252:   xi=matrix(1,npar,1,npar);
                   3253:   for (i=1;i<=npar;i++)
                   3254:     for (j=1;j<=npar;j++)
                   3255:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3256:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3257:   strcpy(filerespow,"POW_"); 
1.126     brouard  3258:   strcat(filerespow,fileres);
                   3259:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3260:     printf("Problem with resultfile: %s\n", filerespow);
                   3261:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3262:   }
                   3263:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3264:   for (i=1;i<=nlstate;i++)
                   3265:     for(j=1;j<=nlstate+ndeath;j++)
                   3266:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3267:   fprintf(ficrespow,"\n");
1.162     brouard  3268: #ifdef POWELL
1.126     brouard  3269:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3270: #endif
1.126     brouard  3271: 
1.162     brouard  3272: #ifdef NLOPT
                   3273: #ifdef NEWUOA
                   3274:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3275: #else
                   3276:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3277: #endif
                   3278:   lb=vector(0,npar-1);
                   3279:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3280:   nlopt_set_lower_bounds(opt, lb);
                   3281:   nlopt_set_initial_step1(opt, 0.1);
                   3282:   
                   3283:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3284:   d->function = func;
                   3285:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3286:   nlopt_set_min_objective(opt, myfunc, d);
                   3287:   nlopt_set_xtol_rel(opt, ftol);
                   3288:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3289:     printf("nlopt failed! %d\n",creturn); 
                   3290:   }
                   3291:   else {
                   3292:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3293:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3294:     iter=1; /* not equal */
                   3295:   }
                   3296:   nlopt_destroy(opt);
                   3297: #endif
1.126     brouard  3298:   free_matrix(xi,1,npar,1,npar);
                   3299:   fclose(ficrespow);
1.203     brouard  3300:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3301:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3302:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3303: 
                   3304: }
                   3305: 
                   3306: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3307: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3308: {
                   3309:   double  **a,**y,*x,pd;
1.203     brouard  3310:   /* double **hess; */
1.164     brouard  3311:   int i, j;
1.126     brouard  3312:   int *indx;
                   3313: 
                   3314:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3315:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3316:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3317:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3318:   double gompertz(double p[]);
1.203     brouard  3319:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3320: 
                   3321:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3322:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3323:   for (i=1;i<=npar;i++){
1.203     brouard  3324:     printf("%d-",i);fflush(stdout);
                   3325:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3326:    
                   3327:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3328:     
                   3329:     /*  printf(" %f ",p[i]);
                   3330:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3331:   }
                   3332:   
                   3333:   for (i=1;i<=npar;i++) {
                   3334:     for (j=1;j<=npar;j++)  {
                   3335:       if (j>i) { 
1.203     brouard  3336:        printf(".%d-%d",i,j);fflush(stdout);
                   3337:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3338:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3339:        
                   3340:        hess[j][i]=hess[i][j];    
                   3341:        /*printf(" %lf ",hess[i][j]);*/
                   3342:       }
                   3343:     }
                   3344:   }
                   3345:   printf("\n");
                   3346:   fprintf(ficlog,"\n");
                   3347: 
                   3348:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3349:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3350:   
                   3351:   a=matrix(1,npar,1,npar);
                   3352:   y=matrix(1,npar,1,npar);
                   3353:   x=vector(1,npar);
                   3354:   indx=ivector(1,npar);
                   3355:   for (i=1;i<=npar;i++)
                   3356:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3357:   ludcmp(a,npar,indx,&pd);
                   3358: 
                   3359:   for (j=1;j<=npar;j++) {
                   3360:     for (i=1;i<=npar;i++) x[i]=0;
                   3361:     x[j]=1;
                   3362:     lubksb(a,npar,indx,x);
                   3363:     for (i=1;i<=npar;i++){ 
                   3364:       matcov[i][j]=x[i];
                   3365:     }
                   3366:   }
                   3367: 
                   3368:   printf("\n#Hessian matrix#\n");
                   3369:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3370:   for (i=1;i<=npar;i++) { 
                   3371:     for (j=1;j<=npar;j++) { 
1.203     brouard  3372:       printf("%.6e ",hess[i][j]);
                   3373:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3374:     }
                   3375:     printf("\n");
                   3376:     fprintf(ficlog,"\n");
                   3377:   }
                   3378: 
1.203     brouard  3379:   /* printf("\n#Covariance matrix#\n"); */
                   3380:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3381:   /* for (i=1;i<=npar;i++) {  */
                   3382:   /*   for (j=1;j<=npar;j++) {  */
                   3383:   /*     printf("%.6e ",matcov[i][j]); */
                   3384:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3385:   /*   } */
                   3386:   /*   printf("\n"); */
                   3387:   /*   fprintf(ficlog,"\n"); */
                   3388:   /* } */
                   3389: 
1.126     brouard  3390:   /* Recompute Inverse */
1.203     brouard  3391:   /* for (i=1;i<=npar;i++) */
                   3392:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3393:   /* ludcmp(a,npar,indx,&pd); */
                   3394: 
                   3395:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3396: 
                   3397:   /* for (j=1;j<=npar;j++) { */
                   3398:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3399:   /*   x[j]=1; */
                   3400:   /*   lubksb(a,npar,indx,x); */
                   3401:   /*   for (i=1;i<=npar;i++){  */
                   3402:   /*     y[i][j]=x[i]; */
                   3403:   /*     printf("%.3e ",y[i][j]); */
                   3404:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3405:   /*   } */
                   3406:   /*   printf("\n"); */
                   3407:   /*   fprintf(ficlog,"\n"); */
                   3408:   /* } */
                   3409: 
                   3410:   /* Verifying the inverse matrix */
                   3411: #ifdef DEBUGHESS
                   3412:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3413: 
1.203     brouard  3414:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3415:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3416: 
                   3417:   for (j=1;j<=npar;j++) {
                   3418:     for (i=1;i<=npar;i++){ 
1.203     brouard  3419:       printf("%.2f ",y[i][j]);
                   3420:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3421:     }
                   3422:     printf("\n");
                   3423:     fprintf(ficlog,"\n");
                   3424:   }
1.203     brouard  3425: #endif
1.126     brouard  3426: 
                   3427:   free_matrix(a,1,npar,1,npar);
                   3428:   free_matrix(y,1,npar,1,npar);
                   3429:   free_vector(x,1,npar);
                   3430:   free_ivector(indx,1,npar);
1.203     brouard  3431:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3432: 
                   3433: 
                   3434: }
                   3435: 
                   3436: /*************** hessian matrix ****************/
                   3437: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3438: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3439:   int i;
                   3440:   int l=1, lmax=20;
1.203     brouard  3441:   double k1,k2, res, fx;
1.132     brouard  3442:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3443:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3444:   int k=0,kmax=10;
                   3445:   double l1;
                   3446: 
                   3447:   fx=func(x);
                   3448:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3449:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3450:     l1=pow(10,l);
                   3451:     delts=delt;
                   3452:     for(k=1 ; k <kmax; k=k+1){
                   3453:       delt = delta*(l1*k);
                   3454:       p2[theta]=x[theta] +delt;
1.145     brouard  3455:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3456:       p2[theta]=x[theta]-delt;
                   3457:       k2=func(p2)-fx;
                   3458:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3459:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3460:       
1.203     brouard  3461: #ifdef DEBUGHESSII
1.126     brouard  3462:       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);
                   3463:       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);
                   3464: #endif
                   3465:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3466:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3467:        k=kmax;
                   3468:       }
                   3469:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3470:        k=kmax; l=lmax*10;
1.126     brouard  3471:       }
                   3472:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3473:        delts=delt;
                   3474:       }
1.203     brouard  3475:     } /* End loop k */
1.126     brouard  3476:   }
                   3477:   delti[theta]=delts;
                   3478:   return res; 
                   3479:   
                   3480: }
                   3481: 
1.203     brouard  3482: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3483: {
                   3484:   int i;
1.164     brouard  3485:   int l=1, lmax=20;
1.126     brouard  3486:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3487:   double p2[MAXPARM+1];
1.203     brouard  3488:   int k, kmax=1;
                   3489:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3490: 
                   3491:   int firstime=0;
1.203     brouard  3492:   
1.126     brouard  3493:   fx=func(x);
1.203     brouard  3494:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3495:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3496:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3497:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3498:     k1=func(p2)-fx;
                   3499:   
1.203     brouard  3500:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3501:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3502:     k2=func(p2)-fx;
                   3503:   
1.203     brouard  3504:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3505:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3506:     k3=func(p2)-fx;
                   3507:   
1.203     brouard  3508:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3509:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3510:     k4=func(p2)-fx;
1.203     brouard  3511:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3512:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3513:       firstime=1;
1.203     brouard  3514:       kmax=kmax+10;
1.208     brouard  3515:     }
                   3516:     if(kmax >=10 || firstime ==1){
1.218     brouard  3517:       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);
                   3518:       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  3519:       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);
                   3520:       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);
                   3521:     }
                   3522: #ifdef DEBUGHESSIJ
                   3523:     v1=hess[thetai][thetai];
                   3524:     v2=hess[thetaj][thetaj];
                   3525:     cv12=res;
                   3526:     /* Computing eigen value of Hessian matrix */
                   3527:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3528:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3529:     if ((lc2 <0) || (lc1 <0) ){
                   3530:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3531:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3532:       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);
                   3533:       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);
                   3534:     }
1.126     brouard  3535: #endif
                   3536:   }
                   3537:   return res;
                   3538: }
                   3539: 
1.203     brouard  3540:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3541: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3542: /* { */
                   3543: /*   int i; */
                   3544: /*   int l=1, lmax=20; */
                   3545: /*   double k1,k2,k3,k4,res,fx; */
                   3546: /*   double p2[MAXPARM+1]; */
                   3547: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3548: /*   int k=0,kmax=10; */
                   3549: /*   double l1; */
                   3550:   
                   3551: /*   fx=func(x); */
                   3552: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3553: /*     l1=pow(10,l); */
                   3554: /*     delts=delt; */
                   3555: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3556: /*       delt = delti*(l1*k); */
                   3557: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3558: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3559: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3560: /*       k1=func(p2)-fx; */
                   3561:       
                   3562: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3563: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3564: /*       k2=func(p2)-fx; */
                   3565:       
                   3566: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3567: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3568: /*       k3=func(p2)-fx; */
                   3569:       
                   3570: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3571: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3572: /*       k4=func(p2)-fx; */
                   3573: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3574: /* #ifdef DEBUGHESSIJ */
                   3575: /*       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); */
                   3576: /*       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); */
                   3577: /* #endif */
                   3578: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3579: /*     k=kmax; */
                   3580: /*       } */
                   3581: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3582: /*     k=kmax; l=lmax*10; */
                   3583: /*       } */
                   3584: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3585: /*     delts=delt; */
                   3586: /*       } */
                   3587: /*     } /\* End loop k *\/ */
                   3588: /*   } */
                   3589: /*   delti[theta]=delts; */
                   3590: /*   return res;  */
                   3591: /* } */
                   3592: 
                   3593: 
1.126     brouard  3594: /************** Inverse of matrix **************/
                   3595: void ludcmp(double **a, int n, int *indx, double *d) 
                   3596: { 
                   3597:   int i,imax,j,k; 
                   3598:   double big,dum,sum,temp; 
                   3599:   double *vv; 
                   3600:  
                   3601:   vv=vector(1,n); 
                   3602:   *d=1.0; 
                   3603:   for (i=1;i<=n;i++) { 
                   3604:     big=0.0; 
                   3605:     for (j=1;j<=n;j++) 
                   3606:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3607:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3608:     vv[i]=1.0/big; 
                   3609:   } 
                   3610:   for (j=1;j<=n;j++) { 
                   3611:     for (i=1;i<j;i++) { 
                   3612:       sum=a[i][j]; 
                   3613:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3614:       a[i][j]=sum; 
                   3615:     } 
                   3616:     big=0.0; 
                   3617:     for (i=j;i<=n;i++) { 
                   3618:       sum=a[i][j]; 
                   3619:       for (k=1;k<j;k++) 
                   3620:        sum -= a[i][k]*a[k][j]; 
                   3621:       a[i][j]=sum; 
                   3622:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3623:        big=dum; 
                   3624:        imax=i; 
                   3625:       } 
                   3626:     } 
                   3627:     if (j != imax) { 
                   3628:       for (k=1;k<=n;k++) { 
                   3629:        dum=a[imax][k]; 
                   3630:        a[imax][k]=a[j][k]; 
                   3631:        a[j][k]=dum; 
                   3632:       } 
                   3633:       *d = -(*d); 
                   3634:       vv[imax]=vv[j]; 
                   3635:     } 
                   3636:     indx[j]=imax; 
                   3637:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3638:     if (j != n) { 
                   3639:       dum=1.0/(a[j][j]); 
                   3640:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3641:     } 
                   3642:   } 
                   3643:   free_vector(vv,1,n);  /* Doesn't work */
                   3644: ;
                   3645: } 
                   3646: 
                   3647: void lubksb(double **a, int n, int *indx, double b[]) 
                   3648: { 
                   3649:   int i,ii=0,ip,j; 
                   3650:   double sum; 
                   3651:  
                   3652:   for (i=1;i<=n;i++) { 
                   3653:     ip=indx[i]; 
                   3654:     sum=b[ip]; 
                   3655:     b[ip]=b[i]; 
                   3656:     if (ii) 
                   3657:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3658:     else if (sum) ii=i; 
                   3659:     b[i]=sum; 
                   3660:   } 
                   3661:   for (i=n;i>=1;i--) { 
                   3662:     sum=b[i]; 
                   3663:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3664:     b[i]=sum/a[i][i]; 
                   3665:   } 
                   3666: } 
                   3667: 
                   3668: void pstamp(FILE *fichier)
                   3669: {
1.196     brouard  3670:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3671: }
                   3672: 
                   3673: /************ Frequencies ********************/
1.220     brouard  3674:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3675:                                                                         int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   3676:                                                                         int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3677:  {  /* Some frequencies */
                   3678:   
                   3679:         int i, m, jk, j1, bool, z1,j;
                   3680:         int iind=0, iage=0;
                   3681:         int mi; /* Effective wave */
                   3682:         int first;
                   3683:         double ***freq; /* Frequencies */
                   3684:         double *pp, **prop, *posprop, *pospropt;
                   3685:         double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   3686:         char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3687:         double agebegin, ageend;
                   3688:     
                   3689:         pp=vector(1,nlstate);
                   3690:         prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3691:         posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   3692:         pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   3693:         /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   3694:         strcpy(fileresp,"P_");
                   3695:         strcat(fileresp,fileresu);
                   3696:         /*strcat(fileresphtm,fileresu);*/
                   3697:         if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3698:                 printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3699:                 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3700:                 exit(0);
                   3701:         }
1.214     brouard  3702: 
1.220     brouard  3703:         strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3704:         if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3705:                 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3706:                 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3707:                 fflush(ficlog);
                   3708:                 exit(70); 
                   3709:         }
                   3710:         else{
                   3711:                 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3712: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3713: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3714:                                                 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3715:         }
                   3716:         fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
1.214     brouard  3717:     
1.220     brouard  3718:         strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3719:         if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3720:                 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3721:                 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3722:                 fflush(ficlog);
                   3723:                 exit(70); 
                   3724:         }
                   3725:         else{
                   3726:                 fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3727: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3728: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3729:                                                 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3730:         }
                   3731:         fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
1.214     brouard  3732: 
1.220     brouard  3733:         freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   3734:         j1=0;
1.126     brouard  3735:   
1.220     brouard  3736:         j=cptcoveff;
                   3737:         if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3738: 
                   3739:         first=1;
                   3740: 
                   3741:         /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   3742:                        reference=low_education V1=0,V2=0
                   3743:                        med_educ                V1=1 V2=0, 
                   3744:                        high_educ               V1=0 V2=1
                   3745:                        Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   3746:         */
1.126     brouard  3747: 
1.220     brouard  3748:         for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
                   3749:                 posproptt=0.;
                   3750:                 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3751:                         scanf("%d", i);*/
                   3752:                 for (i=-5; i<=nlstate+ndeath; i++)  
                   3753:                         for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3754:                                 for(m=iagemin; m <= iagemax+3; m++)
                   3755:                                         freq[i][jk][m]=0;
                   3756:       
                   3757:                 for (i=1; i<=nlstate; i++)  {
                   3758:                         for(m=iagemin; m <= iagemax+3; m++)
                   3759:                                 prop[i][m]=0;
                   3760:                         posprop[i]=0;
                   3761:                         pospropt[i]=0;
                   3762:                 }
                   3763:       
                   3764:                 dateintsum=0;
                   3765:                 k2cpt=0;
1.126     brouard  3766: 
1.220     brouard  3767:                 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   3768:                         bool=1;
                   3769:                         if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3770:                                 for (z1=1; z1<=cptcoveff; z1++) {      
                   3771:                                         if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   3772:                                                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
                   3773:                                                 bool=0;
                   3774:                                                 /* 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", 
1.198     brouard  3775:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3776:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.220     brouard  3777:                                                 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   3778:                                         } 
                   3779:                                 } /* end z1 */
                   3780:                         } /* cptcovn > 0 */
                   3781: 
                   3782:                         if (bool==1){
                   3783:                                 /* for(m=firstpass; m<=lastpass; m++){ */
                   3784:                                 for(mi=1; mi<wav[iind];mi++){
                   3785:                                         m=mw[mi][iind];
                   3786:                                         /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   3787:                                                        and mw[mi+1][iind]. dh depends on stepm. */
                   3788:                                         agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   3789:                                         ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   3790:                                         if(m >=firstpass && m <=lastpass){
                   3791:                                                 k2=anint[m][iind]+(mint[m][iind]/12.);
                   3792:                                                 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3793:                                                 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3794:                                                 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3795:                                                 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   3796:                                                         prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   3797:                                                 if (m<lastpass) {
                   3798:                                                         /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   3799:                                                         /*   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]); */
                   3800:                                                         if(s[m][iind]==-1)
                   3801:                                                                 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.));
                   3802:                                                         freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   3803:                                                         /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   3804:                                                         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 */
                   3805:                                                 }
                   3806:                                         }  
                   3807:                                         if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   3808:                                                 dateintsum=dateintsum+k2;
                   3809:                                                 k2cpt++;
                   3810:                                                 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3811:                                         }
                   3812:                                         /*}*/
                   3813:                                 } /* end m */
                   3814:                         } /* end bool */
                   3815:                 } /* end iind = 1 to imx */
                   3816:        /* prop[s][age] is feeded for any initial and valid live state as well as
                   3817:                                        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   3818: 
                   3819: 
                   3820:                 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3821:                 pstamp(ficresp);
                   3822:                 if  (cptcovn>0) {
                   3823:                         fprintf(ficresp, "\n#********** Variable "); 
                   3824:                         fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3825:                         fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   3826:                         for (z1=1; z1<=cptcoveff; z1++){
                   3827:                                 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3828:                                 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3829:                                 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3830:                         }
                   3831:                         fprintf(ficresp, "**********\n#");
                   3832:                         fprintf(ficresphtm, "**********</h3>\n");
                   3833:                         fprintf(ficresphtmfr, "**********</h3>\n");
                   3834:                         fprintf(ficlog, "\n#********** Variable "); 
                   3835:                         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3836:                         fprintf(ficlog, "**********\n");
                   3837:                 }
                   3838:                 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   3839:                 for(i=1; i<=nlstate;i++) {
                   3840:                         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3841:                         fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3842:                 }
                   3843:                 fprintf(ficresp, "\n");
                   3844:                 fprintf(ficresphtm, "\n");
                   3845:       
                   3846:                 /* Header of frequency table by age */
                   3847:                 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3848:                 fprintf(ficresphtmfr,"<th>Age</th> ");
                   3849:                 for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3850:                         for(m=-1; m <=nlstate+ndeath; m++){
                   3851:                                 if(jk!=0 && m!=0)
                   3852:                                         fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3853:                         }
                   3854:                 }
                   3855:                 fprintf(ficresphtmfr, "\n");
1.214     brouard  3856:       
1.220     brouard  3857:                 /* For each age */
                   3858:                 for(iage=iagemin; iage <= iagemax+3; iage++){
                   3859:                         fprintf(ficresphtm,"<tr>");
                   3860:                         if(iage==iagemax+1){
                   3861:                                 fprintf(ficlog,"1");
                   3862:                                 fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3863:                         }else if(iage==iagemax+2){
                   3864:                                 fprintf(ficlog,"0");
                   3865:                                 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3866:                         }else if(iage==iagemax+3){
                   3867:                                 fprintf(ficlog,"Total");
                   3868:                                 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   3869:                         }else{
                   3870:                                 if(first==1){
                   3871:                                         first=0;
                   3872:                                         printf("See log file for details...\n");
                   3873:                                 }
                   3874:                                 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   3875:                                 fprintf(ficlog,"Age %d", iage);
                   3876:                         }
                   3877:                         for(jk=1; jk <=nlstate ; jk++){
                   3878:                                 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3879:                                         pp[jk] += freq[jk][m][iage]; 
                   3880:                         }
                   3881:                         for(jk=1; jk <=nlstate ; jk++){
                   3882:                                 for(m=-1, pos=0; m <=0 ; m++)
                   3883:                                         pos += freq[jk][m][iage];
                   3884:                                 if(pp[jk]>=1.e-10){
                   3885:                                         if(first==1){
                   3886:                                                 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3887:                                         }
                   3888:                                         fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3889:                                 }else{
                   3890:                                         if(first==1)
                   3891:                                                 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3892:                                         fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3893:                                 }
                   3894:                         }
                   3895: 
                   3896:                         for(jk=1; jk <=nlstate ; jk++){ 
                   3897:                                 /* posprop[jk]=0; */
                   3898:                                 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   3899:                                         pp[jk] += freq[jk][m][iage];
                   3900:                         }      /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   3901: 
                   3902:                         for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   3903:                                 pos += pp[jk]; /* pos is the total number of transitions until this age */
                   3904:                                 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3905:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3906:                                 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3907:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3908:                         }
                   3909:                         for(jk=1; jk <=nlstate ; jk++){
                   3910:                                 if(pos>=1.e-5){
                   3911:                                         if(first==1)
                   3912:                                                 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3913:                                         fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3914:                                 }else{
                   3915:                                         if(first==1)
                   3916:                                                 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3917:                                         fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3918:                                 }
                   3919:                                 if( iage <= iagemax){
                   3920:                                         if(pos>=1.e-5){
                   3921:                                                 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3922:                                                 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3923:                                                 /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   3924:                                                 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   3925:                                         }
                   3926:                                         else{
                   3927:                                                 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   3928:                                                 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   3929:                                         }
                   3930:                                 }
                   3931:                                 pospropt[jk] +=posprop[jk];
                   3932:                         } /* end loop jk */
                   3933:                         /* pospropt=0.; */
                   3934:                         for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3935:                                 for(m=-1; m <=nlstate+ndeath; m++){
                   3936:                                         if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   3937:                                                 if(first==1){
                   3938:                                                         printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3939:                                                 }
                   3940:                                                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3941:                                         }
                   3942:                                         if(jk!=0 && m!=0)
                   3943:                                                 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   3944:                                 }
                   3945:                         } /* end loop jk */
                   3946:                         posproptt=0.; 
                   3947:                         for(jk=1; jk <=nlstate; jk++){
                   3948:                                 posproptt += pospropt[jk];
                   3949:                         }
                   3950:                         fprintf(ficresphtmfr,"</tr>\n ");
                   3951:                         if(iage <= iagemax){
                   3952:                                 fprintf(ficresp,"\n");
                   3953:                                 fprintf(ficresphtm,"</tr>\n");
                   3954:                         }
                   3955:                         if(first==1)
                   3956:                                 printf("Others in log...\n");
                   3957:                         fprintf(ficlog,"\n");
                   3958:                 } /* end loop age iage */
                   3959:                 fprintf(ficresphtm,"<tr><th>Tot</th>");
                   3960:                 for(jk=1; jk <=nlstate ; jk++){
                   3961:                         if(posproptt < 1.e-5){
1.221   ! brouard  3962:                                 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
        !          3963:                         }else{
1.220     brouard  3964:                                 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
                   3965:                         }
                   3966:                 }
                   3967:                 fprintf(ficresphtm,"</tr>\n");
                   3968:                 fprintf(ficresphtm,"</table>\n");
                   3969:                 fprintf(ficresphtmfr,"</table>\n");
                   3970:                 if(posproptt < 1.e-5){
                   3971:                         fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   3972:                         fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   3973:                         fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   3974:                         invalidvarcomb[j1]=1;
                   3975:                 }else{
                   3976:                         fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   3977:                         invalidvarcomb[j1]=0;
                   3978:                 }
                   3979:                 fprintf(ficresphtmfr,"</table>\n");
                   3980:         } /* end selected combination of covariate j1 */
                   3981:         dateintmean=dateintsum/k2cpt; 
                   3982:                 
                   3983:         fclose(ficresp);
                   3984:         fclose(ficresphtm);
                   3985:         fclose(ficresphtmfr);
                   3986:         free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   3987:         free_vector(pospropt,1,nlstate);
                   3988:         free_vector(posprop,1,nlstate);
                   3989:         free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   3990:         free_vector(pp,1,nlstate);
                   3991:         /* End of Freq */
                   3992:  }
1.126     brouard  3993: 
                   3994: /************ Prevalence ********************/
                   3995: 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)
                   3996: {  
                   3997:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3998:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3999:      We still use firstpass and lastpass as another selection.
                   4000:   */
                   4001:  
1.164     brouard  4002:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  4003:   int mi; /* Effective wave */
                   4004:   int iage;
                   4005:   double agebegin, ageend;
1.164     brouard  4006: 
                   4007:   double **prop;
                   4008:   double posprop; 
1.126     brouard  4009:   double  y2; /* in fractional years */
                   4010:   int iagemin, iagemax;
1.145     brouard  4011:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  4012: 
                   4013:   iagemin= (int) agemin;
                   4014:   iagemax= (int) agemax;
                   4015:   /*pp=vector(1,nlstate);*/
1.218     brouard  4016:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
1.126     brouard  4017:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4018:   j1=0;
                   4019:   
1.145     brouard  4020:   /*j=cptcoveff;*/
1.126     brouard  4021:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   4022:   
1.145     brouard  4023:   first=1;
1.219     brouard  4024:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
1.214     brouard  4025:     for (i=1; i<=nlstate; i++)  
1.218     brouard  4026:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4027:                                prop[i][iage]=0.0;
1.214     brouard  4028:     
                   4029:     for (i=1; i<=imx; i++) { /* Each individual */
                   4030:       bool=1;
                   4031:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.219     brouard  4032:                                for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
1.218     brouard  4033:                                        if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   4034:                                                bool=0;
1.214     brouard  4035:       } 
1.219     brouard  4036:       if (bool==1) { /* For this combination of covariates values, this individual fits */
1.218     brouard  4037:                                /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4038:                                for(mi=1; mi<wav[i];mi++){
                   4039:                                        m=mw[mi][i];
                   4040:                                        agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4041:                                        /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4042:                                        if(m >=firstpass && m <=lastpass){
                   4043:                                                y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4044:                                                if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4045:                                                        if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4046:                                                        if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4047:                                                        if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4048:                                                                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); 
                   4049:                                                                exit(1);
                   4050:                                                        }
                   4051:                                                        if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4052:                                                                /*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]]);*/
                   4053:                                                                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4054:                                                                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4055:                                                        } /* end valid statuses */ 
                   4056:                                                } /* end selection of dates */
                   4057:                                        } /* end selection of waves */
                   4058:                                } /* end effective waves */
1.214     brouard  4059:       } /* end bool */
                   4060:     }
                   4061:     for(i=iagemin; i <= iagemax+3; i++){  
                   4062:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
1.218     brouard  4063:                                posprop += prop[jk][i]; 
1.214     brouard  4064:       } 
                   4065:       
                   4066:       for(jk=1; jk <=nlstate ; jk++){      
1.218     brouard  4067:                                if( i <=  iagemax){ 
                   4068:                                        if(posprop>=1.e-5){ 
                   4069:                                                probs[i][jk][j1]= prop[jk][i]/posprop;
                   4070:                                        } else{
                   4071:                                                if(first==1){
                   4072:                                                        first=0;
                   4073:                                                        printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4074:                                                }
                   4075:                                        }
                   4076:                                } 
1.214     brouard  4077:       }/* end jk */ 
                   4078:     }/* end i */ 
1.145     brouard  4079:     /*} *//* end i1 */
                   4080:   } /* end j1 */
1.126     brouard  4081:   
                   4082:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4083:   /*free_vector(pp,1,nlstate);*/
1.218     brouard  4084:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
1.126     brouard  4085: }  /* End of prevalence */
                   4086: 
                   4087: /************* Waves Concatenation ***************/
                   4088: 
                   4089: 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)
                   4090: {
                   4091:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4092:      Death is a valid wave (if date is known).
                   4093:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4094:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4095:      and mw[mi+1][i]. dh depends on stepm.
                   4096:      */
                   4097: 
                   4098:   int i, mi, m;
                   4099:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4100:      double sum=0., jmean=0.;*/
1.218     brouard  4101:   int first, firstwo, firsthree, firstfour;
1.126     brouard  4102:   int j, k=0,jk, ju, jl;
                   4103:   double sum=0.;
                   4104:   first=0;
1.214     brouard  4105:   firstwo=0;
1.217     brouard  4106:   firsthree=0;
1.218     brouard  4107:   firstfour=0;
1.164     brouard  4108:   jmin=100000;
1.126     brouard  4109:   jmax=-1;
                   4110:   jmean=0.;
1.214     brouard  4111:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  4112:     mi=0;
                   4113:     m=firstpass;
1.214     brouard  4114:     while(s[m][i] <= nlstate){  /* a live state */
1.216     brouard  4115:       if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
1.126     brouard  4116:        mw[++mi][i]=m;
1.216     brouard  4117:       }
                   4118:       if(m >=lastpass){
                   4119:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
1.217     brouard  4120:          if(firsthree == 0){
                   4121:            printf("Information! Unknown health 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.\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);
                   4122:            firsthree=1;
                   4123:          }
1.218     brouard  4124:          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.\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);
1.216     brouard  4125:          mw[++mi][i]=m;
                   4126:        }
                   4127:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4128:          nbwarn++;
                   4129:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4130:            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);
                   4131:            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.\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);
                   4132:          }
                   4133:          break;
                   4134:        }
1.126     brouard  4135:        break;
1.216     brouard  4136:       }
1.126     brouard  4137:       else
                   4138:        m++;
                   4139:     }/* end while */
1.216     brouard  4140:     
                   4141:     /* After last pass */
1.214     brouard  4142:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  4143:       mi++;    /* Death is another wave */
                   4144:       /* if(mi==0)  never been interviewed correctly before death */
                   4145:         /* Only death is a correct wave */
                   4146:       mw[mi][i]=m;
1.216     brouard  4147:     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
                   4148:       /* m++; */
                   4149:       /* mi++; */
                   4150:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4151:       /* mw[mi][i]=m; */
                   4152:       nberr++;
1.218     brouard  4153:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
                   4154:        if(firstwo==0){
                   4155:          printf("Error! Death for individual %ld line=%d  occurred %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 );
                   4156:          firstwo=1;
                   4157:        }
                   4158:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %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 );
                   4159:       }else{ /* end date of interview is known */
                   4160:        /* death is known but not confirmed by death status at any wave */
                   4161:        if(firstfour==0){
                   4162:          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 );
                   4163:          firstfour=1;
                   4164:        }
                   4165:        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  4166:       }
1.126     brouard  4167:     }
                   4168:     wav[i]=mi;
                   4169:     if(mi==0){
                   4170:       nbwarn++;
                   4171:       if(first==0){
                   4172:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4173:        first=1;
                   4174:       }
                   4175:       if(first==1){
                   4176:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   4177:       }
                   4178:     } /* end mi==0 */
                   4179:   } /* End individuals */
1.214     brouard  4180:   /* wav and mw are no more changed */
1.126     brouard  4181: 
1.214     brouard  4182:   
1.126     brouard  4183:   for(i=1; i<=imx; i++){
                   4184:     for(mi=1; mi<wav[i];mi++){
                   4185:       if (stepm <=0)
                   4186:        dh[mi][i]=1;
                   4187:       else{
                   4188:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4189:          if (agedc[i] < 2*AGESUP) {
                   4190:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4191:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4192:            else if(j<0){
                   4193:              nberr++;
                   4194:              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]);
                   4195:              j=1; /* Temporary Dangerous patch */
                   4196:              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);
                   4197:              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]);
                   4198:              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);
                   4199:            }
                   4200:            k=k+1;
                   4201:            if (j >= jmax){
                   4202:              jmax=j;
                   4203:              ijmax=i;
                   4204:            }
                   4205:            if (j <= jmin){
                   4206:              jmin=j;
                   4207:              ijmin=i;
                   4208:            }
                   4209:            sum=sum+j;
                   4210:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4211:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4212:          }
                   4213:        }
                   4214:        else{
                   4215:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   4216: /*       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]); */
                   4217: 
                   4218:          k=k+1;
                   4219:          if (j >= jmax) {
                   4220:            jmax=j;
                   4221:            ijmax=i;
                   4222:          }
                   4223:          else if (j <= jmin){
                   4224:            jmin=j;
                   4225:            ijmin=i;
                   4226:          }
                   4227:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4228:          /*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]);*/
                   4229:          if(j<0){
                   4230:            nberr++;
                   4231:            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]);
                   4232:            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]);
                   4233:          }
                   4234:          sum=sum+j;
                   4235:        }
                   4236:        jk= j/stepm;
                   4237:        jl= j -jk*stepm;
                   4238:        ju= j -(jk+1)*stepm;
                   4239:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4240:          if(jl==0){
                   4241:            dh[mi][i]=jk;
                   4242:            bh[mi][i]=0;
                   4243:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  4244:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  4245:            dh[mi][i]=jk+1;
                   4246:            bh[mi][i]=ju;
                   4247:          }
                   4248:        }else{
                   4249:          if(jl <= -ju){
                   4250:            dh[mi][i]=jk;
                   4251:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4252:                                 * is higher than the multiple of stepm and negative otherwise.
                   4253:                                 */
                   4254:          }
                   4255:          else{
                   4256:            dh[mi][i]=jk+1;
                   4257:            bh[mi][i]=ju;
                   4258:          }
                   4259:          if(dh[mi][i]==0){
                   4260:            dh[mi][i]=1; /* At least one step */
                   4261:            bh[mi][i]=ju; /* At least one step */
                   4262:            /*  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);*/
                   4263:          }
                   4264:        } /* end if mle */
                   4265:       }
                   4266:     } /* end wave */
                   4267:   }
                   4268:   jmean=sum/k;
                   4269:   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  4270:   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.126     brouard  4271:  }
                   4272: 
                   4273: /*********** Tricode ****************************/
1.220     brouard  4274:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4275: {
1.144     brouard  4276:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4277:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
1.169     brouard  4278:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  4279:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.220     brouard  4280:    * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
1.144     brouard  4281:   */
1.130     brouard  4282: 
1.145     brouard  4283:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4284:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4285:   int cptcode=0; /* Modality max of covariates j */
                   4286:   int modmincovj=0; /* Modality min of covariates j */
                   4287: 
                   4288: 
1.220     brouard  4289:   /* cptcoveff=0;  */
                   4290:        *cptcov=0;
1.126     brouard  4291:  
1.144     brouard  4292:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4293: 
1.145     brouard  4294:   /* Loop on covariates without age and products */
1.186     brouard  4295:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4296:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4297:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.219     brouard  4298:                                                                                                                                modality of this covariate Vj*/ 
1.145     brouard  4299:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
1.219     brouard  4300:                                                                                                                                                * If product of Vn*Vm, still boolean *:
                   4301:                                                                                                                                                * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4302:                                                                                                                                                * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
1.145     brouard  4303:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  4304:                                      modality of the nth covariate of individual i. */
1.145     brouard  4305:       if (ij > modmaxcovj)
                   4306:         modmaxcovj=ij; 
                   4307:       else if (ij < modmincovj) 
1.219     brouard  4308:                                modmincovj=ij; 
1.145     brouard  4309:       if ((ij < -1) && (ij > NCOVMAX)){
1.219     brouard  4310:                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4311:                                exit(1);
1.145     brouard  4312:       }else
1.136     brouard  4313:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4314:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4315:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4316:       /* getting the maximum value of the modality of the covariate
                   4317:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4318:         female is 1, then modmaxcovj=1.*/
1.192     brouard  4319:     } /* end for loop on individuals i */
1.145     brouard  4320:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4321:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145     brouard  4322:     cptcode=modmaxcovj;
1.137     brouard  4323:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  4324:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4325:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4326:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4327:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4328:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
1.219     brouard  4329:                                if( k != -1){
                   4330:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4331:                                                                                                                 covariate for which somebody answered excluding 
                   4332:                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4333:                                }
                   4334:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4335:                                                                                                                                covariate for which somebody answered including 
                   4336:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4337:       }
                   4338:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.219     brouard  4339:                                 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4340:     } /* Ndum[-1] number of undefined modalities */
1.219     brouard  4341:                
1.136     brouard  4342:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4343:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4344:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145     brouard  4345:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4346:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4347:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4348:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4349:        nbcode[Tvar[j]][ij]=k;
                   4350:        nbcode[Tvar[j]][1]=0;
                   4351:        nbcode[Tvar[j]][2]=1;
                   4352:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4353:        To be continued (not working yet).
1.145     brouard  4354:     */
1.197     brouard  4355:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4356:     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*/
                   4357:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.219     brouard  4358:                                break;
                   4359:                        }
1.192     brouard  4360:        ij++;
1.197     brouard  4361:        nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
1.192     brouard  4362:        cptcode = ij; /* New max modality for covar j */
                   4363:     } /* end of loop on modality i=-1 to 1 or more */
                   4364:       
                   4365:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4366:     /*         /\*recode from 0 *\/ */
                   4367:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4368:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4369:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4370:     /*         } */
                   4371:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4372:     /*         if (ij > ncodemax[j]) { */
                   4373:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4374:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4375:     /*           break; */
                   4376:     /*         } */
                   4377:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4378:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4379:   
1.219     brouard  4380:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4381:   
1.187     brouard  4382:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.219     brouard  4383:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4384:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   4385:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
                   4386:        } 
                   4387:        
                   4388:        ij=0;
                   4389:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4390:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4391:                if((Ndum[i]!=0) && (i<=ncovcol)){
                   4392:                        ij++;
                   4393:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4394:                        Tvaraff[ij]=i; /*For printing (unclear) */
                   4395:                }else{
                   4396:                        /* Tvaraff[ij]=0; */
                   4397:                }
                   4398:        }
                   4399:        /* ij--; */
1.220     brouard  4400:        /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4401:        *cptcov=ij; /*Number of total covariates*/
1.219     brouard  4402:        
1.126     brouard  4403: }
                   4404: 
1.145     brouard  4405: 
1.126     brouard  4406: /*********** Health Expectancies ****************/
                   4407: 
1.127     brouard  4408: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126     brouard  4409: 
                   4410: {
                   4411:   /* Health expectancies, no variances */
1.164     brouard  4412:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4413:   int nhstepma, nstepma; /* Decreasing with age */
                   4414:   double age, agelim, hf;
                   4415:   double ***p3mat;
                   4416:   double eip;
                   4417: 
                   4418:   pstamp(ficreseij);
                   4419:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4420:   fprintf(ficreseij,"# Age");
                   4421:   for(i=1; i<=nlstate;i++){
                   4422:     for(j=1; j<=nlstate;j++){
                   4423:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4424:     }
                   4425:     fprintf(ficreseij," e%1d. ",i);
                   4426:   }
                   4427:   fprintf(ficreseij,"\n");
                   4428: 
                   4429:   
                   4430:   if(estepm < stepm){
                   4431:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4432:   }
                   4433:   else  hstepm=estepm;   
                   4434:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4435:    * This is mainly to measure the difference between two models: for example
                   4436:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4437:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4438:    * progression in between and thus overestimating or underestimating according
                   4439:    * to the curvature of the survival function. If, for the same date, we 
                   4440:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4441:    * to compare the new estimate of Life expectancy with the same linear 
                   4442:    * hypothesis. A more precise result, taking into account a more precise
                   4443:    * curvature will be obtained if estepm is as small as stepm. */
                   4444: 
                   4445:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4446:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4447:      nhstepm is the number of hstepm from age to agelim 
                   4448:      nstepm is the number of stepm from age to agelin. 
                   4449:      Look at hpijx to understand the reason of that which relies in memory size
                   4450:      and note for a fixed period like estepm months */
                   4451:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4452:      survival function given by stepm (the optimization length). Unfortunately it
                   4453:      means that if the survival funtion is printed only each two years of age and if
                   4454:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4455:      results. So we changed our mind and took the option of the best precision.
                   4456:   */
                   4457:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4458: 
                   4459:   agelim=AGESUP;
                   4460:   /* If stepm=6 months */
                   4461:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4462:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4463:     
                   4464: /* nhstepm age range expressed in number of stepm */
                   4465:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4466:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4467:   /* if (stepm >= YEARM) hstepm=1;*/
                   4468:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4469:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4470: 
                   4471:   for (age=bage; age<=fage; age ++){ 
                   4472:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4473:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4474:     /* if (stepm >= YEARM) hstepm=1;*/
                   4475:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4476: 
                   4477:     /* If stepm=6 months */
                   4478:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4479:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4480:     
                   4481:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4482:     
                   4483:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4484:     
                   4485:     printf("%d|",(int)age);fflush(stdout);
                   4486:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4487:     
                   4488:     /* Computing expectancies */
                   4489:     for(i=1; i<=nlstate;i++)
                   4490:       for(j=1; j<=nlstate;j++)
                   4491:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4492:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4493:          
                   4494:          /* 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]);*/
                   4495: 
                   4496:        }
                   4497: 
                   4498:     fprintf(ficreseij,"%3.0f",age );
                   4499:     for(i=1; i<=nlstate;i++){
                   4500:       eip=0;
                   4501:       for(j=1; j<=nlstate;j++){
                   4502:        eip +=eij[i][j][(int)age];
                   4503:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4504:       }
                   4505:       fprintf(ficreseij,"%9.4f", eip );
                   4506:     }
                   4507:     fprintf(ficreseij,"\n");
                   4508:     
                   4509:   }
                   4510:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4511:   printf("\n");
                   4512:   fprintf(ficlog,"\n");
                   4513:   
                   4514: }
                   4515: 
1.127     brouard  4516: 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[] )
1.126     brouard  4517: 
                   4518: {
                   4519:   /* Covariances of health expectancies eij and of total life expectancies according
                   4520:    to initial status i, ei. .
                   4521:   */
                   4522:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4523:   int nhstepma, nstepma; /* Decreasing with age */
                   4524:   double age, agelim, hf;
                   4525:   double ***p3matp, ***p3matm, ***varhe;
                   4526:   double **dnewm,**doldm;
                   4527:   double *xp, *xm;
                   4528:   double **gp, **gm;
                   4529:   double ***gradg, ***trgradg;
                   4530:   int theta;
                   4531: 
                   4532:   double eip, vip;
                   4533: 
                   4534:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4535:   xp=vector(1,npar);
                   4536:   xm=vector(1,npar);
                   4537:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4538:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4539:   
                   4540:   pstamp(ficresstdeij);
                   4541:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4542:   fprintf(ficresstdeij,"# Age");
                   4543:   for(i=1; i<=nlstate;i++){
                   4544:     for(j=1; j<=nlstate;j++)
                   4545:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4546:     fprintf(ficresstdeij," e%1d. ",i);
                   4547:   }
                   4548:   fprintf(ficresstdeij,"\n");
                   4549: 
                   4550:   pstamp(ficrescveij);
                   4551:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4552:   fprintf(ficrescveij,"# Age");
                   4553:   for(i=1; i<=nlstate;i++)
                   4554:     for(j=1; j<=nlstate;j++){
                   4555:       cptj= (j-1)*nlstate+i;
                   4556:       for(i2=1; i2<=nlstate;i2++)
                   4557:        for(j2=1; j2<=nlstate;j2++){
                   4558:          cptj2= (j2-1)*nlstate+i2;
                   4559:          if(cptj2 <= cptj)
                   4560:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4561:        }
                   4562:     }
                   4563:   fprintf(ficrescveij,"\n");
                   4564:   
                   4565:   if(estepm < stepm){
                   4566:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4567:   }
                   4568:   else  hstepm=estepm;   
                   4569:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4570:    * This is mainly to measure the difference between two models: for example
                   4571:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4572:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4573:    * progression in between and thus overestimating or underestimating according
                   4574:    * to the curvature of the survival function. If, for the same date, we 
                   4575:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4576:    * to compare the new estimate of Life expectancy with the same linear 
                   4577:    * hypothesis. A more precise result, taking into account a more precise
                   4578:    * curvature will be obtained if estepm is as small as stepm. */
                   4579: 
                   4580:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4581:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4582:      nhstepm is the number of hstepm from age to agelim 
                   4583:      nstepm is the number of stepm from age to agelin. 
                   4584:      Look at hpijx to understand the reason of that which relies in memory size
                   4585:      and note for a fixed period like estepm months */
                   4586:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4587:      survival function given by stepm (the optimization length). Unfortunately it
                   4588:      means that if the survival funtion is printed only each two years of age and if
                   4589:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4590:      results. So we changed our mind and took the option of the best precision.
                   4591:   */
                   4592:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4593: 
                   4594:   /* If stepm=6 months */
                   4595:   /* nhstepm age range expressed in number of stepm */
                   4596:   agelim=AGESUP;
                   4597:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4598:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4599:   /* if (stepm >= YEARM) hstepm=1;*/
                   4600:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4601:   
                   4602:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4603:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4604:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4605:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4606:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4607:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4608: 
                   4609:   for (age=bage; age<=fage; age ++){ 
                   4610:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4611:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4612:     /* if (stepm >= YEARM) hstepm=1;*/
                   4613:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  4614:                
1.126     brouard  4615:     /* If stepm=6 months */
                   4616:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4617:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4618:     
                   4619:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  4620:                
1.126     brouard  4621:     /* Computing  Variances of health expectancies */
                   4622:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4623:        decrease memory allocation */
                   4624:     for(theta=1; theta <=npar; theta++){
                   4625:       for(i=1; i<=npar; i++){ 
1.218     brouard  4626:                                xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4627:                                xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  4628:       }
                   4629:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4630:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  4631:                        
1.126     brouard  4632:       for(j=1; j<= nlstate; j++){
1.218     brouard  4633:                                for(i=1; i<=nlstate; i++){
                   4634:                                        for(h=0; h<=nhstepm-1; h++){
                   4635:                                                gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4636:                                                gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4637:                                        }
                   4638:                                }
1.126     brouard  4639:       }
1.218     brouard  4640:                        
1.126     brouard  4641:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.218     brouard  4642:                                for(h=0; h<=nhstepm-1; h++){
                   4643:                                        gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4644:                                }
1.126     brouard  4645:     }/* End theta */
                   4646:     
                   4647:     
                   4648:     for(h=0; h<=nhstepm-1; h++)
                   4649:       for(j=1; j<=nlstate*nlstate;j++)
1.218     brouard  4650:                                for(theta=1; theta <=npar; theta++)
                   4651:                                        trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  4652:     
1.218     brouard  4653:                
                   4654:                for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  4655:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.218     brouard  4656:                                varhe[ij][ji][(int)age] =0.;
                   4657:                
                   4658:                printf("%d|",(int)age);fflush(stdout);
                   4659:                fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4660:                for(h=0;h<=nhstepm-1;h++){
1.126     brouard  4661:       for(k=0;k<=nhstepm-1;k++){
1.218     brouard  4662:                                matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4663:                                matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4664:                                for(ij=1;ij<=nlstate*nlstate;ij++)
                   4665:                                        for(ji=1;ji<=nlstate*nlstate;ji++)
                   4666:                                                varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  4667:       }
                   4668:     }
1.218     brouard  4669:                
1.126     brouard  4670:     /* Computing expectancies */
                   4671:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4672:     for(i=1; i<=nlstate;i++)
                   4673:       for(j=1; j<=nlstate;j++)
1.218     brouard  4674:                                for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4675:                                        eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4676:                                        
                   4677:                                        /* 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]);*/
                   4678:                                        
                   4679:                                }
                   4680:                
1.126     brouard  4681:     fprintf(ficresstdeij,"%3.0f",age );
                   4682:     for(i=1; i<=nlstate;i++){
                   4683:       eip=0.;
                   4684:       vip=0.;
                   4685:       for(j=1; j<=nlstate;j++){
1.218     brouard  4686:                                eip += eij[i][j][(int)age];
                   4687:                                for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4688:                                        vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4689:                                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  4690:       }
                   4691:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4692:     }
                   4693:     fprintf(ficresstdeij,"\n");
1.218     brouard  4694:                
1.126     brouard  4695:     fprintf(ficrescveij,"%3.0f",age );
                   4696:     for(i=1; i<=nlstate;i++)
                   4697:       for(j=1; j<=nlstate;j++){
1.218     brouard  4698:                                cptj= (j-1)*nlstate+i;
                   4699:                                for(i2=1; i2<=nlstate;i2++)
                   4700:                                        for(j2=1; j2<=nlstate;j2++){
                   4701:                                                cptj2= (j2-1)*nlstate+i2;
                   4702:                                                if(cptj2 <= cptj)
                   4703:                                                        fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4704:                                        }
1.126     brouard  4705:       }
                   4706:     fprintf(ficrescveij,"\n");
1.218     brouard  4707:                
1.126     brouard  4708:   }
                   4709:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4710:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4711:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4712:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4713:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4714:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4715:   printf("\n");
                   4716:   fprintf(ficlog,"\n");
1.218     brouard  4717:        
1.126     brouard  4718:   free_vector(xm,1,npar);
                   4719:   free_vector(xp,1,npar);
                   4720:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4721:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4722:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4723: }
1.218     brouard  4724:  
1.126     brouard  4725: /************ Variance ******************/
1.209     brouard  4726:  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[])
1.218     brouard  4727:  {
                   4728:    /* Variance of health expectancies */
                   4729:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4730:    /* double **newm;*/
                   4731:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4732:   
                   4733:    /* int movingaverage(); */
                   4734:    double **dnewm,**doldm;
                   4735:    double **dnewmp,**doldmp;
                   4736:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4737:    int k;
                   4738:    double *xp;
                   4739:    double **gp, **gm;  /* for var eij */
                   4740:    double ***gradg, ***trgradg; /*for var eij */
                   4741:    double **gradgp, **trgradgp; /* for var p point j */
                   4742:    double *gpp, *gmp; /* for var p point j */
                   4743:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4744:    double ***p3mat;
                   4745:    double age,agelim, hf;
                   4746:    /* double ***mobaverage; */
                   4747:    int theta;
                   4748:    char digit[4];
                   4749:    char digitp[25];
                   4750: 
                   4751:    char fileresprobmorprev[FILENAMELENGTH];
                   4752: 
                   4753:    if(popbased==1){
                   4754:      if(mobilav!=0)
                   4755:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4756:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4757:    }
                   4758:    else 
                   4759:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  4760: 
1.218     brouard  4761:    /* if (mobilav!=0) { */
                   4762:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4763:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4764:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4765:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4766:    /*   } */
                   4767:    /* } */
                   4768: 
                   4769:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4770:    sprintf(digit,"%-d",ij);
                   4771:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4772:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4773:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4774:    strcat(fileresprobmorprev,fileresu);
                   4775:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4776:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4777:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4778:    }
                   4779:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4780:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4781:    pstamp(ficresprobmorprev);
                   4782:    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);
                   4783:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4784:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4785:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4786:      for(i=1; i<=nlstate;i++)
                   4787:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4788:    }  
                   4789:    fprintf(ficresprobmorprev,"\n");
                   4790:   
                   4791:    fprintf(ficgp,"\n# Routine varevsij");
                   4792:    fprintf(ficgp,"\nunset title \n");
                   4793:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4794:    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");
                   4795:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4796:    /*   } */
                   4797:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4798:    pstamp(ficresvij);
                   4799:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4800:    if(popbased==1)
                   4801:      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);
                   4802:    else
                   4803:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4804:    fprintf(ficresvij,"# Age");
                   4805:    for(i=1; i<=nlstate;i++)
                   4806:      for(j=1; j<=nlstate;j++)
                   4807:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4808:    fprintf(ficresvij,"\n");
                   4809: 
                   4810:    xp=vector(1,npar);
                   4811:    dnewm=matrix(1,nlstate,1,npar);
                   4812:    doldm=matrix(1,nlstate,1,nlstate);
                   4813:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4814:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4815: 
                   4816:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4817:    gpp=vector(nlstate+1,nlstate+ndeath);
                   4818:    gmp=vector(nlstate+1,nlstate+ndeath);
                   4819:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  4820:   
1.218     brouard  4821:    if(estepm < stepm){
                   4822:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   4823:    }
                   4824:    else  hstepm=estepm;   
                   4825:    /* For example we decided to compute the life expectancy with the smallest unit */
                   4826:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4827:       nhstepm is the number of hstepm from age to agelim 
                   4828:       nstepm is the number of stepm from age to agelim. 
                   4829:       Look at function hpijx to understand why because of memory size limitations, 
                   4830:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   4831:       survival function given by stepm (the optimization length). Unfortunately it
                   4832:       means that if the survival funtion is printed every two years of age and if
                   4833:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4834:       results. So we changed our mind and took the option of the best precision.
                   4835:    */
                   4836:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4837:    agelim = AGESUP;
                   4838:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4839:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4840:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4841:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4842:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4843:      gp=matrix(0,nhstepm,1,nlstate);
                   4844:      gm=matrix(0,nhstepm,1,nlstate);
                   4845:                
                   4846:                
                   4847:      for(theta=1; theta <=npar; theta++){
                   4848:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4849:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4850:        }
                   4851:                        
                   4852:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4853:                        
                   4854:        if (popbased==1) {
                   4855:         if(mobilav ==0){
                   4856:           for(i=1; i<=nlstate;i++)
                   4857:             prlim[i][i]=probs[(int)age][i][ij];
                   4858:         }else{ /* mobilav */ 
                   4859:           for(i=1; i<=nlstate;i++)
                   4860:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4861:         }
                   4862:        }
                   4863:                        
                   4864:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   4865:        for(j=1; j<= nlstate; j++){
                   4866:         for(h=0; h<=nhstepm; h++){
                   4867:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4868:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4869:         }
                   4870:        }
                   4871:        /* Next for computing probability of death (h=1 means
                   4872:          computed over hstepm matrices product = hstepm*stepm months) 
                   4873:          as a weighted average of prlim.
                   4874:        */
                   4875:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4876:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4877:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4878:        }    
                   4879:        /* end probability of death */
                   4880:                        
                   4881:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4882:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4883:                        
                   4884:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   4885:                        
                   4886:        if (popbased==1) {
                   4887:         if(mobilav ==0){
                   4888:           for(i=1; i<=nlstate;i++)
                   4889:             prlim[i][i]=probs[(int)age][i][ij];
                   4890:         }else{ /* mobilav */ 
                   4891:           for(i=1; i<=nlstate;i++)
                   4892:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4893:         }
                   4894:        }
                   4895:                        
                   4896:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4897:                        
                   4898:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   4899:         for(h=0; h<=nhstepm; h++){
                   4900:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4901:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4902:         }
                   4903:        }
                   4904:        /* This for computing probability of death (h=1 means
                   4905:          computed over hstepm matrices product = hstepm*stepm months) 
                   4906:          as a weighted average of prlim.
                   4907:        */
                   4908:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4909:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4910:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4911:        }    
                   4912:        /* end probability of death */
                   4913:                        
                   4914:        for(j=1; j<= nlstate; j++) /* vareij */
                   4915:         for(h=0; h<=nhstepm; h++){
                   4916:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4917:         }
                   4918:                        
                   4919:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4920:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4921:        }
                   4922:                        
                   4923:      } /* End theta */
                   4924:                
                   4925:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4926:                
                   4927:      for(h=0; h<=nhstepm; h++) /* veij */
                   4928:        for(j=1; j<=nlstate;j++)
                   4929:         for(theta=1; theta <=npar; theta++)
                   4930:           trgradg[h][j][theta]=gradg[h][theta][j];
                   4931:                
                   4932:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4933:        for(theta=1; theta <=npar; theta++)
                   4934:         trgradgp[j][theta]=gradgp[theta][j];
                   4935:                
                   4936:                
                   4937:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4938:      for(i=1;i<=nlstate;i++)
                   4939:        for(j=1;j<=nlstate;j++)
                   4940:         vareij[i][j][(int)age] =0.;
                   4941:                
                   4942:      for(h=0;h<=nhstepm;h++){
                   4943:        for(k=0;k<=nhstepm;k++){
                   4944:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4945:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4946:         for(i=1;i<=nlstate;i++)
                   4947:           for(j=1;j<=nlstate;j++)
                   4948:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4949:        }
                   4950:      }
                   4951:                
                   4952:      /* pptj */
                   4953:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4954:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4955:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4956:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4957:         varppt[j][i]=doldmp[j][i];
                   4958:      /* end ppptj */
                   4959:      /*  x centered again */
                   4960:                
                   4961:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4962:                
                   4963:      if (popbased==1) {
                   4964:        if(mobilav ==0){
                   4965:         for(i=1; i<=nlstate;i++)
                   4966:           prlim[i][i]=probs[(int)age][i][ij];
                   4967:        }else{ /* mobilav */ 
                   4968:         for(i=1; i<=nlstate;i++)
                   4969:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   4970:        }
                   4971:      }
                   4972:                
                   4973:      /* This for computing probability of death (h=1 means
                   4974:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4975:        as a weighted average of prlim.
                   4976:      */
                   4977:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4978:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4979:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4980:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4981:      }    
                   4982:      /* end probability of death */
                   4983:                
                   4984:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4985:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4986:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4987:        for(i=1; i<=nlstate;i++){
                   4988:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4989:        }
                   4990:      } 
                   4991:      fprintf(ficresprobmorprev,"\n");
                   4992:                
                   4993:      fprintf(ficresvij,"%.0f ",age );
                   4994:      for(i=1; i<=nlstate;i++)
                   4995:        for(j=1; j<=nlstate;j++){
                   4996:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4997:        }
                   4998:      fprintf(ficresvij,"\n");
                   4999:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5000:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5001:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5002:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5003:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5004:    } /* End age */
                   5005:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5006:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5007:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5008:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5009:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5010:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5011:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5012:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5013:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5014:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5015:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5016:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5017:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5018:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5019:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5020:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5021:    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);
                   5022:    /*  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  5023:     */
1.218     brouard  5024:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5025:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5026: 
1.218     brouard  5027:    free_vector(xp,1,npar);
                   5028:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5029:    free_matrix(dnewm,1,nlstate,1,npar);
                   5030:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5031:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5032:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5033:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5034:    fclose(ficresprobmorprev);
                   5035:    fflush(ficgp);
                   5036:    fflush(fichtm); 
                   5037:  }  /* end varevsij */
1.126     brouard  5038: 
                   5039: /************ Variance of prevlim ******************/
1.209     brouard  5040:  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[])
1.126     brouard  5041: {
1.205     brouard  5042:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5043:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5044: 
1.126     brouard  5045:   double **dnewm,**doldm;
                   5046:   int i, j, nhstepm, hstepm;
                   5047:   double *xp;
                   5048:   double *gp, *gm;
                   5049:   double **gradg, **trgradg;
1.208     brouard  5050:   double **mgm, **mgp;
1.126     brouard  5051:   double age,agelim;
                   5052:   int theta;
                   5053:   
                   5054:   pstamp(ficresvpl);
                   5055:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5056:   fprintf(ficresvpl,"# Age");
                   5057:   for(i=1; i<=nlstate;i++)
                   5058:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5059:   fprintf(ficresvpl,"\n");
                   5060: 
                   5061:   xp=vector(1,npar);
                   5062:   dnewm=matrix(1,nlstate,1,npar);
                   5063:   doldm=matrix(1,nlstate,1,nlstate);
                   5064:   
                   5065:   hstepm=1*YEARM; /* Every year of age */
                   5066:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5067:   agelim = AGESUP;
                   5068:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5069:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5070:     if (stepm >= YEARM) hstepm=1;
                   5071:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5072:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5073:     mgp=matrix(1,npar,1,nlstate);
                   5074:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5075:     gp=vector(1,nlstate);
                   5076:     gm=vector(1,nlstate);
                   5077: 
                   5078:     for(theta=1; theta <=npar; theta++){
                   5079:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5080:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5081:       }
1.209     brouard  5082:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5083:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5084:       else
                   5085:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5086:       for(i=1;i<=nlstate;i++){
1.126     brouard  5087:        gp[i] = prlim[i][i];
1.208     brouard  5088:        mgp[theta][i] = prlim[i][i];
                   5089:       }
1.126     brouard  5090:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5091:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5092:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5093:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5094:       else
                   5095:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5096:       for(i=1;i<=nlstate;i++){
1.126     brouard  5097:        gm[i] = prlim[i][i];
1.208     brouard  5098:        mgm[theta][i] = prlim[i][i];
                   5099:       }
1.126     brouard  5100:       for(i=1;i<=nlstate;i++)
                   5101:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5102:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5103:     } /* End theta */
                   5104: 
                   5105:     trgradg =matrix(1,nlstate,1,npar);
                   5106: 
                   5107:     for(j=1; j<=nlstate;j++)
                   5108:       for(theta=1; theta <=npar; theta++)
                   5109:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5110:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5111:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5112:     /*   for(j=1; j<=nlstate;j++){ */
                   5113:     /*         printf(" %d ",j); */
                   5114:     /*         for(theta=1; theta <=npar; theta++) */
                   5115:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5116:     /*         printf("\n "); */
                   5117:     /*   } */
                   5118:     /* } */
                   5119:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5120:     /*   printf("\n gradg %d ",(int)age); */
                   5121:     /*   for(j=1; j<=nlstate;j++){ */
                   5122:     /*         printf("%d ",j); */
                   5123:     /*         for(theta=1; theta <=npar; theta++) */
                   5124:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5125:     /*         printf("\n "); */
                   5126:     /*   } */
                   5127:     /* } */
1.126     brouard  5128: 
                   5129:     for(i=1;i<=nlstate;i++)
                   5130:       varpl[i][(int)age] =0.;
1.209     brouard  5131:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5132:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5133:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5134:     }else{
1.126     brouard  5135:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5136:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5137:     }
1.126     brouard  5138:     for(i=1;i<=nlstate;i++)
                   5139:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5140: 
                   5141:     fprintf(ficresvpl,"%.0f ",age );
                   5142:     for(i=1; i<=nlstate;i++)
                   5143:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5144:     fprintf(ficresvpl,"\n");
                   5145:     free_vector(gp,1,nlstate);
                   5146:     free_vector(gm,1,nlstate);
1.208     brouard  5147:     free_matrix(mgm,1,npar,1,nlstate);
                   5148:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5149:     free_matrix(gradg,1,npar,1,nlstate);
                   5150:     free_matrix(trgradg,1,nlstate,1,npar);
                   5151:   } /* End age */
                   5152: 
                   5153:   free_vector(xp,1,npar);
                   5154:   free_matrix(doldm,1,nlstate,1,npar);
                   5155:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5156: 
                   5157: }
                   5158: 
                   5159: /************ Variance of one-step probabilities  ******************/
                   5160: 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[])
                   5161: {
1.164     brouard  5162:   int i, j=0,  k1, l1, tj;
1.126     brouard  5163:   int k2, l2, j1,  z1;
1.164     brouard  5164:   int k=0, l;
1.145     brouard  5165:   int first=1, first1, first2;
1.126     brouard  5166:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5167:   double **dnewm,**doldm;
                   5168:   double *xp;
                   5169:   double *gp, *gm;
                   5170:   double **gradg, **trgradg;
                   5171:   double **mu;
1.164     brouard  5172:   double age, cov[NCOVMAX+1];
1.126     brouard  5173:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5174:   int theta;
                   5175:   char fileresprob[FILENAMELENGTH];
                   5176:   char fileresprobcov[FILENAMELENGTH];
                   5177:   char fileresprobcor[FILENAMELENGTH];
                   5178:   double ***varpij;
                   5179: 
1.201     brouard  5180:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  5181:   strcat(fileresprob,fileres);
                   5182:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5183:     printf("Problem with resultfile: %s\n", fileresprob);
                   5184:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5185:   }
1.201     brouard  5186:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  5187:   strcat(fileresprobcov,fileresu);
1.126     brouard  5188:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5189:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   5190:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5191:   }
1.201     brouard  5192:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  5193:   strcat(fileresprobcor,fileresu);
1.126     brouard  5194:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5195:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   5196:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5197:   }
                   5198:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5199:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5200:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5201:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5202:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5203:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5204:   pstamp(ficresprob);
                   5205:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5206:   fprintf(ficresprob,"# Age");
                   5207:   pstamp(ficresprobcov);
                   5208:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5209:   fprintf(ficresprobcov,"# Age");
                   5210:   pstamp(ficresprobcor);
                   5211:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5212:   fprintf(ficresprobcor,"# Age");
                   5213: 
                   5214: 
                   5215:   for(i=1; i<=nlstate;i++)
                   5216:     for(j=1; j<=(nlstate+ndeath);j++){
                   5217:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5218:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5219:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5220:     }  
                   5221:  /* fprintf(ficresprob,"\n");
                   5222:   fprintf(ficresprobcov,"\n");
                   5223:   fprintf(ficresprobcor,"\n");
                   5224:  */
1.131     brouard  5225:   xp=vector(1,npar);
1.126     brouard  5226:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5227:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5228:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5229:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5230:   first=1;
                   5231:   fprintf(ficgp,"\n# Routine varprob");
                   5232:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5233:   fprintf(fichtm,"\n");
                   5234: 
1.200     brouard  5235:   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);
1.197     brouard  5236:   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);
                   5237:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5238: and drawn. It helps understanding how is the covariance between two incidences.\
                   5239:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   5240:   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. \
                   5241: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5242: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5243: standard deviations wide on each axis. <br>\
                   5244:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5245:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5246: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5247: 
                   5248:   cov[1]=1;
1.145     brouard  5249:   /* tj=cptcoveff; */
                   5250:   tj = (int) pow(2,cptcoveff);
1.126     brouard  5251:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5252:   j1=0;
1.220     brouard  5253:   for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates */
                   5254:                if  (cptcovn>0) {
                   5255:                        fprintf(ficresprob, "\n#********** Variable "); 
                   5256:                        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5257:                        fprintf(ficresprob, "**********\n#\n");
                   5258:                        fprintf(ficresprobcov, "\n#********** Variable "); 
                   5259:                        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5260:                        fprintf(ficresprobcov, "**********\n#\n");
                   5261:                        
                   5262:                        fprintf(ficgp, "\n#********** Variable "); 
                   5263:                        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5264:                        fprintf(ficgp, "**********\n#\n");
                   5265:                        
                   5266:                        
                   5267:                        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   5268:                        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5269:                        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5270:                        
                   5271:                        fprintf(ficresprobcor, "\n#********** Variable ");    
                   5272:                        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5273:                        fprintf(ficresprobcor, "**********\n#");    
                   5274:                        if(invalidvarcomb[j1]){
                   5275:                          fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5276:                          fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5277:                          continue;
                   5278:                        }
                   5279:                }
                   5280:                gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5281:                trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5282:                gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5283:                gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5284:                for (age=bage; age<=fage; age ++){ 
                   5285:                        cov[2]=age;
                   5286:                        if(nagesqr==1)
                   5287:                                cov[3]= age*age;
                   5288:                        for (k=1; k<=cptcovn;k++) {
                   5289:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5290:                                /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5291:                                                                                                                                                                                                                                                                         * 1  1 1 1 1
                   5292:                                                                                                                                                                                                                                                                         * 2  2 1 1 1
                   5293:                                                                                                                                                                                                                                                                         * 3  1 2 1 1
                   5294:                                                                                                                                                                                                                                                                         */
                   5295:                                /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5296:                        }
                   5297:                        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5298:                        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5299:                        for (k=1; k<=cptcovprod;k++)
                   5300:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   5301:                        
                   5302:                        
                   5303:                        for(theta=1; theta <=npar; theta++){
                   5304:                                for(i=1; i<=npar; i++)
                   5305:                                        xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   5306:                                
                   5307:                                pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5308:                                
                   5309:                                k=0;
                   5310:                                for(i=1; i<= (nlstate); i++){
                   5311:                                        for(j=1; j<=(nlstate+ndeath);j++){
                   5312:                                                k=k+1;
                   5313:                                                gp[k]=pmmij[i][j];
                   5314:                                        }
                   5315:                                }
                   5316:                                
                   5317:                                for(i=1; i<=npar; i++)
                   5318:                                        xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   5319:                                
                   5320:                                pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5321:                                k=0;
                   5322:                                for(i=1; i<=(nlstate); i++){
                   5323:                                        for(j=1; j<=(nlstate+ndeath);j++){
                   5324:                                                k=k+1;
                   5325:                                                gm[k]=pmmij[i][j];
                   5326:                                        }
                   5327:                                }
                   5328:                                
                   5329:                                for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5330:                                        gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5331:                        }
1.126     brouard  5332: 
1.220     brouard  5333:                        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5334:                                for(theta=1; theta <=npar; theta++)
                   5335:                                        trgradg[j][theta]=gradg[theta][j];
                   5336:                        
                   5337:                        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5338:                        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   5339:                        
                   5340:                        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   5341:                        
                   5342:                        k=0;
                   5343:                        for(i=1; i<=(nlstate); i++){
                   5344:                                for(j=1; j<=(nlstate+ndeath);j++){
                   5345:                                        k=k+1;
                   5346:                                        mu[k][(int) age]=pmmij[i][j];
                   5347:                                }
                   5348:                        }
1.126     brouard  5349:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
1.220     brouard  5350:                                for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5351:                                        varpij[i][j][(int)age] = doldm[i][j];
                   5352:                        
                   5353:                        /*printf("\n%d ",(int)age);
                   5354:                                for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5355:                                printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5356:                                fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5357:                                }*/
                   5358:                        
                   5359:                        fprintf(ficresprob,"\n%d ",(int)age);
                   5360:                        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5361:                        fprintf(ficresprobcor,"\n%d ",(int)age);
                   5362:                        
                   5363:                        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5364:                                fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5365:                        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5366:                                fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5367:                                fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5368:                        }
                   5369:                        i=0;
                   5370:                        for (k=1; k<=(nlstate);k++){
                   5371:                                for (l=1; l<=(nlstate+ndeath);l++){ 
                   5372:                                        i++;
                   5373:                                        fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5374:                                        fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5375:                                        for (j=1; j<=i;j++){
                   5376:                                                /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5377:                                                fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5378:                                                fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5379:                                        }
                   5380:                                }
                   5381:                        }/* end of loop for state */
                   5382:                } /* end of loop for age */
                   5383:                free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5384:                free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5385:                free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5386:                free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5387:     
                   5388:                /* Confidence intervalle of pij  */
                   5389:                /*
                   5390:                        fprintf(ficgp,"\nunset parametric;unset label");
                   5391:                        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5392:                        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5393:                        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);
                   5394:                        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5395:                        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5396:                        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5397:                */
                   5398:                
                   5399:                /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5400:                first1=1;first2=2;
                   5401:                for (k2=1; k2<=(nlstate);k2++){
                   5402:                        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5403:                                if(l2==k2) continue;
                   5404:                                j=(k2-1)*(nlstate+ndeath)+l2;
                   5405:                                for (k1=1; k1<=(nlstate);k1++){
                   5406:                                        for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5407:                                                if(l1==k1) continue;
                   5408:                                                i=(k1-1)*(nlstate+ndeath)+l1;
                   5409:                                                if(i<=j) continue;
                   5410:                                                for (age=bage; age<=fage; age ++){ 
                   5411:                                                        if ((int)age %5==0){
                   5412:                                                                v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5413:                                                                v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5414:                                                                cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5415:                                                                mu1=mu[i][(int) age]/stepm*YEARM ;
                   5416:                                                                mu2=mu[j][(int) age]/stepm*YEARM;
                   5417:                                                                c12=cv12/sqrt(v1*v2);
                   5418:                                                                /* Computing eigen value of matrix of covariance */
                   5419:                                                                lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5420:                                                                lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5421:                                                                if ((lc2 <0) || (lc1 <0) ){
                   5422:                                                                        if(first2==1){
                   5423:                                                                                first1=0;
                   5424:                                                                                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);
                   5425:                                                                        }
                   5426:                                                                        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);
                   5427:                                                                        /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5428:                                                                        /* lc2=fabs(lc2); */
                   5429:                                                                }
                   5430:                                                                
                   5431:                                                                /* Eigen vectors */
                   5432:                                                                v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5433:                                                                /*v21=sqrt(1.-v11*v11); *//* error */
                   5434:                                                                v21=(lc1-v1)/cv12*v11;
                   5435:                                                                v12=-v21;
                   5436:                                                                v22=v11;
                   5437:                                                                tnalp=v21/v11;
                   5438:                                                                if(first1==1){
                   5439:                                                                        first1=0;
                   5440:                                                                        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);
                   5441:                                                                }
                   5442:                                                                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);
                   5443:                                                                /*printf(fignu*/
                   5444:                                                                /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5445:                                                                /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5446:                                                                if(first==1){
                   5447:                                                                        first=0;
                   5448:                                                                        fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5449:                                                                        fprintf(ficgp,"\nset parametric;unset label");
                   5450:                                                                        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);
                   5451:                                                                        fprintf(ficgp,"\nset ter svg size 640, 480");
                   5452:                                                                        fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   5453:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5454: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.220     brouard  5455:                                                                                                        subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2, \
                   5456:                                                                                                        subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5457:                                                                        fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5458:                                                                        fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5459:                                                                        fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  5460:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5461:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
1.220     brouard  5462:                    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",     \
                   5463:                                                                mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                            \
                   5464:                                                                mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5465:                                                                }else{
                   5466:                                                                        first=0;
                   5467:                                                                        fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5468:                                                                        fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5469:                                                                        fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5470:                                                                        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", \
                   5471:                                                                                                        mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                    \
                   5472:                                                                                                        mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5473:                                                                }/* if first */
                   5474:                                                        } /* age mod 5 */
                   5475:                                                } /* end loop age */
                   5476:                                                fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5477:                                                first=1;
                   5478:                                        } /*l12 */
                   5479:                                } /* k12 */
                   5480:                        } /*l1 */
                   5481:                }/* k1 */
                   5482:        }  /* loop on combination of covariates j1 */
1.126     brouard  5483:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5484:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5485:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5486:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5487:   free_vector(xp,1,npar);
                   5488:   fclose(ficresprob);
                   5489:   fclose(ficresprobcov);
                   5490:   fclose(ficresprobcor);
                   5491:   fflush(ficgp);
                   5492:   fflush(fichtmcov);
                   5493: }
                   5494: 
                   5495: 
                   5496: /******************* Printing html file ***********/
1.201     brouard  5497: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5498:                  int lastpass, int stepm, int weightopt, char model[],\
                   5499:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5500:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5501:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5502:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5503:   int jj1, k1, i1, cpt;
                   5504: 
                   5505:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5506:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5507: </ul>");
1.214     brouard  5508:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5509:    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",
                   5510:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5511:    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  5512:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5513:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5514:    fprintf(fichtm,"\
                   5515:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5516:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5517:    fprintf(fichtm,"\
1.217     brouard  5518:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5519:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5520:    fprintf(fichtm,"\
1.126     brouard  5521:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5522:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5523:    fprintf(fichtm,"\
1.217     brouard  5524:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5525:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5526:    fprintf(fichtm,"\
1.211     brouard  5527:  - (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  5528:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5529:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5530:    if(prevfcast==1){
                   5531:      fprintf(fichtm,"\
                   5532:  - Prevalence projections by age and states:                           \
1.201     brouard  5533:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5534:    }
1.126     brouard  5535: 
                   5536: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5537: 
1.145     brouard  5538:  m=pow(2,cptcoveff);
1.126     brouard  5539:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5540: 
                   5541:  jj1=0;
                   5542:  for(k1=1; k1<=m;k1++){
1.220     brouard  5543: 
1.192     brouard  5544:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.220     brouard  5545:         jj1++;
                   5546:         if (cptcovn > 0) {
                   5547:                 fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5548:                 for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   5549:                         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5550:                         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   5551:                 }
                   5552:                 fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5553:                 if(invalidvarcomb[k1]){
                   5554:                         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   5555:                         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   5556:                         continue;
                   5557:                 }
                   5558:         }
                   5559:         /* aij, bij */
                   5560:         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.svg\">%s_%d-1.svg</a><br> \
1.211     brouard  5561: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.220     brouard  5562:         /* Pij */
                   5563:         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.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  5564: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.220     brouard  5565:         /* Quasi-incidences */
                   5566:         fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   5567:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  5568:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5569: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201     brouard  5570: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.220     brouard  5571:         /* Survival functions (period) in state j */
                   5572:         for(cpt=1; cpt<=nlstate;cpt++){
                   5573:                 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.svg\">%s%d_%d.svg</a><br> \
1.201     brouard  5574: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
1.220     brouard  5575:         }
                   5576:         /* State specific survival functions (period) */
                   5577:         for(cpt=1; cpt<=nlstate;cpt++){
                   5578:                 fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
                   5579:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  5580:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
1.220     brouard  5581:         }
                   5582:         /* Period (stable) prevalence in each health state */
                   5583:         for(cpt=1; cpt<=nlstate;cpt++){
                   5584:                 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.svg\">%s_%d-%d.svg</a><br> \
1.201     brouard  5585: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
1.220     brouard  5586:         }
                   5587:         if(backcast==1){
1.217     brouard  5588:      /* Period (stable) back prevalence in each health state */
                   5589:      for(cpt=1; cpt<=nlstate;cpt++){
                   5590:        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.svg\">%s_%d-%d.svg</a><br> \
                   5591: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
                   5592:      }
1.220     brouard  5593:         }
                   5594:         if(prevfcast==1){
                   5595:                 /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5596:                 for(cpt=1; cpt<=nlstate;cpt++){
                   5597:                         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.svg\">%s%d_%d.svg</a><br> \
1.213     brouard  5598: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
1.220     brouard  5599:                 }
                   5600:         }
                   5601:         
                   5602:         for(cpt=1; cpt<=nlstate;cpt++) {
                   5603:                 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.svg\">%s_%d%d.svg</a> <br> \
1.201     brouard  5604: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.220     brouard  5605:         }
1.192     brouard  5606:    /* } /\* end i1 *\/ */
1.126     brouard  5607:  }/* End k1 */
                   5608:  fprintf(fichtm,"</ul>");
                   5609: 
                   5610:  fprintf(fichtm,"\
                   5611: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5612:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5613:  - 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  5614: But because parameters are usually highly correlated (a higher incidence of disability \
                   5615: and a higher incidence of recovery can give very close observed transition) it might \
                   5616: be very useful to look not only at linear confidence intervals estimated from the \
                   5617: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5618: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5619: covariance matrix of the one-step probabilities. \
                   5620: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5621: 
1.193     brouard  5622:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5623:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5624:  fprintf(fichtm,"\
                   5625:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5626:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5627: 
                   5628:  fprintf(fichtm,"\
                   5629:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5630:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5631:  fprintf(fichtm,"\
                   5632:  - 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): \
                   5633:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5634:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5635:  fprintf(fichtm,"\
                   5636:  - (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): \
                   5637:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5638:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5639:  fprintf(fichtm,"\
1.128     brouard  5640:  - 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.201     brouard  5641:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5642:  fprintf(fichtm,"\
1.128     brouard  5643:  - 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.201     brouard  5644:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5645:  fprintf(fichtm,"\
                   5646:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5647:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5648: 
                   5649: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5650: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5651: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5652: /*     <br>",fileres,fileres,fileres,fileres); */
                   5653: /*  else  */
                   5654: /*    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); */
                   5655:  fflush(fichtm);
                   5656:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5657: 
1.145     brouard  5658:  m=pow(2,cptcoveff);
1.126     brouard  5659:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5660: 
                   5661:  jj1=0;
                   5662:  for(k1=1; k1<=m;k1++){
1.220     brouard  5663:   /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5664:                 jj1++;
1.126     brouard  5665:      if (cptcovn > 0) {
                   5666:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5667:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.220     brouard  5668:                                                         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5669:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5670: 
                   5671:                         if(invalidvarcomb[k1]){
                   5672:                                 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   5673:                                 continue;
                   5674:                         }
1.126     brouard  5675:      }
                   5676:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  5677:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5678: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  5679: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  5680:      }
                   5681:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5682: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5683: true period expectancies (those weighted with period prevalences are also\
                   5684:  drawn in addition to the population based expectancies computed using\
1.218     brouard  5685:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  5686: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5687:    /* } /\* end i1 *\/ */
1.126     brouard  5688:  }/* End k1 */
                   5689:  fprintf(fichtm,"</ul>");
                   5690:  fflush(fichtm);
                   5691: }
                   5692: 
                   5693: /******************* Gnuplot file **************/
1.218     brouard  5694:  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  5695: 
                   5696:   char dirfileres[132],optfileres[132];
1.220     brouard  5697:        char gplotcondition[132];
1.164     brouard  5698:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5699:   int lv=0, vlv=0, kl=0;
1.130     brouard  5700:   int ng=0;
1.201     brouard  5701:   int vpopbased;
1.219     brouard  5702:        int ioffset; /* variable offset for columns */
                   5703: 
1.126     brouard  5704: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5705: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5706: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5707: /*   } */
                   5708: 
                   5709:   /*#ifdef windows */
                   5710:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5711:     /*#endif */
                   5712:   m=pow(2,cptcoveff);
                   5713: 
1.202     brouard  5714:   /* Contribution to likelihood */
                   5715:   /* Plot the probability implied in the likelihood */
                   5716:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5717:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5718:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5719:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5720: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5721:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5722: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5723:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5724:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5725:     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));
1.204     brouard  5726:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5727:     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));
1.204     brouard  5728:     for (i=1; i<= nlstate ; i ++) {
                   5729:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5730:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5731:       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);
1.204     brouard  5732:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.219     brouard  5733:                                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);
1.204     brouard  5734:       }
                   5735:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5736:     }
                   5737:     /* 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 */             
                   5738:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5739:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
1.203     brouard  5740:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5741:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5742: 
1.126     brouard  5743:   strcpy(dirfileres,optionfilefiname);
                   5744:   strcpy(optfileres,"vpl");
                   5745:  /* 1eme*/
1.211     brouard  5746:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.220     brouard  5747:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
1.211     brouard  5748:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5749:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.219     brouard  5750:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   5751:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   5752:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5753:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5754:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5755:                                vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   5756:                        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.220     brouard  5757:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5758:       }
                   5759:       fprintf(ficgp,"\n#\n");
1.220     brouard  5760:                        if(invalidvarcomb[k1]){
                   5761:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5762:                                                continue;
                   5763:                        }
1.211     brouard  5764: 
1.219     brouard  5765:                        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5766:                        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   5767:                        fprintf(ficgp,"set xlabel \"Age\" \n\
                   5768: set ylabel \"Probability\" \n  \
                   5769: set ter svg size 640, 480\n    \
1.201     brouard  5770: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219     brouard  5771:                        
                   5772:                        for (i=1; i<= nlstate ; i ++) {
                   5773:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5774:                                else        fprintf(ficgp," %%*lf (%%*lf)");
                   5775:                        }
                   5776:                        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                   5777:                        for (i=1; i<= nlstate ; i ++) {
                   5778:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5779:                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5780:                        } 
                   5781:                        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
                   5782:                        for (i=1; i<= nlstate ; i ++) {
                   5783:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5784:                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5785:                        }  
                   5786:                        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));
                   5787:                        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   5788:                                /* 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); */
                   5789:                                fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
                   5790:                                kl=0;
                   5791:                                for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   5792:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5793:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5794:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5795:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5796:                                        vlv= nbcode[Tvaraff[k]][lv];
                   5797:                                        kl++;
                   5798:                                        /* 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 *\/ */
                   5799:                                        /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5800:                                        /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5801:                                        /* ''  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*/
                   5802:                                        if(k==cptcoveff){
1.220     brouard  5803:                                                        fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   5804:                                                                                        6+(cpt-1),  cpt );
1.219     brouard  5805:                                        }else{
1.220     brouard  5806:                                                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
1.219     brouard  5807:                                                kl++;
                   5808:                                        }
                   5809:                                } /* end covariate */
                   5810:                        }
                   5811:                        fprintf(ficgp,"\nset out \n");
1.201     brouard  5812:     } /* k1 */
                   5813:   } /* cpt */
1.126     brouard  5814:   /*2 eme*/
                   5815:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5816: 
1.211     brouard  5817:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5818:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219     brouard  5819:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5820:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5821:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5822:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5823:                                vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  5824:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5825:       }
                   5826:       fprintf(ficgp,"\n#\n");
1.220     brouard  5827:                        if(invalidvarcomb[k1]){
                   5828:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5829:                                                continue;
                   5830:                        }
1.219     brouard  5831:                        
                   5832:                        fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5833:                        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5834:                                if(vpopbased==0)
                   5835:                                        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5836:                                else
                   5837:                                        fprintf(ficgp,"\nreplot ");
                   5838:                                for (i=1; i<= nlstate+1 ; i ++) {
                   5839:                                        k=2*i;
                   5840:                                        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);
                   5841:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5842:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5843:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5844:                                        }   
                   5845:                                        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5846:                                        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5847:                                        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);
                   5848:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5849:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5850:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5851:                                        }   
                   5852:                                        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5853:                                        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);
                   5854:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5855:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5856:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5857:                                        }   
                   5858:                                        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5859:                                        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5860:                                } /* state */
                   5861:                        } /* vpopbased */
                   5862:                        fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  5863:   } /* k1 */
1.219     brouard  5864:        
                   5865:        
1.126     brouard  5866:   /*3eme*/
                   5867:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5868: 
1.126     brouard  5869:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5870:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5871:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219     brouard  5872:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5873:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5874:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5875:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5876:                                vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  5877:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5878:       }
                   5879:       fprintf(ficgp,"\n#\n");
1.220     brouard  5880:                        if(invalidvarcomb[k1]){
                   5881:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5882:                                                continue;
                   5883:                        }
1.219     brouard  5884:                        
1.126     brouard  5885:       /*       k=2+nlstate*(2*cpt-2); */
                   5886:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5887:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5888:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5889: 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.126     brouard  5890:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.219     brouard  5891:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5892:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5893:                                fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5894:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5895:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5896:                                
1.126     brouard  5897:       */
                   5898:       for (i=1; i< nlstate ; i ++) {
1.219     brouard  5899:                                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);
                   5900:                                /*      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);*/
                   5901:                                
1.126     brouard  5902:       } 
1.201     brouard  5903:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126     brouard  5904:     }
                   5905:   }
                   5906:   
1.220     brouard  5907:        /* 4eme */
1.201     brouard  5908:   /* Survival functions (period) from state i in state j by initial state i */
                   5909:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
1.220     brouard  5910: 
1.201     brouard  5911:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5912:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5913:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  5914:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5915:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5916:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5917:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5918:                                vlv= nbcode[Tvaraff[k]][lv];
                   5919:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5920:       }
                   5921:       fprintf(ficgp,"\n#\n");
1.220     brouard  5922:                        if(invalidvarcomb[k1]){
                   5923:                                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5924:                                                        continue;
                   5925:                        }
                   5926:                        
1.201     brouard  5927:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5928:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  5929: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   5930: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  5931: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5932:       k=3;
1.201     brouard  5933:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  5934:                                if(i==1){
                   5935:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5936:                                }else{
                   5937:                                        fprintf(ficgp,", '' ");
                   5938:                                }
                   5939:                                l=(nlstate+ndeath)*(i-1)+1;
                   5940:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5941:                                for (j=2; j<= nlstate+ndeath ; j ++)
                   5942:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   5943:                                fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  5944:       } /* nlstate */
                   5945:       fprintf(ficgp,"\nset out\n");
                   5946:     } /* end cpt state*/ 
                   5947:   } /* end covariate */  
1.220     brouard  5948:        
                   5949: /* 5eme */
1.201     brouard  5950:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5951:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5952:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.220     brouard  5953: 
1.201     brouard  5954:       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);
1.211     brouard  5955:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  5956:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5957:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5958:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5959:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5960:                                vlv= nbcode[Tvaraff[k]][lv];
                   5961:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5962:       }
                   5963:       fprintf(ficgp,"\n#\n");
1.220     brouard  5964:                        if(invalidvarcomb[k1]){
                   5965:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5966:                                                continue;
                   5967:                        }
                   5968:                        
1.201     brouard  5969:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5970:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  5971: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   5972: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  5973: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5974:       k=3;
1.201     brouard  5975:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  5976:                                if(j==1)
                   5977:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5978:                                else
                   5979:                                        fprintf(ficgp,", '' ");
                   5980:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   5981:                                fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5982:                                /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5983:                                /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5984:                                fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  5985:       } /* nlstate */
                   5986:       fprintf(ficgp,", '' ");
                   5987:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5988:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  5989:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   5990:                                if(j < nlstate)
                   5991:                                        fprintf(ficgp,"$%d +",k+l);
                   5992:                                else
                   5993:                                        fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  5994:       }
                   5995:       fprintf(ficgp,"\nset out\n");
                   5996:     } /* end cpt state*/ 
                   5997:   } /* end covariate */  
1.220     brouard  5998:        
                   5999: /* 6eme */
1.202     brouard  6000:   /* CV preval stable (period) for each covariate */
1.211     brouard  6001:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6002:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6003: 
1.211     brouard  6004:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6005:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  6006:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6007:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6008:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6009:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6010:                                vlv= nbcode[Tvaraff[k]][lv];
                   6011:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6012:       }
                   6013:       fprintf(ficgp,"\n#\n");
1.220     brouard  6014:                        if(invalidvarcomb[k1]){
                   6015:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6016:                                                continue;
                   6017:                        }
1.211     brouard  6018: 
1.201     brouard  6019:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6020:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  6021: set ter svg size 640, 480\n\
1.126     brouard  6022: unset log y\n\
1.153     brouard  6023: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6024:       k=3; /* Offset */
1.153     brouard  6025:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  6026:                                if(i==1)
                   6027:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6028:                                else
                   6029:                                        fprintf(ficgp,", '' ");
                   6030:                                l=(nlstate+ndeath)*(i-1)+1;
                   6031:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6032:                                for (j=2; j<= nlstate ; j ++)
                   6033:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   6034:                                fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6035:       } /* nlstate */
1.201     brouard  6036:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6037:     } /* end cpt state*/ 
                   6038:   } /* end covariate */  
1.220     brouard  6039: 
                   6040: 
                   6041: /* 7eme */
1.218     brouard  6042:   if(backcast == 1){
1.217     brouard  6043:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6044:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6045:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6046:                                fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6047:                                for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6048:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6049:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6050:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6051:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6052:                                        vlv= nbcode[Tvaraff[k]][lv];
                   6053:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6054:                                }
                   6055:                                fprintf(ficgp,"\n#\n");
                   6056:                                if(invalidvarcomb[k1]){
                   6057:                                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6058:                                                                continue;
                   6059:                                }
                   6060:                                
                   6061:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6062:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6063: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6064: unset log y\n                                                                                                                                                                                                                                          \
1.218     brouard  6065: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.220     brouard  6066:                                k=3; /* Offset */
                   6067:                                for (i=1; i<= nlstate ; i ++){
                   6068:                                        if(i==1)
                   6069:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6070:                                        else
                   6071:                                                fprintf(ficgp,", '' ");
                   6072:                                        /* l=(nlstate+ndeath)*(i-1)+1; */
                   6073:                                        l=(nlstate+ndeath)*(cpt-1)+1;
                   6074:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6075:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6076:                                        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6077:                                        /* for (j=2; j<= nlstate ; j ++) */
                   6078:                                        /*      fprintf(ficgp,"+$%d",k+l+j-1); */
                   6079:                                        /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6080:                                        fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6081:                                } /* nlstate */
                   6082:                                fprintf(ficgp,"\nset out\n");
1.218     brouard  6083:       } /* end cpt state*/ 
                   6084:     } /* end covariate */  
                   6085:   } /* End if backcast */
                   6086:   
1.220     brouard  6087:        /* 8eme */
1.218     brouard  6088:   if(prevfcast==1){
                   6089:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6090:     
                   6091:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6092:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.219     brouard  6093:                                fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6094:                                for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6095:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6096:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6097:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6098:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6099:                                        vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  6100:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.219     brouard  6101:                                }
                   6102:                                fprintf(ficgp,"\n#\n");
1.220     brouard  6103:                                if(invalidvarcomb[k1]){
                   6104:                                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6105:                                                                continue;
                   6106:                                }
1.219     brouard  6107:                                
                   6108:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6109:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6110:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   6111: set ter svg size 640, 480\n    \
                   6112: unset log y\n  \
                   6113: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6114:                                for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6115:                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6116:                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6117:                                        /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6118:                                        /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6119:                                        if(i==1){
                   6120:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6121:                                        }else{
                   6122:                                                fprintf(ficgp,",\\\n '' ");
                   6123:                                        }
                   6124:                                        if(cptcoveff ==0){ /* No covariate */
                   6125:                                                ioffset=2; /* Age is in 2 */
                   6126:                                                /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6127:                                                /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6128:                                                /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6129:                                                /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6130:                                                fprintf(ficgp," u %d:(", ioffset); 
                   6131:                                                if(i==nlstate+1)
                   6132:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
                   6133:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6134:                                                else
                   6135:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
                   6136:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6137:                                        }else{ /* more than 2 covariates */
                   6138:                                                if(cptcoveff ==1){
                   6139:                                                        ioffset=4; /* Age is in 4 */
                   6140:                                                }else{
                   6141:                                                        ioffset=6; /* Age is in 6 */
                   6142:                                                /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6143:                                                /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6144:                                                }   
1.220     brouard  6145:                                                fprintf(ficgp," u %d:(",ioffset); 
1.219     brouard  6146:                                                kl=0;
1.220     brouard  6147:                                                strcpy(gplotcondition,"(");
                   6148:                                                for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.219     brouard  6149:                                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6150:                                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6151:                                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6152:                                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6153:                                                        vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6154:                                                        kl++;
                   6155:                                                        sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
1.219     brouard  6156:                                                        kl++;
1.220     brouard  6157:                                                        if(k <cptcoveff && cptcoveff>1)
                   6158:                                                                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6159:                                                }
                   6160:                                                strcpy(gplotcondition+strlen(gplotcondition),")");
                   6161:                                                /* 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 *\/ */
                   6162:                                                /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6163:                                                /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6164:                                                /* ''  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*/
                   6165:                                                if(i==nlstate+1){
                   6166:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6167:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6168:                                                }else{
                   6169:                                                                fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6170:                                                                                                ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6171:                                                }
1.219     brouard  6172:                                        } /* end if covariate */
                   6173:                                } /* nlstate */
                   6174:                                fprintf(ficgp,"\nset out\n");
                   6175:                        } /* end cpt state*/
                   6176:                } /* end covariate */
                   6177:        } /* End if prevfcast */
                   6178:        
1.211     brouard  6179:        
1.219     brouard  6180:        /* proba elementaires */
                   6181:        fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6182:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6183:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6184:     for(k=1; k <=(nlstate+ndeath); k++){
                   6185:       if (k != i) {
1.187     brouard  6186:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  6187:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  6188:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  6189:          jk++; 
                   6190:        }
1.187     brouard  6191:        fprintf(ficgp,"\n");
1.126     brouard  6192:       }
                   6193:     }
                   6194:    }
1.187     brouard  6195:   fprintf(ficgp,"##############\n#\n");
                   6196: 
1.145     brouard  6197:   /*goto avoid;*/
1.200     brouard  6198:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6199:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6200:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6201:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6202:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6203:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6204:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6205:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6206:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6207:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6208:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6209:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6210:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6211:   fprintf(ficgp,"#\n");
1.201     brouard  6212:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  6213:      fprintf(ficgp,"# ng=%d\n",ng);
                   6214:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  6215:      for(jk=1; jk <=m; jk++) {
1.187     brouard  6216:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  6217:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6218:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6219:        if (ng==1){
                   6220:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6221:         fprintf(ficgp,"\nunset log y");
                   6222:        }else if (ng==2){
                   6223:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6224:         fprintf(ficgp,"\nset log y");
                   6225:        }else if (ng==3){
1.126     brouard  6226:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  6227:         fprintf(ficgp,"\nset log y");
                   6228:        }else
                   6229:         fprintf(ficgp,"\nunset title ");
                   6230:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  6231:        i=1;
                   6232:        for(k2=1; k2<=nlstate; k2++) {
                   6233:         k3=i;
                   6234:         for(k=1; k<=(nlstate+ndeath); k++) {
                   6235:           if (k != k2){
1.201     brouard  6236:             switch( ng) {
                   6237:             case 1:
1.187     brouard  6238:               if(nagesqr==0)
1.201     brouard  6239:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  6240:               else /* nagesqr =1 */
1.201     brouard  6241:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6242:               break;
                   6243:             case 2: /* ng=2 */
1.187     brouard  6244:               if(nagesqr==0)
                   6245:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6246:               else /* nagesqr =1 */
1.201     brouard  6247:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6248:               break;
                   6249:             case 3:
                   6250:               if(nagesqr==0)
                   6251:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6252:               else /* nagesqr =1 */
                   6253:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6254:               break;
                   6255:             }
1.141     brouard  6256:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  6257:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  6258:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6259:               if(ij <=cptcovage) { /* Bug valgrind */
                   6260:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  6261:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6262:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  6263:                   ij++;
                   6264:                 }
1.186     brouard  6265:               }
                   6266:               else
1.198     brouard  6267:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6268:             }
1.217     brouard  6269:           }else{
                   6270:             i=i-ncovmodel;
                   6271:             if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6272:               fprintf(ficgp," (1.");
                   6273:           }
                   6274:           
                   6275:           if(ng != 1){
                   6276:             fprintf(ficgp,")/(1");
1.126     brouard  6277:             
1.217     brouard  6278:             for(k1=1; k1 <=nlstate; k1++){ 
                   6279:               if(nagesqr==0)
                   6280:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6281:               else /* nagesqr =1 */
                   6282:                 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);
                   6283:               
                   6284:               ij=1;
                   6285:               for(j=3; j <=ncovmodel-nagesqr; j++){
                   6286:                 if(ij <=cptcovage) { /* Bug valgrind */
                   6287:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6288:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6289:                     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6290:                     ij++;
1.197     brouard  6291:                   }
1.186     brouard  6292:                 }
1.217     brouard  6293:                 else
                   6294:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6295:               }
                   6296:               fprintf(ficgp,")");
1.217     brouard  6297:             }
                   6298:             fprintf(ficgp,")");
                   6299:             if(ng ==2)
                   6300:               fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6301:             else /* ng= 3 */
                   6302:               fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6303:           }else{ /* end ng <> 1 */
                   6304:             if( k !=k2) /* logit p11 is hard to draw */
1.201     brouard  6305:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  6306:           }
1.217     brouard  6307:           if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6308:             fprintf(ficgp,",");
                   6309:           if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6310:             fprintf(ficgp,",");
                   6311:           i=i+ncovmodel;
1.126     brouard  6312:         } /* end k */
                   6313:        } /* end k2 */
1.201     brouard  6314:        fprintf(ficgp,"\n set out\n");
1.126     brouard  6315:      } /* end jk */
                   6316:    } /* end ng */
1.164     brouard  6317:  /* avoid: */
1.126     brouard  6318:    fflush(ficgp); 
                   6319: }  /* end gnuplot */
                   6320: 
                   6321: 
                   6322: /*************** Moving average **************/
1.219     brouard  6323: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.218     brouard  6324: int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
                   6325:    
1.126     brouard  6326:   int i, cpt, cptcod;
                   6327:   int modcovmax =1;
                   6328:   int mobilavrange, mob;
1.219     brouard  6329:   int iage=0;
                   6330: 
                   6331:   double sum=0.;
1.126     brouard  6332:   double age;
1.218     brouard  6333:   double *sumnewp, *sumnewm;
                   6334:   double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6335:   
1.219     brouard  6336:   
1.220     brouard  6337:   /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
                   6338:        /*                 a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
1.219     brouard  6339: 
1.220     brouard  6340:   sumnewp = vector(1,ncovcombmax);
                   6341:   sumnewm = vector(1,ncovcombmax);
                   6342:   agemingood = vector(1,ncovcombmax);  
                   6343:   agemaxgood = vector(1,ncovcombmax);
1.219     brouard  6344: 
1.220     brouard  6345:   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.219     brouard  6346:                sumnewm[cptcod]=0.;
                   6347:                sumnewp[cptcod]=0.;
                   6348:                agemingood[cptcod]=0;
                   6349:                agemaxgood[cptcod]=0;
                   6350:        }
1.220     brouard  6351:   if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
1.218     brouard  6352:   
1.126     brouard  6353:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6354:     if(mobilav==1) mobilavrange=5; /* default */
                   6355:     else mobilavrange=mobilav;
                   6356:     for (age=bage; age<=fage; age++)
                   6357:       for (i=1; i<=nlstate;i++)
1.220     brouard  6358:                                for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
1.219     brouard  6359:                                        mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
1.126     brouard  6360:     /* We keep the original values on the extreme ages bage, fage and for 
                   6361:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6362:        we use a 5 terms etc. until the borders are no more concerned. 
                   6363:     */ 
                   6364:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6365:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.219     brouard  6366:                                for (i=1; i<=nlstate;i++){
1.220     brouard  6367:                                        for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.219     brouard  6368:                                                mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6369:                                                for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6370:                                                        mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6371:                                                        mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6372:                                                }
                   6373:                                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6374:                                        }
                   6375:                                }
1.126     brouard  6376:       }/* end age */
                   6377:     }/* end mob */
1.218     brouard  6378:   }else
                   6379:     return -1;
1.220     brouard  6380:   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.218     brouard  6381:     /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
1.219     brouard  6382:     agemingood[cptcod]=fage-(mob-1)/2;
1.218     brouard  6383:     for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6384:       sumnewm[cptcod]=0.;
                   6385:       for (i=1; i<=nlstate;i++){
                   6386:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6387:       }
                   6388:       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.219     brouard  6389:                                agemingood[cptcod]=age;
1.218     brouard  6390:       }else{ /* bad */
1.219     brouard  6391:                                for (i=1; i<=nlstate;i++){
                   6392:                                        mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6393:                                } /* i */
1.218     brouard  6394:       } /* end bad */
                   6395:     }/* age */
1.219     brouard  6396:     sum=0.;
                   6397:     for (i=1; i<=nlstate;i++){
                   6398:       sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
1.218     brouard  6399:     }
1.219     brouard  6400:     if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6401:       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);
                   6402:       /* for (i=1; i<=nlstate;i++){ */
                   6403:       /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6404:       /* } /\* i *\/ */
                   6405:     } /* end bad */
                   6406:     /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6407:                /* From youngest, finding the oldest wrong */
                   6408:                agemaxgood[cptcod]=bage+(mob-1)/2;
                   6409:                for (age=bage+(mob-1)/2; age<=fage; age++){
                   6410:                        sumnewm[cptcod]=0.;
                   6411:                        for (i=1; i<=nlstate;i++){
                   6412:                                sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6413:                        }
                   6414:                        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6415:                                agemaxgood[cptcod]=age;
                   6416:                        }else{ /* bad */
                   6417:                                for (i=1; i<=nlstate;i++){
                   6418:                                        mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6419:                                } /* i */
                   6420:                        } /* end bad */
                   6421:                }/* age */
                   6422:                sum=0.;
                   6423:                for (i=1; i<=nlstate;i++){
                   6424:                        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6425:                }
                   6426:                if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6427:                        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);
                   6428:                        /* for (i=1; i<=nlstate;i++){ */
                   6429:                        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6430:                        /* } /\* i *\/ */
                   6431:                } /* end bad */
                   6432:                
                   6433:                for (age=bage; age<=fage; age++){
                   6434:                        printf("%d %d ", cptcod, (int)age);
                   6435:                        sumnewp[cptcod]=0.;
                   6436:                        sumnewm[cptcod]=0.;
                   6437:                        for (i=1; i<=nlstate;i++){
                   6438:                                sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6439:                                sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6440:                                /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6441:                        }
                   6442:                        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6443:                }
                   6444:                /* printf("\n"); */
                   6445:     /* } */
1.218     brouard  6446:     /* brutal averaging */
                   6447:     for (i=1; i<=nlstate;i++){
                   6448:       for (age=1; age<=bage; age++){
1.219     brouard  6449:                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6450:                                /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
1.218     brouard  6451:       }        
                   6452:       for (age=fage; age<=AGESUP; age++){
1.219     brouard  6453:                                mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6454:                                /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
1.218     brouard  6455:       }
                   6456:     } /* end i status */
                   6457:     for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6458:       for (age=1; age<=AGESUP; age++){
1.219     brouard  6459:                                /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6460:                                mobaverage[(int)age][i][cptcod]=0.;
1.218     brouard  6461:       }
                   6462:     }
                   6463:   }/* end cptcod */
1.220     brouard  6464:   free_vector(sumnewm,1, ncovcombmax);
                   6465:   free_vector(sumnewp,1, ncovcombmax);
                   6466:   free_vector(agemaxgood,1, ncovcombmax);
                   6467:   free_vector(agemingood,1, ncovcombmax);
1.126     brouard  6468:   return 0;
                   6469: }/* End movingaverage */
1.218     brouard  6470:  
1.126     brouard  6471: 
                   6472: /************** Forecasting ******************/
1.169     brouard  6473: 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  6474:   /* proj1, year, month, day of starting projection 
                   6475:      agemin, agemax range of age
                   6476:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6477:      anproj2 year of en of projection (same day and month as proj1).
                   6478:   */
1.164     brouard  6479:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6480:   double agec; /* generic age */
                   6481:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6482:   double *popeffectif,*popcount;
                   6483:   double ***p3mat;
1.218     brouard  6484:   /* double ***mobaverage; */
1.126     brouard  6485:   char fileresf[FILENAMELENGTH];
                   6486: 
                   6487:   agelim=AGESUP;
1.211     brouard  6488:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6489:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6490:      We still use firstpass and lastpass as another selection.
                   6491:   */
1.214     brouard  6492:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6493:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6494:  
1.201     brouard  6495:   strcpy(fileresf,"F_"); 
                   6496:   strcat(fileresf,fileresu);
1.126     brouard  6497:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6498:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6499:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6500:   }
1.215     brouard  6501:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6502:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6503: 
                   6504:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6505: 
                   6506: 
                   6507:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6508:   if (stepm<=12) stepsize=1;
                   6509:   if(estepm < stepm){
                   6510:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6511:   }
                   6512:   else  hstepm=estepm;   
                   6513: 
                   6514:   hstepm=hstepm/stepm; 
                   6515:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6516:                                fractional in yp1 */
                   6517:   anprojmean=yp;
                   6518:   yp2=modf((yp1*12),&yp);
                   6519:   mprojmean=yp;
                   6520:   yp1=modf((yp2*30.5),&yp);
                   6521:   jprojmean=yp;
                   6522:   if(jprojmean==0) jprojmean=1;
                   6523:   if(mprojmean==0) jprojmean=1;
                   6524: 
                   6525:   i1=cptcoveff;
                   6526:   if (cptcovn < 1){i1=1;}
                   6527:   
                   6528:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6529:   
                   6530:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6531: 
                   6532: /*           if (h==(int)(YEARM*yearp)){ */
                   6533:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6534:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6535:       k=k+1;
1.211     brouard  6536:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  6537:       for(j=1;j<=cptcoveff;j++) {
1.219     brouard  6538:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6539:       }
1.211     brouard  6540:       fprintf(ficresf," yearproj age");
1.126     brouard  6541:       for(j=1; j<=nlstate+ndeath;j++){ 
1.219     brouard  6542:                                for(i=1; i<=nlstate;i++)              
1.126     brouard  6543:           fprintf(ficresf," p%d%d",i,j);
1.219     brouard  6544:                                fprintf(ficresf," wp.%d",j);
1.126     brouard  6545:       }
1.217     brouard  6546:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.219     brouard  6547:                                fprintf(ficresf,"\n");
                   6548:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6549:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6550:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6551:                                        nhstepm = nhstepm/hstepm; 
                   6552:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6553:                                        oldm=oldms;savm=savms;
                   6554:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6555:                                        
                   6556:                                        for (h=0; h<=nhstepm; h++){
                   6557:                                                if (h*hstepm/YEARM*stepm ==yearp) {
1.126     brouard  6558:               fprintf(ficresf,"\n");
                   6559:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6560:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  6561:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6562:                                                } 
                   6563:                                                for(j=1; j<=nlstate+ndeath;j++) {
                   6564:                                                        ppij=0.;
                   6565:                                                        for(i=1; i<=nlstate;i++) {
                   6566:                                                                if (mobilav==1) 
                   6567:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6568:                                                                else {
                   6569:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6570:                                                                }
                   6571:                                                                if (h*hstepm/YEARM*stepm== yearp) {
                   6572:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6573:                                                                }
                   6574:                                                        } /* end i */
                   6575:                                                        if (h*hstepm/YEARM*stepm==yearp) {
                   6576:                                                                fprintf(ficresf," %.3f", ppij);
                   6577:                                                        }
                   6578:                                                }/* end j */
                   6579:                                        } /* end h */
                   6580:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6581:                                } /* end agec */
1.126     brouard  6582:       } /* end yearp */
                   6583:     } /* end cptcod */
                   6584:   } /* end  cptcov */
1.219     brouard  6585:        
1.126     brouard  6586:   fclose(ficresf);
1.215     brouard  6587:   printf("End of Computing forecasting \n");
                   6588:   fprintf(ficlog,"End of Computing forecasting\n");
                   6589: 
1.126     brouard  6590: }
                   6591: 
1.218     brouard  6592: /* /\************** Back Forecasting ******************\/ */
                   6593: /* 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){ */
                   6594: /*   /\* back1, year, month, day of starting backection  */
                   6595: /*      agemin, agemax range of age */
                   6596: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6597: /*      anback2 year of en of backection (same day and month as back1). */
                   6598: /*   *\/ */
                   6599: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6600: /*   double agec; /\* generic age *\/ */
                   6601: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6602: /*   double *popeffectif,*popcount; */
                   6603: /*   double ***p3mat; */
                   6604: /*   /\* double ***mobaverage; *\/ */
                   6605: /*   char fileresfb[FILENAMELENGTH]; */
                   6606:        
                   6607: /*   agelim=AGESUP; */
                   6608: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6609: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6610: /*      We still use firstpass and lastpass as another selection. */
                   6611: /*   *\/ */
                   6612: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6613: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6614: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6615:        
                   6616: /*   strcpy(fileresfb,"FB_");  */
                   6617: /*   strcat(fileresfb,fileresu); */
                   6618: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6619: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6620: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6621: /*   } */
                   6622: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6623: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6624:        
                   6625: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   6626:        
                   6627: /*   /\* if (mobilav!=0) { *\/ */
                   6628: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6629: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6630: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6631: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6632: /*   /\*   } *\/ */
                   6633: /*   /\* } *\/ */
                   6634:        
                   6635: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6636: /*   if (stepm<=12) stepsize=1; */
                   6637: /*   if(estepm < stepm){ */
                   6638: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6639: /*   } */
                   6640: /*   else  hstepm=estepm;    */
                   6641:        
                   6642: /*   hstepm=hstepm/stepm;  */
                   6643: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6644: /*                                fractional in yp1 *\/ */
                   6645: /*   anprojmean=yp; */
                   6646: /*   yp2=modf((yp1*12),&yp); */
                   6647: /*   mprojmean=yp; */
                   6648: /*   yp1=modf((yp2*30.5),&yp); */
                   6649: /*   jprojmean=yp; */
                   6650: /*   if(jprojmean==0) jprojmean=1; */
                   6651: /*   if(mprojmean==0) jprojmean=1; */
                   6652:        
                   6653: /*   i1=cptcoveff; */
                   6654: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  6655:   
1.218     brouard  6656: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  6657:   
1.218     brouard  6658: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6659:        
                   6660: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6661: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
                   6662: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   6663: /*       k=k+1; */
                   6664: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
                   6665: /*       for(j=1;j<=cptcoveff;j++) { */
                   6666: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6667: /*       } */
                   6668: /*       fprintf(ficresfb," yearbproj age"); */
                   6669: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6670: /*                             for(i=1; i<=nlstate;i++)               */
                   6671: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6672: /*                             fprintf(ficresfb," p.%d",j); */
                   6673: /*       } */
                   6674: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6675: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6676: /*                             fprintf(ficresfb,"\n"); */
                   6677: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6678: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6679: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6680: /*                                     nhstepm = nhstepm/hstepm;  */
                   6681: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6682: /*                                     oldm=oldms;savm=savms; */
                   6683: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6684: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6685: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6686: /*               fprintf(ficresfb,"\n"); */
                   6687: /*               for(j=1;j<=cptcoveff;j++)  */
                   6688: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6689: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6690: /*                                             }  */
                   6691: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6692: /*                                                     ppij=0.; */
                   6693: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6694: /*                                                             if (mobilav==1)  */
                   6695: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6696: /*                                                             else { */
                   6697: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6698: /*                                                             } */
                   6699: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6700: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6701: /*                                                             } */
                   6702: /*                                                     } /\* end i *\/ */
                   6703: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6704: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6705: /*                                                     } */
                   6706: /*                                             }/\* end j *\/ */
                   6707: /*                                     } /\* end h *\/ */
                   6708: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6709: /*                             } /\* end agec *\/ */
                   6710: /*       } /\* end yearp *\/ */
                   6711: /*     } /\* end cptcod *\/ */
                   6712: /*   } /\* end  cptcov *\/ */
                   6713:        
                   6714: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6715:        
                   6716: /*   fclose(ficresfb); */
                   6717: /*   printf("End of Computing Back forecasting \n"); */
                   6718: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  6719:        
1.218     brouard  6720: /* } */
1.217     brouard  6721: 
1.126     brouard  6722: /************** Forecasting *****not tested NB*************/
1.169     brouard  6723: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
1.126     brouard  6724:   
                   6725:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6726:   int *popage;
                   6727:   double calagedatem, agelim, kk1, kk2;
                   6728:   double *popeffectif,*popcount;
                   6729:   double ***p3mat,***tabpop,***tabpopprev;
1.218     brouard  6730:   /* double ***mobaverage; */
1.126     brouard  6731:   char filerespop[FILENAMELENGTH];
                   6732: 
                   6733:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6734:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6735:   agelim=AGESUP;
                   6736:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6737:   
                   6738:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6739:   
                   6740:   
1.201     brouard  6741:   strcpy(filerespop,"POP_"); 
                   6742:   strcat(filerespop,fileresu);
1.126     brouard  6743:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6744:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6745:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6746:   }
                   6747:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6748:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6749: 
                   6750:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6751: 
1.218     brouard  6752:   /* if (mobilav!=0) { */
                   6753:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6754:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6755:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6756:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6757:   /*   } */
                   6758:   /* } */
1.126     brouard  6759: 
                   6760:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6761:   if (stepm<=12) stepsize=1;
                   6762:   
                   6763:   agelim=AGESUP;
                   6764:   
                   6765:   hstepm=1;
                   6766:   hstepm=hstepm/stepm; 
1.218     brouard  6767:        
1.126     brouard  6768:   if (popforecast==1) {
                   6769:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6770:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6771:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6772:     } 
                   6773:     popage=ivector(0,AGESUP);
                   6774:     popeffectif=vector(0,AGESUP);
                   6775:     popcount=vector(0,AGESUP);
                   6776:     
                   6777:     i=1;   
                   6778:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
1.218     brouard  6779:     
1.126     brouard  6780:     imx=i;
                   6781:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6782:   }
1.218     brouard  6783:   
1.126     brouard  6784:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
1.218     brouard  6785:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
1.126     brouard  6786:       k=k+1;
                   6787:       fprintf(ficrespop,"\n#******");
                   6788:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6789:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6790:       }
                   6791:       fprintf(ficrespop,"******\n");
                   6792:       fprintf(ficrespop,"# Age");
                   6793:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6794:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6795:       
                   6796:       for (cpt=0; cpt<=0;cpt++) { 
                   6797:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6798:        
1.218     brouard  6799:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
1.126     brouard  6800:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6801:          nhstepm = nhstepm/hstepm; 
                   6802:          
                   6803:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6804:          oldm=oldms;savm=savms;
                   6805:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
1.218     brouard  6806:          
1.126     brouard  6807:          for (h=0; h<=nhstepm; h++){
                   6808:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6809:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6810:            } 
                   6811:            for(j=1; j<=nlstate+ndeath;j++) {
                   6812:              kk1=0.;kk2=0;
                   6813:              for(i=1; i<=nlstate;i++) {              
                   6814:                if (mobilav==1) 
                   6815:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6816:                else {
                   6817:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6818:                }
                   6819:              }
                   6820:              if (h==(int)(calagedatem+12*cpt)){
                   6821:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
1.218     brouard  6822:                /*fprintf(ficrespop," %.3f", kk1);
                   6823:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
1.126     brouard  6824:              }
                   6825:            }
                   6826:            for(i=1; i<=nlstate;i++){
                   6827:              kk1=0.;
1.218     brouard  6828:              for(j=1; j<=nlstate;j++){
                   6829:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6830:              }
                   6831:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
1.126     brouard  6832:            }
1.218     brouard  6833:            
                   6834:            if (h==(int)(calagedatem+12*cpt))
                   6835:              for(j=1; j<=nlstate;j++) 
                   6836:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
1.126     brouard  6837:          }
                   6838:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6839:        }
                   6840:       }
1.218     brouard  6841:       
                   6842:       /******/
                   6843:       
1.126     brouard  6844:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6845:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6846:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6847:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6848:          nhstepm = nhstepm/hstepm; 
                   6849:          
                   6850:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6851:          oldm=oldms;savm=savms;
                   6852:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6853:          for (h=0; h<=nhstepm; h++){
                   6854:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6855:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6856:            } 
                   6857:            for(j=1; j<=nlstate+ndeath;j++) {
                   6858:              kk1=0.;kk2=0;
                   6859:              for(i=1; i<=nlstate;i++) {              
                   6860:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6861:              }
                   6862:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6863:            }
                   6864:          }
                   6865:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6866:        }
                   6867:       }
1.218     brouard  6868:     } 
1.126     brouard  6869:   }
1.218     brouard  6870:   
                   6871:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6872:   
1.126     brouard  6873:   if (popforecast==1) {
                   6874:     free_ivector(popage,0,AGESUP);
                   6875:     free_vector(popeffectif,0,AGESUP);
                   6876:     free_vector(popcount,0,AGESUP);
                   6877:   }
                   6878:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6879:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6880:   fclose(ficrespop);
                   6881: } /* End of popforecast */
1.218     brouard  6882:  
1.126     brouard  6883: int fileappend(FILE *fichier, char *optionfich)
                   6884: {
                   6885:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   6886:     printf("Problem with file: %s\n", optionfich);
                   6887:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   6888:     return (0);
                   6889:   }
                   6890:   fflush(fichier);
                   6891:   return (1);
                   6892: }
                   6893: 
                   6894: 
                   6895: /**************** function prwizard **********************/
                   6896: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6897: {
                   6898: 
                   6899:   /* Wizard to print covariance matrix template */
                   6900: 
1.164     brouard  6901:   char ca[32], cb[32];
                   6902:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6903:   int numlinepar;
                   6904: 
                   6905:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6906:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6907:   for(i=1; i <=nlstate; i++){
                   6908:     jj=0;
                   6909:     for(j=1; j <=nlstate+ndeath; j++){
                   6910:       if(j==i) continue;
                   6911:       jj++;
                   6912:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6913:       printf("%1d%1d",i,j);
                   6914:       fprintf(ficparo,"%1d%1d",i,j);
                   6915:       for(k=1; k<=ncovmodel;k++){
                   6916:        /*        printf(" %lf",param[i][j][k]); */
                   6917:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6918:        printf(" 0.");
                   6919:        fprintf(ficparo," 0.");
                   6920:       }
                   6921:       printf("\n");
                   6922:       fprintf(ficparo,"\n");
                   6923:     }
                   6924:   }
                   6925:   printf("# Scales (for hessian or gradient estimation)\n");
                   6926:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6927:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6928:   for(i=1; i <=nlstate; i++){
                   6929:     jj=0;
                   6930:     for(j=1; j <=nlstate+ndeath; j++){
                   6931:       if(j==i) continue;
                   6932:       jj++;
                   6933:       fprintf(ficparo,"%1d%1d",i,j);
                   6934:       printf("%1d%1d",i,j);
                   6935:       fflush(stdout);
                   6936:       for(k=1; k<=ncovmodel;k++){
                   6937:        /*      printf(" %le",delti3[i][j][k]); */
                   6938:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6939:        printf(" 0.");
                   6940:        fprintf(ficparo," 0.");
                   6941:       }
                   6942:       numlinepar++;
                   6943:       printf("\n");
                   6944:       fprintf(ficparo,"\n");
                   6945:     }
                   6946:   }
                   6947:   printf("# Covariance matrix\n");
                   6948: /* # 121 Var(a12)\n\ */
                   6949: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6950: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6951: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6952: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6953: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6954: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6955: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6956:   fflush(stdout);
                   6957:   fprintf(ficparo,"# Covariance matrix\n");
                   6958:   /* # 121 Var(a12)\n\ */
                   6959:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6960:   /* #   ...\n\ */
                   6961:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6962:   
                   6963:   for(itimes=1;itimes<=2;itimes++){
                   6964:     jj=0;
                   6965:     for(i=1; i <=nlstate; i++){
                   6966:       for(j=1; j <=nlstate+ndeath; j++){
                   6967:        if(j==i) continue;
                   6968:        for(k=1; k<=ncovmodel;k++){
                   6969:          jj++;
                   6970:          ca[0]= k+'a'-1;ca[1]='\0';
                   6971:          if(itimes==1){
                   6972:            printf("#%1d%1d%d",i,j,k);
                   6973:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6974:          }else{
                   6975:            printf("%1d%1d%d",i,j,k);
                   6976:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6977:            /*  printf(" %.5le",matcov[i][j]); */
                   6978:          }
                   6979:          ll=0;
                   6980:          for(li=1;li <=nlstate; li++){
                   6981:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6982:              if(lj==li) continue;
                   6983:              for(lk=1;lk<=ncovmodel;lk++){
                   6984:                ll++;
                   6985:                if(ll<=jj){
                   6986:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6987:                  if(ll<jj){
                   6988:                    if(itimes==1){
                   6989:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6990:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6991:                    }else{
                   6992:                      printf(" 0.");
                   6993:                      fprintf(ficparo," 0.");
                   6994:                    }
                   6995:                  }else{
                   6996:                    if(itimes==1){
                   6997:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6998:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6999:                    }else{
                   7000:                      printf(" 0.");
                   7001:                      fprintf(ficparo," 0.");
                   7002:                    }
                   7003:                  }
                   7004:                }
                   7005:              } /* end lk */
                   7006:            } /* end lj */
                   7007:          } /* end li */
                   7008:          printf("\n");
                   7009:          fprintf(ficparo,"\n");
                   7010:          numlinepar++;
                   7011:        } /* end k*/
                   7012:       } /*end j */
                   7013:     } /* end i */
                   7014:   } /* end itimes */
                   7015: 
                   7016: } /* end of prwizard */
                   7017: /******************* Gompertz Likelihood ******************************/
                   7018: double gompertz(double x[])
                   7019: { 
                   7020:   double A,B,L=0.0,sump=0.,num=0.;
                   7021:   int i,n=0; /* n is the size of the sample */
                   7022: 
1.220     brouard  7023:   for (i=1;i<=imx ; i++) {
1.126     brouard  7024:     sump=sump+weight[i];
                   7025:     /*    sump=sump+1;*/
                   7026:     num=num+1;
                   7027:   }
                   7028:  
                   7029:  
                   7030:   /* for (i=0; i<=imx; i++) 
                   7031:      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]);*/
                   7032: 
                   7033:   for (i=1;i<=imx ; i++)
                   7034:     {
                   7035:       if (cens[i] == 1 && wav[i]>1)
                   7036:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7037:       
                   7038:       if (cens[i] == 0 && wav[i]>1)
                   7039:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7040:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7041:       
                   7042:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7043:       if (wav[i] > 1 ) { /* ??? */
                   7044:        L=L+A*weight[i];
                   7045:        /*      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]);*/
                   7046:       }
                   7047:     }
                   7048: 
                   7049:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7050:  
                   7051:   return -2*L*num/sump;
                   7052: }
                   7053: 
1.136     brouard  7054: #ifdef GSL
                   7055: /******************* Gompertz_f Likelihood ******************************/
                   7056: double gompertz_f(const gsl_vector *v, void *params)
                   7057: { 
                   7058:   double A,B,LL=0.0,sump=0.,num=0.;
                   7059:   double *x= (double *) v->data;
                   7060:   int i,n=0; /* n is the size of the sample */
                   7061: 
                   7062:   for (i=0;i<=imx-1 ; i++) {
                   7063:     sump=sump+weight[i];
                   7064:     /*    sump=sump+1;*/
                   7065:     num=num+1;
                   7066:   }
                   7067:  
                   7068:  
                   7069:   /* for (i=0; i<=imx; i++) 
                   7070:      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]);*/
                   7071:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7072:   for (i=1;i<=imx ; i++)
                   7073:     {
                   7074:       if (cens[i] == 1 && wav[i]>1)
                   7075:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7076:       
                   7077:       if (cens[i] == 0 && wav[i]>1)
                   7078:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7079:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7080:       
                   7081:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7082:       if (wav[i] > 1 ) { /* ??? */
                   7083:        LL=LL+A*weight[i];
                   7084:        /*      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]);*/
                   7085:       }
                   7086:     }
                   7087: 
                   7088:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7089:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7090:  
                   7091:   return -2*LL*num/sump;
                   7092: }
                   7093: #endif
                   7094: 
1.126     brouard  7095: /******************* Printing html file ***********/
1.201     brouard  7096: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7097:                  int lastpass, int stepm, int weightopt, char model[],\
                   7098:                  int imx,  double p[],double **matcov,double agemortsup){
                   7099:   int i,k;
                   7100: 
                   7101:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7102:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7103:   for (i=1;i<=2;i++) 
                   7104:     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  7105:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7106:   fprintf(fichtm,"</ul>");
                   7107: 
                   7108: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7109: 
                   7110:  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>");
                   7111: 
                   7112:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7113:    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]);
                   7114: 
                   7115:  
                   7116:   fflush(fichtm);
                   7117: }
                   7118: 
                   7119: /******************* Gnuplot file **************/
1.201     brouard  7120: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7121: 
                   7122:   char dirfileres[132],optfileres[132];
1.164     brouard  7123: 
1.126     brouard  7124:   int ng;
                   7125: 
                   7126: 
                   7127:   /*#ifdef windows */
                   7128:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7129:     /*#endif */
                   7130: 
                   7131: 
                   7132:   strcpy(dirfileres,optionfilefiname);
                   7133:   strcpy(optfileres,"vpl");
1.199     brouard  7134:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7135:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7136:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7137:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7138:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7139: 
                   7140: } 
                   7141: 
1.136     brouard  7142: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7143: {
1.126     brouard  7144: 
1.136     brouard  7145:   /*-------- data file ----------*/
                   7146:   FILE *fic;
                   7147:   char dummy[]="                         ";
1.164     brouard  7148:   int i=0, j=0, n=0;
1.136     brouard  7149:   int linei, month, year,iout;
                   7150:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7151:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7152:   char *stratrunc;
                   7153:   int lstra;
1.126     brouard  7154: 
                   7155: 
1.136     brouard  7156:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7157:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7158:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7159:   }
1.126     brouard  7160: 
1.136     brouard  7161:   i=1;
                   7162:   linei=0;
                   7163:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7164:     linei=linei+1;
                   7165:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7166:       if(line[j] == '\t')
                   7167:        line[j] = ' ';
                   7168:     }
                   7169:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7170:       ;
                   7171:     };
                   7172:     line[j+1]=0;  /* Trims blanks at end of line */
                   7173:     if(line[0]=='#'){
                   7174:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7175:       printf("Comment line\n%s\n",line);
                   7176:       continue;
                   7177:     }
                   7178:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7179:     strcpy(line, linetmp);
1.136     brouard  7180:   
1.126     brouard  7181: 
1.136     brouard  7182:     for (j=maxwav;j>=1;j--){
1.137     brouard  7183:       cutv(stra, strb, line, ' '); 
1.136     brouard  7184:       if(strb[0]=='.') { /* Missing status */
                   7185:        lval=-1;
                   7186:       }else{
                   7187:        errno=0;
                   7188:        lval=strtol(strb,&endptr,10); 
                   7189:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7190:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7191:          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);
                   7192:          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);
1.136     brouard  7193:          return 1;
                   7194:        }
                   7195:       }
                   7196:       s[j][i]=lval;
                   7197:       
                   7198:       strcpy(line,stra);
                   7199:       cutv(stra, strb,line,' ');
1.169     brouard  7200:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7201:       }
1.169     brouard  7202:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7203:        month=99;
                   7204:        year=9999;
                   7205:       }else{
1.141     brouard  7206:        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);
                   7207:        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);
1.136     brouard  7208:        return 1;
                   7209:       }
                   7210:       anint[j][i]= (double) year; 
                   7211:       mint[j][i]= (double)month; 
                   7212:       strcpy(line,stra);
                   7213:     } /* ENd Waves */
                   7214:     
                   7215:     cutv(stra, strb,line,' '); 
1.169     brouard  7216:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7217:     }
1.169     brouard  7218:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7219:       month=99;
                   7220:       year=9999;
                   7221:     }else{
1.141     brouard  7222:       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);
                   7223:        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);
1.136     brouard  7224:        return 1;
                   7225:     }
                   7226:     andc[i]=(double) year; 
                   7227:     moisdc[i]=(double) month; 
                   7228:     strcpy(line,stra);
                   7229:     
                   7230:     cutv(stra, strb,line,' '); 
1.169     brouard  7231:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7232:     }
1.169     brouard  7233:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7234:       month=99;
                   7235:       year=9999;
                   7236:     }else{
1.141     brouard  7237:       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);
                   7238:       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.136     brouard  7239:        return 1;
                   7240:     }
                   7241:     if (year==9999) {
1.141     brouard  7242:       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);
                   7243:       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.136     brouard  7244:        return 1;
1.126     brouard  7245: 
1.136     brouard  7246:     }
                   7247:     annais[i]=(double)(year);
                   7248:     moisnais[i]=(double)(month); 
                   7249:     strcpy(line,stra);
                   7250:     
                   7251:     cutv(stra, strb,line,' '); 
                   7252:     errno=0;
                   7253:     dval=strtod(strb,&endptr); 
                   7254:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7255:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7256:       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  7257:       fflush(ficlog);
                   7258:       return 1;
                   7259:     }
                   7260:     weight[i]=dval; 
                   7261:     strcpy(line,stra);
                   7262:     
                   7263:     for (j=ncovcol;j>=1;j--){
                   7264:       cutv(stra, strb,line,' '); 
                   7265:       if(strb[0]=='.') { /* Missing status */
                   7266:        lval=-1;
                   7267:       }else{
                   7268:        errno=0;
                   7269:        lval=strtol(strb,&endptr,10); 
                   7270:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7271:          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);
                   7272:          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);
1.136     brouard  7273:          return 1;
                   7274:        }
                   7275:       }
                   7276:       if(lval <-1 || lval >1){
1.141     brouard  7277:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7278:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7279:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7280:  For example, for multinomial values like 1, 2 and 3,\n \
                   7281:  build V1=0 V2=0 for the reference value (1),\n \
                   7282:         V1=1 V2=0 for (2) \n \
                   7283:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7284:  output of IMaCh is often meaningless.\n \
                   7285:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  7286:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7287:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7288:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7289:  For example, for multinomial values like 1, 2 and 3,\n \
                   7290:  build V1=0 V2=0 for the reference value (1),\n \
                   7291:         V1=1 V2=0 for (2) \n \
                   7292:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7293:  output of IMaCh is often meaningless.\n \
                   7294:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   7295:        return 1;
                   7296:       }
                   7297:       covar[j][i]=(double)(lval);
                   7298:       strcpy(line,stra);
                   7299:     }  
                   7300:     lstra=strlen(stra);
                   7301:      
                   7302:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7303:       stratrunc = &(stra[lstra-9]);
                   7304:       num[i]=atol(stratrunc);
                   7305:     }
                   7306:     else
                   7307:       num[i]=atol(stra);
                   7308:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7309:       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;}*/
                   7310:     
                   7311:     i=i+1;
                   7312:   } /* End loop reading  data */
1.126     brouard  7313: 
1.136     brouard  7314:   *imax=i-1; /* Number of individuals */
                   7315:   fclose(fic);
                   7316:  
                   7317:   return (0);
1.164     brouard  7318:   /* endread: */
1.136     brouard  7319:     printf("Exiting readdata: ");
                   7320:     fclose(fic);
                   7321:     return (1);
1.126     brouard  7322: 
                   7323: 
                   7324: 
1.136     brouard  7325: }
1.145     brouard  7326: void removespace(char *str) {
                   7327:   char *p1 = str, *p2 = str;
                   7328:   do
                   7329:     while (*p2 == ' ')
                   7330:       p2++;
1.169     brouard  7331:   while (*p1++ == *p2++);
1.145     brouard  7332: }
                   7333: 
                   7334: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  7335:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   7336:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   7337:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   7338:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  7339:    * - cptcovage number of covariates with age*products =2
                   7340:    * - cptcovs number of simple covariates
                   7341:    * - 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
                   7342:    *     which is a new column after the 9 (ncovcol) variables. 
                   7343:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   7344:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   7345:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   7346:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   7347:  */
1.136     brouard  7348: {
1.145     brouard  7349:   int i, j, k, ks;
1.164     brouard  7350:   int  j1, k1, k2;
1.136     brouard  7351:   char modelsav[80];
1.145     brouard  7352:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7353:   char *strpt;
1.136     brouard  7354: 
1.145     brouard  7355:   /*removespace(model);*/
1.136     brouard  7356:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7357:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7358:     if (strstr(model,"AGE") !=0){
1.192     brouard  7359:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7360:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7361:       return 1;
                   7362:     }
1.141     brouard  7363:     if (strstr(model,"v") !=0){
                   7364:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7365:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7366:       return 1;
                   7367:     }
1.187     brouard  7368:     strcpy(modelsav,model); 
                   7369:     if ((strpt=strstr(model,"age*age")) !=0){
                   7370:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7371:       if(strpt != model){
                   7372:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7373:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7374:  corresponding column of parameters.\n",model);
                   7375:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7376:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7377:  corresponding column of parameters.\n",model); fflush(ficlog);
                   7378:       return 1;
                   7379:     }
                   7380: 
                   7381:       nagesqr=1;
                   7382:       if (strstr(model,"+age*age") !=0)
                   7383:        substrchaine(modelsav, model, "+age*age");
                   7384:       else if (strstr(model,"age*age+") !=0)
                   7385:        substrchaine(modelsav, model, "age*age+");
                   7386:       else 
                   7387:        substrchaine(modelsav, model, "age*age");
                   7388:     }else
                   7389:       nagesqr=0;
                   7390:     if (strlen(modelsav) >1){
                   7391:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7392:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   7393:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   7394:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   7395:                   * cst, age and age*age 
                   7396:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   7397:                   /* including age products which are counted in cptcovage.
                   7398:                  * but the covariates which are products must be treated 
                   7399:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   7400:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7401:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7402: 
                   7403:     
                   7404:       /*   Design
                   7405:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7406:        *  <          ncovcol=8                >
                   7407:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7408:        *   k=  1    2      3       4     5       6      7        8
                   7409:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7410:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   7411:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   7412:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   7413:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7414:        *  Tage[++cptcovage]=k
                   7415:        *       if products, new covar are created after ncovcol with k1
                   7416:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7417:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7418:        *  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
                   7419:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7420:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7421:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7422:        *  <          ncovcol=8                >
                   7423:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7424:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7425:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7426:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7427:        * p Tprod[1]@2={                         6, 5}
                   7428:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7429:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7430:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7431:        *How to reorganize?
                   7432:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7433:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7434:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7435:        * Struct []
                   7436:        */
1.145     brouard  7437: 
1.187     brouard  7438:       /* This loop fills the array Tvar from the string 'model'.*/
                   7439:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7440:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7441:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7442:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7443:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7444:       /*       k=1 Tvar[1]=2 (from V2) */
                   7445:       /*       k=5 Tvar[5] */
                   7446:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7447:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7448:       /*       } */
1.198     brouard  7449:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7450:       /*
                   7451:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7452:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7453:         Tvar[k]=0;
1.187     brouard  7454:       cptcovage=0;
                   7455:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   7456:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   7457:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   7458:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   7459:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   7460:        /*scanf("%d",i);*/
                   7461:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   7462:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   7463:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   7464:            /* covar is not filled and then is empty */
                   7465:            cptcovprod--;
                   7466:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   7467:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   7468:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   7469:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7470:            /*printf("stre=%s ", stre);*/
                   7471:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   7472:            cptcovprod--;
                   7473:            cutl(stre,strb,strc,'V');
                   7474:            Tvar[k]=atoi(stre);
                   7475:            cptcovage++;
                   7476:            Tage[cptcovage]=k;
                   7477:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   7478:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   7479:            cptcovn++;
                   7480:            cptcovprodnoage++;k1++;
                   7481:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   7482:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   7483:                                   because this model-covariate is a construction we invent a new column
                   7484:                                   ncovcol + k1
                   7485:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   7486:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   7487:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   7488:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   7489:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   7490:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   7491:            k2=k2+2;
                   7492:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   7493:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   7494:            for (i=1; i<=lastobs;i++){
                   7495:              /* Computes the new covariate which is a product of
                   7496:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   7497:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   7498:            }
                   7499:          } /* End age is not in the model */
                   7500:        } /* End if model includes a product */
                   7501:        else { /* no more sum */
                   7502:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   7503:          /*  scanf("%d",i);*/
                   7504:          cutl(strd,strc,strb,'V');
                   7505:          ks++; /**< Number of simple covariates */
1.145     brouard  7506:          cptcovn++;
1.187     brouard  7507:          Tvar[k]=atoi(strd);
                   7508:        }
                   7509:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   7510:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   7511:          scanf("%d",i);*/
                   7512:       } /* end of loop + on total covariates */
                   7513:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7514:   } /* end if strlen(model == 0) */
1.136     brouard  7515:   
                   7516:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7517:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7518: 
                   7519:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   7520:   printf("cptcovprod=%d ", cptcovprod);
                   7521:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   7522: 
                   7523:   scanf("%d ",i);*/
                   7524: 
                   7525: 
1.137     brouard  7526:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7527:   /*endread:*/
1.136     brouard  7528:     printf("Exiting decodemodel: ");
                   7529:     return (1);
                   7530: }
                   7531: 
1.169     brouard  7532: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7533: {
                   7534:   int i, m;
1.218     brouard  7535:   int firstone=0;
                   7536:   
1.136     brouard  7537:   for (i=1; i<=imx; i++) {
                   7538:     for(m=2; (m<= maxwav); m++) {
                   7539:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7540:        anint[m][i]=9999;
1.216     brouard  7541:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7542:          s[m][i]=-1;
1.136     brouard  7543:       }
                   7544:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7545:        *nberr = *nberr + 1;
1.218     brouard  7546:        if(firstone == 0){
                   7547:          firstone=1;
                   7548:        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);
                   7549:        }
                   7550:        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  7551:        s[m][i]=-1;
                   7552:       }
                   7553:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7554:        (*nberr)++;
1.136     brouard  7555:        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]); 
                   7556:        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]); 
                   7557:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7558:       }
                   7559:     }
                   7560:   }
                   7561: 
                   7562:   for (i=1; i<=imx; i++)  {
                   7563:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7564:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7565:       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  7566:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7567:          if(agedc[i]>0){
                   7568:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7569:              agev[m][i]=agedc[i];
1.214     brouard  7570:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7571:            }else {
1.136     brouard  7572:              if ((int)andc[i]!=9999){
                   7573:                nbwarn++;
                   7574:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7575:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7576:                agev[m][i]=-1;
                   7577:              }
                   7578:            }
1.169     brouard  7579:          } /* agedc > 0 */
1.214     brouard  7580:        } /* end if */
1.136     brouard  7581:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7582:                                 years but with the precision of a month */
                   7583:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7584:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7585:            agev[m][i]=1;
                   7586:          else if(agev[m][i] < *agemin){ 
                   7587:            *agemin=agev[m][i];
                   7588:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7589:          }
                   7590:          else if(agev[m][i] >*agemax){
                   7591:            *agemax=agev[m][i];
1.156     brouard  7592:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7593:          }
                   7594:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7595:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7596:        } /* en if 9*/
1.136     brouard  7597:        else { /* =9 */
1.214     brouard  7598:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7599:          agev[m][i]=1;
                   7600:          s[m][i]=-1;
                   7601:        }
                   7602:       }
1.214     brouard  7603:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7604:        agev[m][i]=1;
1.214     brouard  7605:       else{
                   7606:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7607:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7608:        agev[m][i]=0;
                   7609:       }
                   7610:     } /* End for lastpass */
                   7611:   }
1.136     brouard  7612:     
                   7613:   for (i=1; i<=imx; i++)  {
                   7614:     for(m=firstpass; (m<=lastpass); m++){
                   7615:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7616:        (*nberr)++;
1.136     brouard  7617:        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);     
                   7618:        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);     
                   7619:        return 1;
                   7620:       }
                   7621:     }
                   7622:   }
                   7623: 
                   7624:   /*for (i=1; i<=imx; i++){
                   7625:   for (m=firstpass; (m<lastpass); m++){
                   7626:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7627: }
                   7628: 
                   7629: }*/
                   7630: 
                   7631: 
1.139     brouard  7632:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7633:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7634: 
                   7635:   return (0);
1.164     brouard  7636:  /* endread:*/
1.136     brouard  7637:     printf("Exiting calandcheckages: ");
                   7638:     return (1);
                   7639: }
                   7640: 
1.172     brouard  7641: #if defined(_MSC_VER)
                   7642: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7643: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7644: //#include "stdafx.h"
                   7645: //#include <stdio.h>
                   7646: //#include <tchar.h>
                   7647: //#include <windows.h>
                   7648: //#include <iostream>
                   7649: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7650: 
                   7651: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7652: 
                   7653: BOOL IsWow64()
                   7654: {
                   7655:        BOOL bIsWow64 = FALSE;
                   7656: 
                   7657:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7658:        //  (HANDLE, PBOOL);
                   7659: 
                   7660:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7661: 
                   7662:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7663:        const char funcName[] = "IsWow64Process";
                   7664:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7665:                GetProcAddress(module, funcName);
                   7666: 
                   7667:        if (NULL != fnIsWow64Process)
                   7668:        {
                   7669:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7670:                        &bIsWow64))
                   7671:                        //throw std::exception("Unknown error");
                   7672:                        printf("Unknown error\n");
                   7673:        }
                   7674:        return bIsWow64 != FALSE;
                   7675: }
                   7676: #endif
1.177     brouard  7677: 
1.191     brouard  7678: void syscompilerinfo(int logged)
1.167     brouard  7679:  {
                   7680:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7681:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7682:    /* /GS /W3 /Gy
                   7683:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7684:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7685:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7686:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7687:    */ 
                   7688:    /* 64 bits */
1.185     brouard  7689:    /*
                   7690:      /GS /W3 /Gy
                   7691:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7692:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7693:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7694:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7695:    /* Optimization are useless and O3 is slower than O2 */
                   7696:    /*
                   7697:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7698:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7699:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7700:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7701:    */
1.186     brouard  7702:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  7703:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7704:       /PDB:"visual studio
                   7705:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7706:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7707:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7708:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7709:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7710:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7711:       uiAccess='false'"
                   7712:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7713:       /NOLOGO /TLBID:1
                   7714:    */
1.177     brouard  7715: #if defined __INTEL_COMPILER
1.178     brouard  7716: #if defined(__GNUC__)
                   7717:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7718: #endif
1.177     brouard  7719: #elif defined(__GNUC__) 
1.179     brouard  7720: #ifndef  __APPLE__
1.174     brouard  7721: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  7722: #endif
1.177     brouard  7723:    struct utsname sysInfo;
1.178     brouard  7724:    int cross = CROSS;
                   7725:    if (cross){
                   7726:           printf("Cross-");
1.191     brouard  7727:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  7728:    }
1.174     brouard  7729: #endif
                   7730: 
1.171     brouard  7731: #include <stdint.h>
1.178     brouard  7732: 
1.191     brouard  7733:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  7734: #if defined(__clang__)
1.191     brouard  7735:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  7736: #endif
                   7737: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  7738:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  7739: #endif
                   7740: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  7741:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  7742: #endif
                   7743: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  7744:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  7745: #endif
                   7746: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  7747:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  7748: #endif
                   7749: #if defined(_MSC_VER)
1.191     brouard  7750:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  7751: #endif
                   7752: #if defined(__PGI)
1.191     brouard  7753:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  7754: #endif
                   7755: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  7756:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  7757: #endif
1.191     brouard  7758:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  7759:    
1.167     brouard  7760: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7761: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7762:     // Windows (x64 and x86)
1.191     brouard  7763:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  7764: #elif __unix__ // all unices, not all compilers
                   7765:     // Unix
1.191     brouard  7766:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  7767: #elif __linux__
                   7768:     // linux
1.191     brouard  7769:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  7770: #elif __APPLE__
1.174     brouard  7771:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  7772:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  7773: #endif
                   7774: 
                   7775: /*  __MINGW32__          */
                   7776: /*  __CYGWIN__  */
                   7777: /* __MINGW64__  */
                   7778: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7779: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7780: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7781: /* _WIN64  // Defined for applications for Win64. */
                   7782: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7783: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  7784: 
1.167     brouard  7785: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  7786:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  7787: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  7788:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  7789: #else
1.191     brouard  7790:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  7791: #endif
                   7792: 
1.169     brouard  7793: #if defined(__GNUC__)
                   7794: # if defined(__GNUC_PATCHLEVEL__)
                   7795: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7796:                             + __GNUC_MINOR__ * 100 \
                   7797:                             + __GNUC_PATCHLEVEL__)
                   7798: # else
                   7799: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7800:                             + __GNUC_MINOR__ * 100)
                   7801: # endif
1.174     brouard  7802:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  7803:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  7804: 
                   7805:    if (uname(&sysInfo) != -1) {
                   7806:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  7807:         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  7808:    }
                   7809:    else
                   7810:       perror("uname() error");
1.179     brouard  7811:    //#ifndef __INTEL_COMPILER 
                   7812: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  7813:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  7814:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  7815: #endif
1.169     brouard  7816: #endif
1.172     brouard  7817: 
                   7818:    //   void main()
                   7819:    //   {
1.169     brouard  7820: #if defined(_MSC_VER)
1.174     brouard  7821:    if (IsWow64()){
1.191     brouard  7822:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7823:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  7824:    }
                   7825:    else{
1.191     brouard  7826:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7827:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  7828:    }
1.172     brouard  7829:    //     printf("\nPress Enter to continue...");
                   7830:    //     getchar();
                   7831:    //   }
                   7832: 
1.169     brouard  7833: #endif
                   7834:    
1.167     brouard  7835: 
1.219     brouard  7836: }
1.136     brouard  7837: 
1.219     brouard  7838: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  7839:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7840:   int i, j, k, i1 ;
1.202     brouard  7841:   /* double ftolpl = 1.e-10; */
1.180     brouard  7842:   double age, agebase, agelim;
1.203     brouard  7843:   double tot;
1.180     brouard  7844: 
1.202     brouard  7845:   strcpy(filerespl,"PL_");
                   7846:   strcat(filerespl,fileresu);
                   7847:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7848:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7849:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7850:   }
                   7851:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7852:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7853:   pstamp(ficrespl);
1.203     brouard  7854:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  7855:   fprintf(ficrespl,"#Age ");
                   7856:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7857:   fprintf(ficrespl,"\n");
1.180     brouard  7858:   
1.219     brouard  7859:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  7860: 
1.219     brouard  7861:   agebase=ageminpar;
                   7862:   agelim=agemaxpar;
1.180     brouard  7863: 
1.219     brouard  7864:   i1=pow(2,cptcoveff);
                   7865:   if (cptcovn < 1){i1=1;}
1.180     brouard  7866: 
1.220     brouard  7867:   for(k=1; k<=i1;k++){
                   7868:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  7869:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  7870:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  7871:     /* k=k+1; */
1.219     brouard  7872:     /* to clean */
                   7873:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   7874:     fprintf(ficrespl,"#******");
                   7875:     printf("#******");
                   7876:     fprintf(ficlog,"#******");
                   7877:     for(j=1;j<=cptcoveff;j++) {
                   7878:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7879:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7880:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7881:     }
                   7882:     fprintf(ficrespl,"******\n");
                   7883:     printf("******\n");
                   7884:     fprintf(ficlog,"******\n");
1.220     brouard  7885:                if(invalidvarcomb[k]){
                   7886:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   7887:                                                fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
                   7888:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   7889:                                                continue;
                   7890:                }
1.219     brouard  7891: 
                   7892:     fprintf(ficrespl,"#Age ");
                   7893:     for(j=1;j<=cptcoveff;j++) {
                   7894:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7895:     }
                   7896:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   7897:     fprintf(ficrespl,"Total Years_to_converge\n");
                   7898:        
                   7899:     for (age=agebase; age<=agelim; age++){
                   7900:       /* for (age=agebase; age<=agebase; age++){ */
                   7901:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   7902:       fprintf(ficrespl,"%.0f ",age );
                   7903:       for(j=1;j<=cptcoveff;j++)
1.220     brouard  7904:                                                        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  7905:       tot=0.;
                   7906:       for(i=1; i<=nlstate;i++){
1.220     brouard  7907:                                                        tot +=  prlim[i][i];
                   7908:                                                        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  7909:       }
                   7910:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   7911:     } /* Age */
                   7912:     /* was end of cptcod */
                   7913:   } /* cptcov */
                   7914:   return 0;
1.180     brouard  7915: }
                   7916: 
1.218     brouard  7917: 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){
                   7918:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   7919:        
                   7920:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   7921:    * at any age between ageminpar and agemaxpar
                   7922:         */
1.217     brouard  7923:   int i, j, k, i1 ;
                   7924:   /* double ftolpl = 1.e-10; */
                   7925:   double age, agebase, agelim;
                   7926:   double tot;
1.218     brouard  7927:   /* double ***mobaverage; */
                   7928:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  7929: 
                   7930:   strcpy(fileresplb,"PLB_");
                   7931:   strcat(fileresplb,fileresu);
                   7932:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   7933:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7934:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7935:   }
                   7936:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7937:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7938:   pstamp(ficresplb);
                   7939:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   7940:   fprintf(ficresplb,"#Age ");
                   7941:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   7942:   fprintf(ficresplb,"\n");
                   7943:   
1.218     brouard  7944:   
                   7945:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   7946:   
                   7947:   agebase=ageminpar;
                   7948:   agelim=agemaxpar;
                   7949:   
                   7950:   
                   7951:   i1=pow(2,cptcoveff);
                   7952:   if (cptcovn < 1){i1=1;}
1.220     brouard  7953: 
                   7954:        for(k=1; k<=i1;k++){ 
                   7955:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.217     brouard  7956:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.218     brouard  7957:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  7958:     /* k=k+1; */
1.218     brouard  7959:     /* to clean */
                   7960:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   7961:     fprintf(ficresplb,"#******");
                   7962:     printf("#******");
                   7963:     fprintf(ficlog,"#******");
                   7964:     for(j=1;j<=cptcoveff;j++) {
                   7965:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7966:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7967:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7968:     }
                   7969:     fprintf(ficresplb,"******\n");
                   7970:     printf("******\n");
                   7971:     fprintf(ficlog,"******\n");
1.220     brouard  7972:                if(invalidvarcomb[k]){
                   7973:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   7974:                                                fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   7975:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   7976:                                                continue;
                   7977:                }
1.218     brouard  7978:     
                   7979:     fprintf(ficresplb,"#Age ");
                   7980:     for(j=1;j<=cptcoveff;j++) {
                   7981:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7982:     }
                   7983:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   7984:     fprintf(ficresplb,"Total Years_to_converge\n");
                   7985:     
                   7986:     
                   7987:     for (age=agebase; age<=agelim; age++){
                   7988:       /* for (age=agebase; age<=agebase; age++){ */
                   7989:       if(mobilavproj > 0){
                   7990:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   7991:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.219     brouard  7992:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  7993:       }else if (mobilavproj == 0){
1.219     brouard  7994:                                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);
                   7995:                                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);
                   7996:                                exit(1);
1.218     brouard  7997:       }else{
1.219     brouard  7998:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   7999:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8000:       }
                   8001:       fprintf(ficresplb,"%.0f ",age );
                   8002:       for(j=1;j<=cptcoveff;j++)
1.219     brouard  8003:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  8004:       tot=0.;
                   8005:       for(i=1; i<=nlstate;i++){
1.219     brouard  8006:                                tot +=  bprlim[i][i];
                   8007:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  8008:       }
                   8009:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8010:     } /* Age */
                   8011:     /* was end of cptcod */
                   8012:   } /* cptcov */
                   8013:   
                   8014:   /* hBijx(p, bage, fage); */
                   8015:   /* fclose(ficrespijb); */
                   8016:   
                   8017:   return 0;
1.217     brouard  8018: }
1.218     brouard  8019:  
1.180     brouard  8020: int hPijx(double *p, int bage, int fage){
                   8021:     /*------------- h Pij x at various ages ------------*/
                   8022: 
                   8023:   int stepsize;
                   8024:   int agelim;
                   8025:   int hstepm;
                   8026:   int nhstepm;
                   8027:   int h, i, i1, j, k;
                   8028: 
                   8029:   double agedeb;
                   8030:   double ***p3mat;
                   8031: 
1.201     brouard  8032:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  8033:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8034:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8035:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8036:     }
                   8037:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8038:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8039:   
                   8040:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8041:     /*if (stepm<=24) stepsize=2;*/
                   8042: 
                   8043:     agelim=AGESUP;
                   8044:     hstepm=stepsize*YEARM; /* Every year of age */
                   8045:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  8046:                
1.180     brouard  8047:     /* hstepm=1;   aff par mois*/
                   8048:     pstamp(ficrespij);
                   8049:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   8050:     i1= pow(2,cptcoveff);
1.218     brouard  8051:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8052:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8053:                /*      k=k+1;  */
1.183     brouard  8054:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8055:       fprintf(ficrespij,"\n#****** ");
                   8056:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  8057:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  8058:       fprintf(ficrespij,"******\n");
                   8059:       
                   8060:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8061:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8062:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8063:        
                   8064:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  8065:        
1.183     brouard  8066:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8067:        oldm=oldms;savm=savms;
                   8068:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8069:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8070:        for(i=1; i<=nlstate;i++)
                   8071:          for(j=1; j<=nlstate+ndeath;j++)
                   8072:            fprintf(ficrespij," %1d-%1d",i,j);
                   8073:        fprintf(ficrespij,"\n");
                   8074:        for (h=0; h<=nhstepm; h++){
                   8075:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8076:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  8077:          for(i=1; i<=nlstate;i++)
                   8078:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  8079:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  8080:          fprintf(ficrespij,"\n");
                   8081:        }
1.183     brouard  8082:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8083:        fprintf(ficrespij,"\n");
                   8084:       }
1.180     brouard  8085:       /*}*/
                   8086:     }
1.218     brouard  8087:     return 0;
1.180     brouard  8088: }
1.218     brouard  8089:  
                   8090:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  8091:     /*------------- h Bij x at various ages ------------*/
                   8092: 
                   8093:   int stepsize;
1.218     brouard  8094:   /* int agelim; */
                   8095:        int ageminl;
1.217     brouard  8096:   int hstepm;
                   8097:   int nhstepm;
                   8098:   int h, i, i1, j, k;
1.218     brouard  8099:        
1.217     brouard  8100:   double agedeb;
                   8101:   double ***p3mat;
1.218     brouard  8102:        
                   8103:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8104:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8105:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8106:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8107:   }
                   8108:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8109:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8110:   
                   8111:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8112:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  8113:   
1.218     brouard  8114:   /* agelim=AGESUP; */
                   8115:   ageminl=30;
                   8116:   hstepm=stepsize*YEARM; /* Every year of age */
                   8117:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8118:   
                   8119:   /* hstepm=1;   aff par mois*/
                   8120:   pstamp(ficrespijb);
                   8121:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
                   8122:   i1= pow(2,cptcoveff);
                   8123:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8124:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8125:   /*   k=k+1;  */
                   8126:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8127:     fprintf(ficrespijb,"\n#****** ");
                   8128:     for(j=1;j<=cptcoveff;j++)
                   8129:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8130:     fprintf(ficrespijb,"******\n");
                   8131:     
                   8132:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8133:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8134:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8135:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8136:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8137:       
                   8138:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8139:       
                   8140:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8141:       /* oldm=oldms;savm=savms; */
                   8142:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8143:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8144:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8145:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8146:       for(i=1; i<=nlstate;i++)
                   8147:        for(j=1; j<=nlstate+ndeath;j++)
                   8148:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8149:       fprintf(ficrespijb,"\n");
                   8150:       for (h=0; h<=nhstepm; h++){
                   8151:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8152:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8153:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8154:        for(i=1; i<=nlstate;i++)
                   8155:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8156:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8157:        fprintf(ficrespijb,"\n");
                   8158:       }
1.218     brouard  8159:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8160:       fprintf(ficrespijb,"\n");
1.217     brouard  8161:     }
1.218     brouard  8162:     /*}*/
                   8163:   }
                   8164:   return 0;
                   8165:  } /*  hBijx */
1.217     brouard  8166: 
1.180     brouard  8167: 
1.136     brouard  8168: /***********************************************/
                   8169: /**************** Main Program *****************/
                   8170: /***********************************************/
                   8171: 
                   8172: int main(int argc, char *argv[])
                   8173: {
                   8174: #ifdef GSL
                   8175:   const gsl_multimin_fminimizer_type *T;
                   8176:   size_t iteri = 0, it;
                   8177:   int rval = GSL_CONTINUE;
                   8178:   int status = GSL_SUCCESS;
                   8179:   double ssval;
                   8180: #endif
                   8181:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8182:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8183:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8184:   int jj, ll, li, lj, lk;
1.136     brouard  8185:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8186:   int num_filled;
1.136     brouard  8187:   int itimes;
                   8188:   int NDIM=2;
                   8189:   int vpopbased=0;
                   8190: 
1.164     brouard  8191:   char ca[32], cb[32];
1.136     brouard  8192:   /*  FILE *fichtm; *//* Html File */
                   8193:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8194:   struct stat info;
1.191     brouard  8195:   double agedeb=0.;
1.194     brouard  8196: 
                   8197:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  8198:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  8199: 
1.165     brouard  8200:   double fret;
1.191     brouard  8201:   double dum=0.; /* Dummy variable */
1.136     brouard  8202:   double ***p3mat;
1.218     brouard  8203:   /* double ***mobaverage; */
1.164     brouard  8204: 
                   8205:   char line[MAXLINE];
1.197     brouard  8206:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8207: 
                   8208:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  8209:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  8210:   char *tok, *val; /* pathtot */
1.136     brouard  8211:   int firstobs=1, lastobs=10;
1.195     brouard  8212:   int c,  h , cpt, c2;
1.191     brouard  8213:   int jl=0;
                   8214:   int i1, j1, jk, stepsize=0;
1.194     brouard  8215:   int count=0;
                   8216: 
1.164     brouard  8217:   int *tab; 
1.136     brouard  8218:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  8219:   int backcast=0;
1.136     brouard  8220:   int mobilav=0,popforecast=0;
1.191     brouard  8221:   int hstepm=0, nhstepm=0;
1.136     brouard  8222:   int agemortsup;
                   8223:   float  sumlpop=0.;
                   8224:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8225:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8226: 
1.191     brouard  8227:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  8228:   double ftolpl=FTOL;
                   8229:   double **prlim;
1.217     brouard  8230:   double **bprlim;
1.136     brouard  8231:   double ***param; /* Matrix of parameters */
                   8232:   double  *p;
                   8233:   double **matcov; /* Matrix of covariance */
1.203     brouard  8234:   double **hess; /* Hessian matrix */
1.136     brouard  8235:   double ***delti3; /* Scale */
                   8236:   double *delti; /* Scale */
                   8237:   double ***eij, ***vareij;
                   8238:   double **varpl; /* Variances of prevalence limits by age */
                   8239:   double *epj, vepp;
1.164     brouard  8240: 
1.136     brouard  8241:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  8242:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8243: 
1.136     brouard  8244:   double **ximort;
1.145     brouard  8245:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  8246:   int *dcwave;
                   8247: 
1.164     brouard  8248:   char z[1]="c";
1.136     brouard  8249: 
                   8250:   /*char  *strt;*/
                   8251:   char strtend[80];
1.126     brouard  8252: 
1.164     brouard  8253: 
1.126     brouard  8254: /*   setlocale (LC_ALL, ""); */
                   8255: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8256: /*   textdomain (PACKAGE); */
                   8257: /*   setlocale (LC_CTYPE, ""); */
                   8258: /*   setlocale (LC_MESSAGES, ""); */
                   8259: 
                   8260:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  8261:   rstart_time = time(NULL);  
                   8262:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8263:   start_time = *localtime(&rstart_time);
1.126     brouard  8264:   curr_time=start_time;
1.157     brouard  8265:   /*tml = *localtime(&start_time.tm_sec);*/
                   8266:   /* strcpy(strstart,asctime(&tml)); */
                   8267:   strcpy(strstart,asctime(&start_time));
1.126     brouard  8268: 
                   8269: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  8270: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8271: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  8272: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8273: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8274: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  8275: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  8276: /*   strt=asctime(&tmg); */
                   8277: /*   printf("Time(after) =%s",strstart);  */
                   8278: /*  (void) time (&time_value);
                   8279: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8280: *  tm = *localtime(&time_value);
                   8281: *  strstart=asctime(&tm);
                   8282: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8283: */
                   8284: 
                   8285:   nberr=0; /* Number of errors and warnings */
                   8286:   nbwarn=0;
1.184     brouard  8287: #ifdef WIN32
                   8288:   _getcwd(pathcd, size);
                   8289: #else
1.126     brouard  8290:   getcwd(pathcd, size);
1.184     brouard  8291: #endif
1.191     brouard  8292:   syscompilerinfo(0);
1.196     brouard  8293:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  8294:   if(argc <=1){
                   8295:     printf("\nEnter the parameter file name: ");
1.205     brouard  8296:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8297:       printf("ERROR Empty parameter file name\n");
                   8298:       goto end;
                   8299:     }
1.126     brouard  8300:     i=strlen(pathr);
                   8301:     if(pathr[i-1]=='\n')
                   8302:       pathr[i-1]='\0';
1.156     brouard  8303:     i=strlen(pathr);
1.205     brouard  8304:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  8305:       pathr[i-1]='\0';
1.205     brouard  8306:     }
                   8307:     i=strlen(pathr);
                   8308:     if( i==0 ){
                   8309:       printf("ERROR Empty parameter file name\n");
                   8310:       goto end;
                   8311:     }
                   8312:     for (tok = pathr; tok != NULL; ){
1.126     brouard  8313:       printf("Pathr |%s|\n",pathr);
                   8314:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8315:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8316:       strcpy (pathtot, val);
                   8317:       if(pathr[0] == '\0') break; /* Dirty */
                   8318:     }
                   8319:   }
                   8320:   else{
                   8321:     strcpy(pathtot,argv[1]);
                   8322:   }
                   8323:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8324:   /*cygwin_split_path(pathtot,path,optionfile);
                   8325:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8326:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8327: 
                   8328:   /* Split argv[0], imach program to get pathimach */
                   8329:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8330:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8331:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8332:  /*   strcpy(pathimach,argv[0]); */
                   8333:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8334:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8335:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  8336: #ifdef WIN32
                   8337:   _chdir(path); /* Can be a relative path */
                   8338:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8339: #else
1.126     brouard  8340:   chdir(path); /* Can be a relative path */
1.184     brouard  8341:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8342: #endif
                   8343:   printf("Current directory %s!\n",pathcd);
1.126     brouard  8344:   strcpy(command,"mkdir ");
                   8345:   strcat(command,optionfilefiname);
                   8346:   if((outcmd=system(command)) != 0){
1.169     brouard  8347:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  8348:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8349:     /* fclose(ficlog); */
                   8350: /*     exit(1); */
                   8351:   }
                   8352: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8353: /*     perror("mkdir"); */
                   8354: /*   } */
                   8355: 
                   8356:   /*-------- arguments in the command line --------*/
                   8357: 
1.186     brouard  8358:   /* Main Log file */
1.126     brouard  8359:   strcat(filelog, optionfilefiname);
                   8360:   strcat(filelog,".log");    /* */
                   8361:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8362:     printf("Problem with logfile %s\n",filelog);
                   8363:     goto end;
                   8364:   }
                   8365:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  8366:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  8367:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8368:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8369:  path=%s \n\
                   8370:  optionfile=%s\n\
                   8371:  optionfilext=%s\n\
1.156     brouard  8372:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  8373: 
1.197     brouard  8374:   syscompilerinfo(1);
1.167     brouard  8375: 
1.126     brouard  8376:   printf("Local time (at start):%s",strstart);
                   8377:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8378:   fflush(ficlog);
                   8379: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  8380: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  8381: 
                   8382:   /* */
                   8383:   strcpy(fileres,"r");
                   8384:   strcat(fileres, optionfilefiname);
1.201     brouard  8385:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  8386:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  8387:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  8388: 
1.186     brouard  8389:   /* Main ---------arguments file --------*/
1.126     brouard  8390: 
                   8391:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  8392:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8393:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  8394:     fflush(ficlog);
1.149     brouard  8395:     /* goto end; */
                   8396:     exit(70); 
1.126     brouard  8397:   }
                   8398: 
                   8399: 
                   8400: 
                   8401:   strcpy(filereso,"o");
1.201     brouard  8402:   strcat(filereso,fileresu);
1.126     brouard  8403:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8404:     printf("Problem with Output resultfile: %s\n", filereso);
                   8405:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8406:     fflush(ficlog);
                   8407:     goto end;
                   8408:   }
                   8409: 
                   8410:   /* Reads comments: lines beginning with '#' */
                   8411:   numlinepar=0;
1.197     brouard  8412: 
                   8413:     /* First parameter line */
                   8414:   while(fgets(line, MAXLINE, ficpar)) {
                   8415:     /* If line starts with a # it is a comment */
                   8416:     if (line[0] == '#') {
                   8417:       numlinepar++;
                   8418:       fputs(line,stdout);
                   8419:       fputs(line,ficparo);
                   8420:       fputs(line,ficlog);
                   8421:       continue;
                   8422:     }else
                   8423:       break;
                   8424:   }
                   8425:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8426:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8427:     if (num_filled != 5) {
                   8428:       printf("Should be 5 parameters\n");
                   8429:     }
1.126     brouard  8430:     numlinepar++;
1.197     brouard  8431:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8432:   }
                   8433:   /* Second parameter line */
                   8434:   while(fgets(line, MAXLINE, ficpar)) {
                   8435:     /* If line starts with a # it is a comment */
                   8436:     if (line[0] == '#') {
                   8437:       numlinepar++;
                   8438:       fputs(line,stdout);
                   8439:       fputs(line,ficparo);
                   8440:       fputs(line,ficlog);
                   8441:       continue;
                   8442:     }else
                   8443:       break;
                   8444:   }
                   8445:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   8446:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8447:     if (num_filled != 8) {
1.209     brouard  8448:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
                   8449:       printf("but line=%s\n",line);
1.197     brouard  8450:     }
                   8451:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
1.126     brouard  8452:   }
1.203     brouard  8453:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8454:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8455:   /* Third parameter line */
                   8456:   while(fgets(line, MAXLINE, ficpar)) {
                   8457:     /* If line starts with a # it is a comment */
                   8458:     if (line[0] == '#') {
                   8459:       numlinepar++;
                   8460:       fputs(line,stdout);
                   8461:       fputs(line,ficparo);
                   8462:       fputs(line,ficlog);
                   8463:       continue;
                   8464:     }else
                   8465:       break;
                   8466:   }
1.201     brouard  8467:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8468:     if (num_filled == 0)
                   8469:             model[0]='\0';
                   8470:     else if (num_filled != 1){
1.197     brouard  8471:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8472:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8473:       model[0]='\0';
                   8474:       goto end;
                   8475:     }
                   8476:     else{
                   8477:       if (model[0]=='+'){
                   8478:        for(i=1; i<=strlen(model);i++)
                   8479:          modeltemp[i-1]=model[i];
1.201     brouard  8480:        strcpy(model,modeltemp); 
1.197     brouard  8481:       }
                   8482:     }
1.199     brouard  8483:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8484:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8485:   }
                   8486:   /* 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); */
                   8487:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8488:   /* 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.203     brouard  8489:   fprintf(ficparo,"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);
                   8490:   fprintf(ficlog,"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.126     brouard  8491:   fflush(ficlog);
1.190     brouard  8492:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8493:   if(model[0]=='#'){
1.187     brouard  8494:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8495:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8496:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8497:     if(mle != -1){
                   8498:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8499:       exit(1);
                   8500:     }
                   8501:   }
1.126     brouard  8502:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8503:     ungetc(c,ficpar);
                   8504:     fgets(line, MAXLINE, ficpar);
                   8505:     numlinepar++;
1.195     brouard  8506:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8507:       z[0]=line[1];
                   8508:     }
                   8509:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8510:     fputs(line, stdout);
                   8511:     //puts(line);
1.126     brouard  8512:     fputs(line,ficparo);
                   8513:     fputs(line,ficlog);
                   8514:   }
                   8515:   ungetc(c,ficpar);
                   8516: 
                   8517:    
1.145     brouard  8518:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  8519:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8520:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8521:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8522:   */
                   8523:   if (strlen(model)>1) 
1.187     brouard  8524:     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  8525:   else
1.187     brouard  8526:     ncovmodel=2; /* Constant and age */
1.133     brouard  8527:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8528:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8529:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8530:     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);
                   8531:     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);
                   8532:     fflush(stdout);
                   8533:     fclose (ficlog);
                   8534:     goto end;
                   8535:   }
1.126     brouard  8536:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8537:   delti=delti3[1][1];
                   8538:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8539:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8540:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8541:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8542:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8543:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8544:     fclose (ficparo);
                   8545:     fclose (ficlog);
                   8546:     goto end;
                   8547:     exit(0);
1.220     brouard  8548:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  8549:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8550:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8551:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8552:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8553:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8554:     hess=matrix(1,npar,1,npar);
1.220     brouard  8555:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  8556:     /* Read guessed parameters */
1.126     brouard  8557:     /* Reads comments: lines beginning with '#' */
                   8558:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8559:       ungetc(c,ficpar);
                   8560:       fgets(line, MAXLINE, ficpar);
                   8561:       numlinepar++;
1.141     brouard  8562:       fputs(line,stdout);
1.126     brouard  8563:       fputs(line,ficparo);
                   8564:       fputs(line,ficlog);
                   8565:     }
                   8566:     ungetc(c,ficpar);
                   8567:     
                   8568:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8569:     for(i=1; i <=nlstate; i++){
1.220     brouard  8570:                        j=0;
1.126     brouard  8571:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.220     brouard  8572:                                if(jj==i) continue;
                   8573:                                j++;
                   8574:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8575:                                if ((i1 != i) || (j1 != jj)){
                   8576:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  8577: It might be a problem of design; if ncovcol and the model are correct\n \
                   8578: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.220     brouard  8579:                                        exit(1);
                   8580:                                }
                   8581:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8582:                                if(mle==1)
                   8583:                                        printf("%1d%1d",i,jj);
                   8584:                                fprintf(ficlog,"%1d%1d",i,jj);
                   8585:                                for(k=1; k<=ncovmodel;k++){
                   8586:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   8587:                                        if(mle==1){
                   8588:                                                printf(" %lf",param[i][j][k]);
                   8589:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8590:                                        }
                   8591:                                        else
                   8592:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8593:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   8594:                                }
                   8595:                                fscanf(ficpar,"\n");
                   8596:                                numlinepar++;
                   8597:                                if(mle==1)
                   8598:                                        printf("\n");
                   8599:                                fprintf(ficlog,"\n");
                   8600:                                fprintf(ficparo,"\n");
1.126     brouard  8601:       }
                   8602:     }  
                   8603:     fflush(ficlog);
                   8604: 
1.145     brouard  8605:     /* Reads scales values */
1.126     brouard  8606:     p=param[1][1];
                   8607:     
                   8608:     /* Reads comments: lines beginning with '#' */
                   8609:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8610:       ungetc(c,ficpar);
                   8611:       fgets(line, MAXLINE, ficpar);
                   8612:       numlinepar++;
1.141     brouard  8613:       fputs(line,stdout);
1.126     brouard  8614:       fputs(line,ficparo);
                   8615:       fputs(line,ficlog);
                   8616:     }
                   8617:     ungetc(c,ficpar);
                   8618: 
                   8619:     for(i=1; i <=nlstate; i++){
                   8620:       for(j=1; j <=nlstate+ndeath-1; j++){
1.220     brouard  8621:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8622:                                if ( (i1-i) * (j1-j) != 0){
                   8623:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8624:                                        exit(1);
                   8625:                                }
                   8626:                                printf("%1d%1d",i,j);
                   8627:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8628:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   8629:                                for(k=1; k<=ncovmodel;k++){
                   8630:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8631:                                        printf(" %le",delti3[i][j][k]);
                   8632:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   8633:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   8634:                                }
                   8635:                                fscanf(ficpar,"\n");
                   8636:                                numlinepar++;
                   8637:                                printf("\n");
                   8638:                                fprintf(ficparo,"\n");
                   8639:                                fprintf(ficlog,"\n");
1.126     brouard  8640:       }
                   8641:     }
                   8642:     fflush(ficlog);
1.220     brouard  8643:                
1.145     brouard  8644:     /* Reads covariance matrix */
1.126     brouard  8645:     delti=delti3[1][1];
1.220     brouard  8646:                
                   8647:                
1.126     brouard  8648:     /* 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  8649:                
1.126     brouard  8650:     /* Reads comments: lines beginning with '#' */
                   8651:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8652:       ungetc(c,ficpar);
                   8653:       fgets(line, MAXLINE, ficpar);
                   8654:       numlinepar++;
1.141     brouard  8655:       fputs(line,stdout);
1.126     brouard  8656:       fputs(line,ficparo);
                   8657:       fputs(line,ficlog);
                   8658:     }
                   8659:     ungetc(c,ficpar);
1.220     brouard  8660:                
1.126     brouard  8661:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8662:     hess=matrix(1,npar,1,npar);
1.131     brouard  8663:     for(i=1; i <=npar; i++)
                   8664:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  8665:                
1.194     brouard  8666:     /* Scans npar lines */
1.126     brouard  8667:     for(i=1; i <=npar; i++){
1.194     brouard  8668:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8669:       if(count != 3){
1.220     brouard  8670:                                printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8671: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8672: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8673:                                fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8674: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8675: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8676:                                exit(1);
                   8677:       }else{
                   8678:                                if(mle==1)
                   8679:                                        printf("%1d%1d%1d",i1,j1,jk);
                   8680:                        }
1.194     brouard  8681:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8682:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  8683:       for(j=1; j <=i; j++){
1.220     brouard  8684:                                fscanf(ficpar," %le",&matcov[i][j]);
                   8685:                                if(mle==1){
                   8686:                                        printf(" %.5le",matcov[i][j]);
                   8687:                                }
                   8688:                                fprintf(ficlog," %.5le",matcov[i][j]);
                   8689:                                fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  8690:       }
                   8691:       fscanf(ficpar,"\n");
                   8692:       numlinepar++;
                   8693:       if(mle==1)
1.220     brouard  8694:                                printf("\n");
1.126     brouard  8695:       fprintf(ficlog,"\n");
                   8696:       fprintf(ficparo,"\n");
                   8697:     }
1.194     brouard  8698:     /* End of read covariance matrix npar lines */
1.126     brouard  8699:     for(i=1; i <=npar; i++)
                   8700:       for(j=i+1;j<=npar;j++)
1.220     brouard  8701:                                matcov[i][j]=matcov[j][i];
1.126     brouard  8702:     
                   8703:     if(mle==1)
                   8704:       printf("\n");
                   8705:     fprintf(ficlog,"\n");
                   8706:     
                   8707:     fflush(ficlog);
                   8708:     
                   8709:     /*-------- Rewriting parameter file ----------*/
                   8710:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8711:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8712:     strcat(rfileres,".");    /* */
                   8713:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8714:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  8715:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8716:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  8717:     }
                   8718:     fprintf(ficres,"#%s\n",version);
                   8719:   }    /* End of mle != -3 */
1.218     brouard  8720:   
1.186     brouard  8721:   /*  Main data
                   8722:    */
1.126     brouard  8723:   n= lastobs;
                   8724:   num=lvector(1,n);
                   8725:   moisnais=vector(1,n);
                   8726:   annais=vector(1,n);
                   8727:   moisdc=vector(1,n);
                   8728:   andc=vector(1,n);
1.220     brouard  8729:   weight=vector(1,n);
1.126     brouard  8730:   agedc=vector(1,n);
                   8731:   cod=ivector(1,n);
1.220     brouard  8732:   for(i=1;i<=n;i++){
                   8733:                num[i]=0;
                   8734:                moisnais[i]=0;
                   8735:                annais[i]=0;
                   8736:                moisdc[i]=0;
                   8737:                andc[i]=0;
                   8738:                agedc[i]=0;
                   8739:                cod[i]=0;
                   8740:                weight[i]=1.0; /* Equal weights, 1 by default */
                   8741:        }
1.126     brouard  8742:   mint=matrix(1,maxwav,1,n);
                   8743:   anint=matrix(1,maxwav,1,n);
1.131     brouard  8744:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  8745:   tab=ivector(1,NCOVMAX);
1.144     brouard  8746:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  8747:   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  8748: 
1.136     brouard  8749:   /* Reads data from file datafile */
                   8750:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8751:     goto end;
                   8752: 
                   8753:   /* Calculation of the number of parameters from char model */
1.137     brouard  8754:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8755:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8756:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8757:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8758:        k=1 Tvar[1]=2 (from V2)
                   8759:     */
                   8760:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8761:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8762:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8763:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8764:   */
                   8765:   /* For model-covariate k tells which data-covariate to use but
                   8766:     because this model-covariate is a construction we invent a new column
                   8767:     ncovcol + k1
                   8768:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8769:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  8770:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  8771:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8772:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8773:   */
1.145     brouard  8774:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8775:   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  8776:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8777:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  8778:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  8779:                         4 covariates (3 plus signs)
                   8780:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8781:                      */  
1.136     brouard  8782: 
1.186     brouard  8783: /* Main decodemodel */
                   8784: 
1.187     brouard  8785: 
1.136     brouard  8786:   if(decodemodel(model, lastobs) == 1)
                   8787:     goto end;
                   8788: 
1.137     brouard  8789:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8790:     nbwarn++;
                   8791:     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); 
                   8792:     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); 
                   8793:   }
1.136     brouard  8794:     /*  if(mle==1){*/
1.137     brouard  8795:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8796:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  8797:   }
                   8798: 
                   8799:     /*-calculation of age at interview from date of interview and age at death -*/
                   8800:   agev=matrix(1,maxwav,1,imx);
                   8801: 
                   8802:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8803:     goto end;
                   8804: 
1.126     brouard  8805: 
1.136     brouard  8806:   agegomp=(int)agemin;
                   8807:   free_vector(moisnais,1,n);
                   8808:   free_vector(annais,1,n);
1.126     brouard  8809:   /* free_matrix(mint,1,maxwav,1,n);
                   8810:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  8811:   /* free_vector(moisdc,1,n); */
                   8812:   /* free_vector(andc,1,n); */
1.145     brouard  8813:   /* */
                   8814:   
1.126     brouard  8815:   wav=ivector(1,imx);
1.214     brouard  8816:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8817:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8818:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8819:   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.*/
                   8820:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8821:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  8822:    
                   8823:   /* Concatenates waves */
1.214     brouard  8824:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8825:      Death is a valid wave (if date is known).
                   8826:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8827:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8828:      and mw[mi+1][i]. dh depends on stepm.
                   8829:   */
                   8830: 
1.126     brouard  8831:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  8832:   /* */
                   8833:  
1.215     brouard  8834:   free_vector(moisdc,1,n);
                   8835:   free_vector(andc,1,n);
                   8836: 
1.126     brouard  8837:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8838:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8839:   ncodemax[1]=1;
1.145     brouard  8840:   Ndum =ivector(-1,NCOVMAX);  
1.220     brouard  8841:        cptcoveff=0;
                   8842:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   8843:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   8844:        }
                   8845:        
                   8846:        ncovcombmax=pow(2,cptcoveff);
                   8847:        invalidvarcomb=ivector(1, ncovcombmax); 
                   8848:        for(i=1;i<ncovcombmax;i++)
                   8849:                invalidvarcomb[i]=0;
                   8850: 
1.211     brouard  8851:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  8852:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  8853:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  8854: 
1.200     brouard  8855:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  8856:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  8857:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  8858:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8859:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   8860:    * (currently 0 or 1) in the data.
                   8861:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   8862:    * corresponding modality (h,j).
                   8863:    */
                   8864: 
1.145     brouard  8865:   h=0;
                   8866:   /*if (cptcovn > 0) */
1.126     brouard  8867:   m=pow(2,cptcoveff);
                   8868:  
1.144     brouard  8869:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  8870:           * For k=4 covariates, h goes from 1 to m=2**k
                   8871:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   8872:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  8873:           *     h\k   1     2     3     4
1.143     brouard  8874:           *______________________________  
                   8875:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   8876:           *     2     2     1     1     1
                   8877:           *     3 i=2 1     2     1     1
                   8878:           *     4     2     2     1     1
                   8879:           *     5 i=3 1 i=2 1     2     1
                   8880:           *     6     2     1     2     1
                   8881:           *     7 i=4 1     2     2     1
                   8882:           *     8     2     2     2     1
1.197     brouard  8883:           *     9 i=5 1 i=3 1 i=2 1     2
                   8884:           *    10     2     1     1     2
                   8885:           *    11 i=6 1     2     1     2
                   8886:           *    12     2     2     1     2
                   8887:           *    13 i=7 1 i=4 1     2     2    
                   8888:           *    14     2     1     2     2
                   8889:           *    15 i=8 1     2     2     2
                   8890:           *    16     2     2     2     2
1.143     brouard  8891:           */
1.212     brouard  8892:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  8893:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   8894:      * and the value of each covariate?
                   8895:      * V1=1, V2=1, V3=2, V4=1 ?
                   8896:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   8897:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   8898:      * In order to get the real value in the data, we use nbcode
                   8899:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   8900:      * We are keeping this crazy system in order to be able (in the future?) 
                   8901:      * to have more than 2 values (0 or 1) for a covariate.
                   8902:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   8903:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   8904:      *              bbbbbbbb
                   8905:      *              76543210     
                   8906:      *   h-1        00000101 (6-1=5)
1.219     brouard  8907:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  8908:      *           &
                   8909:      *     1        00000001 (1)
1.219     brouard  8910:      *              00000000        = 1 & ((h-1) >> (k-1))
                   8911:      *          +1= 00000001 =1 
1.211     brouard  8912:      *
                   8913:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   8914:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   8915:      *    >>k'            11
                   8916:      *          &   00000001
                   8917:      *            = 00000001
                   8918:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   8919:      * Reverse h=6 and m=16?
                   8920:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   8921:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   8922:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   8923:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   8924:      * V3=decodtabm(14,3,2**4)=2
                   8925:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   8926:      *(h-1) >> (j-1)    0011 =13 >> 2
                   8927:      *          &1 000000001
                   8928:      *           = 000000001
                   8929:      *         +1= 000000010 =2
                   8930:      *                  2211
                   8931:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   8932:      *                  V3=2
1.220     brouard  8933:                 * codtabm and decodtabm are identical
1.211     brouard  8934:      */
                   8935: 
1.145     brouard  8936: 
                   8937:  free_ivector(Ndum,-1,NCOVMAX);
                   8938: 
                   8939: 
1.126     brouard  8940:     
1.186     brouard  8941:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  8942:   strcpy(optionfilegnuplot,optionfilefiname);
                   8943:   if(mle==-3)
1.201     brouard  8944:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  8945:   strcat(optionfilegnuplot,".gp");
                   8946: 
                   8947:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   8948:     printf("Problem with file %s",optionfilegnuplot);
                   8949:   }
                   8950:   else{
1.204     brouard  8951:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  8952:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  8953:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   8954:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  8955:   }
                   8956:   /*  fclose(ficgp);*/
1.186     brouard  8957: 
                   8958: 
                   8959:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  8960: 
                   8961:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   8962:   if(mle==-3)
1.201     brouard  8963:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  8964:   strcat(optionfilehtm,".htm");
                   8965:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  8966:     printf("Problem with %s \n",optionfilehtm);
                   8967:     exit(0);
1.126     brouard  8968:   }
                   8969: 
                   8970:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   8971:   strcat(optionfilehtmcov,"-cov.htm");
                   8972:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   8973:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   8974:   }
                   8975:   else{
                   8976:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   8977: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8978: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  8979:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   8980:   }
                   8981: 
1.213     brouard  8982:   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  8983: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   8984: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  8985: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8986: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  8987: \n\
                   8988: <hr  size=\"2\" color=\"#EC5E5E\">\
                   8989:  <ul><li><h4>Parameter files</h4>\n\
                   8990:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   8991:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   8992:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   8993:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   8994:  - Date and time at start: %s</ul>\n",\
                   8995:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   8996:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   8997:          fileres,fileres,\
                   8998:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   8999:   fflush(fichtm);
                   9000: 
                   9001:   strcpy(pathr,path);
                   9002:   strcat(pathr,optionfilefiname);
1.184     brouard  9003: #ifdef WIN32
                   9004:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9005: #else
1.126     brouard  9006:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  9007: #endif
                   9008:          
1.126     brouard  9009:   
1.220     brouard  9010:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9011:                 and for any valid combination of covariates
1.126     brouard  9012:      and prints on file fileres'p'. */
1.220     brouard  9013:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,   \
1.214     brouard  9014:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  9015: 
                   9016:   fprintf(fichtm,"\n");
                   9017:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9018: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9019: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9020:          imx,agemin,agemax,jmin,jmax,jmean);
                   9021:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  9022:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9023:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9024:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9025:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  9026: 
1.126     brouard  9027:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9028:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9029:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9030: 
                   9031:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  9032:   /* For mortality only */
1.126     brouard  9033:   if (mle==-3){
1.136     brouard  9034:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  9035:                for(i=1;i<=NDIM;i++)
                   9036:                        for(j=1;j<=NDIM;j++)
                   9037:                                ximort[i][j]=0.;
1.186     brouard  9038:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  9039:     cens=ivector(1,n);
                   9040:     ageexmed=vector(1,n);
                   9041:     agecens=vector(1,n);
                   9042:     dcwave=ivector(1,n);
                   9043:  
                   9044:     for (i=1; i<=imx; i++){
                   9045:       dcwave[i]=-1;
                   9046:       for (m=firstpass; m<=lastpass; m++)
1.218     brouard  9047:                                if (s[m][i]>nlstate) {
                   9048:                                        dcwave[i]=m;
                   9049:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9050:                                        break;
                   9051:                                }
1.126     brouard  9052:     }
1.218     brouard  9053:                
1.126     brouard  9054:     for (i=1; i<=imx; i++) {
                   9055:       if (wav[i]>0){
1.218     brouard  9056:                                ageexmed[i]=agev[mw[1][i]][i];
                   9057:                                j=wav[i];
                   9058:                                agecens[i]=1.; 
                   9059:                                
                   9060:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   9061:                                        agecens[i]=agev[mw[j][i]][i];
                   9062:                                        cens[i]= 1;
                   9063:                                }else if (ageexmed[i]< 1) 
                   9064:                                        cens[i]= -1;
                   9065:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9066:                                        cens[i]=0 ;
1.126     brouard  9067:       }
                   9068:       else cens[i]=-1;
                   9069:     }
                   9070:     
                   9071:     for (i=1;i<=NDIM;i++) {
                   9072:       for (j=1;j<=NDIM;j++)
1.218     brouard  9073:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  9074:     }
                   9075:     
1.145     brouard  9076:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  9077:     /*printf("%lf %lf", p[1], p[2]);*/
                   9078:     
                   9079:     
1.136     brouard  9080: #ifdef GSL
                   9081:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  9082: #else
1.126     brouard  9083:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  9084: #endif
1.201     brouard  9085:     strcpy(filerespow,"POW-MORT_"); 
                   9086:     strcat(filerespow,fileresu);
1.126     brouard  9087:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9088:       printf("Problem with resultfile: %s\n", filerespow);
                   9089:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9090:     }
1.136     brouard  9091: #ifdef GSL
                   9092:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  9093: #else
1.126     brouard  9094:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  9095: #endif
1.126     brouard  9096:     /*  for (i=1;i<=nlstate;i++)
                   9097:        for(j=1;j<=nlstate+ndeath;j++)
                   9098:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9099:     */
                   9100:     fprintf(ficrespow,"\n");
1.136     brouard  9101: #ifdef GSL
                   9102:     /* gsl starts here */ 
                   9103:     T = gsl_multimin_fminimizer_nmsimplex;
                   9104:     gsl_multimin_fminimizer *sfm = NULL;
                   9105:     gsl_vector *ss, *x;
                   9106:     gsl_multimin_function minex_func;
                   9107: 
                   9108:     /* Initial vertex size vector */
                   9109:     ss = gsl_vector_alloc (NDIM);
                   9110:     
                   9111:     if (ss == NULL){
                   9112:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9113:     }
                   9114:     /* Set all step sizes to 1 */
                   9115:     gsl_vector_set_all (ss, 0.001);
                   9116: 
                   9117:     /* Starting point */
1.126     brouard  9118:     
1.136     brouard  9119:     x = gsl_vector_alloc (NDIM);
                   9120:     
                   9121:     if (x == NULL){
                   9122:       gsl_vector_free(ss);
                   9123:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9124:     }
                   9125:   
                   9126:     /* Initialize method and iterate */
                   9127:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9128:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9129:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9130:     gsl_vector_set(x, 0, p[1]);
                   9131:     gsl_vector_set(x, 1, p[2]);
                   9132: 
                   9133:     minex_func.f = &gompertz_f;
                   9134:     minex_func.n = NDIM;
                   9135:     minex_func.params = (void *)&p; /* ??? */
                   9136:     
                   9137:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9138:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9139:     
                   9140:     printf("Iterations beginning .....\n\n");
                   9141:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9142: 
                   9143:     iteri=0;
                   9144:     while (rval == GSL_CONTINUE){
                   9145:       iteri++;
                   9146:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9147:       
                   9148:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9149:       fflush(0);
                   9150:       
                   9151:       if (status) 
                   9152:         break;
                   9153:       
                   9154:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9155:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9156:       
                   9157:       if (rval == GSL_SUCCESS)
                   9158:         printf ("converged to a local maximum at\n");
                   9159:       
                   9160:       printf("%5d ", iteri);
                   9161:       for (it = 0; it < NDIM; it++){
                   9162:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9163:       }
                   9164:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9165:     }
                   9166:     
                   9167:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9168:     
                   9169:     gsl_vector_free(x); /* initial values */
                   9170:     gsl_vector_free(ss); /* inital step size */
                   9171:     for (it=0; it<NDIM; it++){
                   9172:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9173:       fprintf(ficrespow," %.12lf", p[it]);
                   9174:     }
                   9175:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9176: #endif
                   9177: #ifdef POWELL
                   9178:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9179: #endif  
1.126     brouard  9180:     fclose(ficrespow);
                   9181:     
1.203     brouard  9182:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  9183: 
                   9184:     for(i=1; i <=NDIM; i++)
                   9185:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  9186:                                matcov[i][j]=matcov[j][i];
1.126     brouard  9187:     
                   9188:     printf("\nCovariance matrix\n ");
1.203     brouard  9189:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  9190:     for(i=1; i <=NDIM; i++) {
                   9191:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  9192:                                printf("%f ",matcov[i][j]);
                   9193:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  9194:       }
1.203     brouard  9195:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  9196:     }
                   9197:     
                   9198:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  9199:     for (i=1;i<=NDIM;i++) {
1.126     brouard  9200:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  9201:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9202:     }
1.126     brouard  9203:     lsurv=vector(1,AGESUP);
                   9204:     lpop=vector(1,AGESUP);
                   9205:     tpop=vector(1,AGESUP);
                   9206:     lsurv[agegomp]=100000;
                   9207:     
                   9208:     for (k=agegomp;k<=AGESUP;k++) {
                   9209:       agemortsup=k;
                   9210:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9211:     }
                   9212:     
                   9213:     for (k=agegomp;k<agemortsup;k++)
                   9214:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9215:     
                   9216:     for (k=agegomp;k<agemortsup;k++){
                   9217:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9218:       sumlpop=sumlpop+lpop[k];
                   9219:     }
                   9220:     
                   9221:     tpop[agegomp]=sumlpop;
                   9222:     for (k=agegomp;k<(agemortsup-3);k++){
                   9223:       /*  tpop[k+1]=2;*/
                   9224:       tpop[k+1]=tpop[k]-lpop[k];
                   9225:     }
                   9226:     
                   9227:     
                   9228:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9229:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9230:       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]);
                   9231:     
                   9232:     
                   9233:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  9234:                ageminpar=50;
                   9235:                agemaxpar=100;
1.194     brouard  9236:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9237:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9238: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9239: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9240:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9241: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9242: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9243:     }else{
                   9244:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9245:                        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  9246:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  9247:                }
1.201     brouard  9248:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  9249:                     stepm, weightopt,\
                   9250:                     model,imx,p,matcov,agemortsup);
                   9251:     
                   9252:     free_vector(lsurv,1,AGESUP);
                   9253:     free_vector(lpop,1,AGESUP);
                   9254:     free_vector(tpop,1,AGESUP);
1.220     brouard  9255:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  9256:     free_ivector(cens,1,n);
                   9257:     free_vector(agecens,1,n);
                   9258:     free_ivector(dcwave,1,n);
1.220     brouard  9259: #ifdef GSL
1.136     brouard  9260: #endif
1.186     brouard  9261:   } /* Endof if mle==-3 mortality only */
1.205     brouard  9262:   /* Standard  */
                   9263:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9264:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9265:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  9266:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  9267:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9268:     for (k=1; k<=npar;k++)
                   9269:       printf(" %d %8.5f",k,p[k]);
                   9270:     printf("\n");
1.205     brouard  9271:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9272:       /* mlikeli uses func not funcone */
                   9273:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9274:     }
                   9275:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9276:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9277:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9278:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9279:     }
                   9280:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  9281:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9282:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9283:     for (k=1; k<=npar;k++)
                   9284:       printf(" %d %8.5f",k,p[k]);
                   9285:     printf("\n");
                   9286:     
                   9287:     /*--------- results files --------------*/
1.192     brouard  9288:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  9289:     
                   9290:     
                   9291:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9292:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9293:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9294:     for(i=1,jk=1; i <=nlstate; i++){
                   9295:       for(k=1; k <=(nlstate+ndeath); k++){
1.220     brouard  9296:                                if (k != i) {
                   9297:                                        printf("%d%d ",i,k);
                   9298:                                        fprintf(ficlog,"%d%d ",i,k);
                   9299:                                        fprintf(ficres,"%1d%1d ",i,k);
                   9300:                                        for(j=1; j <=ncovmodel; j++){
                   9301:                                                printf("%12.7f ",p[jk]);
                   9302:                                                fprintf(ficlog,"%12.7f ",p[jk]);
                   9303:                                                fprintf(ficres,"%12.7f ",p[jk]);
                   9304:                                                jk++; 
                   9305:                                        }
                   9306:                                        printf("\n");
                   9307:                                        fprintf(ficlog,"\n");
                   9308:                                        fprintf(ficres,"\n");
                   9309:                                }
1.126     brouard  9310:       }
                   9311:     }
1.203     brouard  9312:     if(mle != 0){
                   9313:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  9314:       ftolhess=ftol; /* Usually correct */
1.203     brouard  9315:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9316:       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");
                   9317:       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");
                   9318:       for(i=1,jk=1; i <=nlstate; i++){
1.220     brouard  9319:                                for(k=1; k <=(nlstate+ndeath); k++){
                   9320:                                        if (k != i) {
                   9321:                                                printf("%d%d ",i,k);
                   9322:                                                fprintf(ficlog,"%d%d ",i,k);
                   9323:                                                for(j=1; j <=ncovmodel; j++){
                   9324:                                                        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]));
                   9325:                                                        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]));
                   9326:                                                        jk++; 
                   9327:                                                }
                   9328:                                                printf("\n");
                   9329:                                                fprintf(ficlog,"\n");
                   9330:                                        }
                   9331:                                }
1.193     brouard  9332:       }
1.203     brouard  9333:     } /* end of hesscov and Wald tests */
1.220     brouard  9334:                
1.203     brouard  9335:     /*  */
1.126     brouard  9336:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9337:     printf("# Scales (for hessian or gradient estimation)\n");
                   9338:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9339:     for(i=1,jk=1; i <=nlstate; i++){
                   9340:       for(j=1; j <=nlstate+ndeath; j++){
1.220     brouard  9341:                                if (j!=i) {
                   9342:                                        fprintf(ficres,"%1d%1d",i,j);
                   9343:                                        printf("%1d%1d",i,j);
                   9344:                                        fprintf(ficlog,"%1d%1d",i,j);
                   9345:                                        for(k=1; k<=ncovmodel;k++){
                   9346:                                                printf(" %.5e",delti[jk]);
                   9347:                                                fprintf(ficlog," %.5e",delti[jk]);
                   9348:                                                fprintf(ficres," %.5e",delti[jk]);
                   9349:                                                jk++;
                   9350:                                        }
                   9351:                                        printf("\n");
                   9352:                                        fprintf(ficlog,"\n");
                   9353:                                        fprintf(ficres,"\n");
                   9354:                                }
1.126     brouard  9355:       }
                   9356:     }
                   9357:     
                   9358:     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  9359:     if(mle >= 1) /* To big for the screen */
1.126     brouard  9360:       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");
                   9361:     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");
                   9362:     /* # 121 Var(a12)\n\ */
                   9363:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9364:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9365:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9366:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9367:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9368:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9369:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9370:     
                   9371:     
                   9372:     /* Just to have a covariance matrix which will be more understandable
                   9373:        even is we still don't want to manage dictionary of variables
                   9374:     */
                   9375:     for(itimes=1;itimes<=2;itimes++){
                   9376:       jj=0;
                   9377:       for(i=1; i <=nlstate; i++){
1.220     brouard  9378:                                for(j=1; j <=nlstate+ndeath; j++){
                   9379:                                        if(j==i) continue;
                   9380:                                        for(k=1; k<=ncovmodel;k++){
                   9381:                                                jj++;
                   9382:                                                ca[0]= k+'a'-1;ca[1]='\0';
                   9383:                                                if(itimes==1){
                   9384:                                                        if(mle>=1)
                   9385:                                                                printf("#%1d%1d%d",i,j,k);
                   9386:                                                        fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9387:                                                        fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9388:                                                }else{
                   9389:                                                        if(mle>=1)
                   9390:                                                                printf("%1d%1d%d",i,j,k);
                   9391:                                                        fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9392:                                                        fprintf(ficres,"%1d%1d%d",i,j,k);
                   9393:                                                }
                   9394:                                                ll=0;
                   9395:                                                for(li=1;li <=nlstate; li++){
                   9396:                                                        for(lj=1;lj <=nlstate+ndeath; lj++){
                   9397:                                                                if(lj==li) continue;
                   9398:                                                                for(lk=1;lk<=ncovmodel;lk++){
                   9399:                                                                        ll++;
                   9400:                                                                        if(ll<=jj){
                   9401:                                                                                cb[0]= lk +'a'-1;cb[1]='\0';
                   9402:                                                                                if(ll<jj){
                   9403:                                                                                        if(itimes==1){
                   9404:                                                                                                if(mle>=1)
                   9405:                                                                                                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9406:                                                                                                fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9407:                                                                                                fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9408:                                                                                        }else{
                   9409:                                                                                                if(mle>=1)
                   9410:                                                                                                        printf(" %.5e",matcov[jj][ll]); 
                   9411:                                                                                                fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9412:                                                                                                fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9413:                                                                                        }
                   9414:                                                                                }else{
                   9415:                                                                                        if(itimes==1){
                   9416:                                                                                                if(mle>=1)
                   9417:                                                                                                        printf(" Var(%s%1d%1d)",ca,i,j);
                   9418:                                                                                                fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9419:                                                                                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9420:                                                                                        }else{
                   9421:                                                                                                if(mle>=1)
                   9422:                                                                                                        printf(" %.7e",matcov[jj][ll]); 
                   9423:                                                                                                fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9424:                                                                                                fprintf(ficres," %.7e",matcov[jj][ll]); 
                   9425:                                                                                        }
                   9426:                                                                                }
                   9427:                                                                        }
                   9428:                                                                } /* end lk */
                   9429:                                                        } /* end lj */
                   9430:                                                } /* end li */
                   9431:                                                if(mle>=1)
                   9432:                                                        printf("\n");
                   9433:                                                fprintf(ficlog,"\n");
                   9434:                                                fprintf(ficres,"\n");
                   9435:                                                numlinepar++;
                   9436:                                        } /* end k*/
                   9437:                                } /*end j */
1.126     brouard  9438:       } /* end i */
                   9439:     } /* end itimes */
                   9440:     
                   9441:     fflush(ficlog);
                   9442:     fflush(ficres);
1.220     brouard  9443:                while(fgets(line, MAXLINE, ficpar)) {
                   9444:                        /* If line starts with a # it is a comment */
                   9445:                        if (line[0] == '#') {
                   9446:                                numlinepar++;
                   9447:                                fputs(line,stdout);
                   9448:                                fputs(line,ficparo);
                   9449:                                fputs(line,ficlog);
                   9450:                                continue;
                   9451:                        }else
                   9452:                                break;
                   9453:                }
                   9454:                
1.209     brouard  9455:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9456:     /*   ungetc(c,ficpar); */
                   9457:     /*   fgets(line, MAXLINE, ficpar); */
                   9458:     /*   fputs(line,stdout); */
                   9459:     /*   fputs(line,ficparo); */
                   9460:     /* } */
                   9461:     /* ungetc(c,ficpar); */
1.126     brouard  9462:     
                   9463:     estepm=0;
1.209     brouard  9464:     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.220     brouard  9465:                        
                   9466:                        if (num_filled != 6) {
                   9467:                                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);
                   9468:                                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);
                   9469:                                goto end;
                   9470:                        }
                   9471:                        printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9472:                }
                   9473:                /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9474:                /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9475:                
1.209     brouard  9476:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9477:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9478:     if (fage <= 2) {
                   9479:       bage = ageminpar;
                   9480:       fage = agemaxpar;
                   9481:     }
                   9482:     
                   9483:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9484:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9485:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  9486:                
1.186     brouard  9487:     /* Other stuffs, more or less useful */    
1.126     brouard  9488:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9489:       ungetc(c,ficpar);
                   9490:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9491:       fputs(line,stdout);
1.126     brouard  9492:       fputs(line,ficparo);
                   9493:     }
                   9494:     ungetc(c,ficpar);
                   9495:     
                   9496:     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);
                   9497:     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);
                   9498:     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);
                   9499:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9500:     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);
                   9501:     
                   9502:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9503:       ungetc(c,ficpar);
                   9504:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9505:       fputs(line,stdout);
1.126     brouard  9506:       fputs(line,ficparo);
                   9507:     }
                   9508:     ungetc(c,ficpar);
                   9509:     
                   9510:     
                   9511:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9512:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9513:     
                   9514:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9515:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9516:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9517:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9518:     
                   9519:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9520:       ungetc(c,ficpar);
                   9521:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9522:       fputs(line,stdout);
1.126     brouard  9523:       fputs(line,ficparo);
                   9524:     }
                   9525:     ungetc(c,ficpar);
                   9526:     
                   9527:     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);
                   9528:     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);
                   9529:     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);
                   9530:     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);
                   9531:     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);
                   9532:     /* day and month of proj2 are not used but only year anproj2.*/
                   9533:     
1.217     brouard  9534:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9535:       ungetc(c,ficpar);
                   9536:       fgets(line, MAXLINE, ficpar);
                   9537:       fputs(line,stdout);
                   9538:       fputs(line,ficparo);
                   9539:     }
                   9540:     ungetc(c,ficpar);
                   9541:     
                   9542:     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.219     brouard  9543:     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);
                   9544:     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);
                   9545:     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  9546:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9547:     
                   9548:     
1.220     brouard  9549:                /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  9550:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9551:     
                   9552:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9553:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.220     brouard  9554:                        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9555: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9556: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9557:                        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9558: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9559: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9560:     }else{
1.218     brouard  9561:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  9562:     }
                   9563:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   9564:                                                                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   9565:                                                                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                   9566:                
                   9567:                /*------------ free_vector  -------------*/
                   9568:                /*  chdir(path); */
                   9569:                
1.215     brouard  9570:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9571:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9572:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9573:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9574:     free_lvector(num,1,n);
                   9575:     free_vector(agedc,1,n);
                   9576:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9577:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9578:     fclose(ficparo);
                   9579:     fclose(ficres);
1.220     brouard  9580:                
                   9581:                
1.186     brouard  9582:     /* Other results (useful)*/
1.220     brouard  9583:                
                   9584:                
1.126     brouard  9585:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9586:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9587:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9588:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9589:     fclose(ficrespl);
                   9590: 
                   9591:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9592:     /*#include "hpijx.h"*/
                   9593:     hPijx(p, bage, fage);
1.145     brouard  9594:     fclose(ficrespij);
1.126     brouard  9595: 
1.220     brouard  9596:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  9597:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  9598:     k=1;
1.126     brouard  9599:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9600: 
1.219     brouard  9601:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  9602:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9603:     for(i=1;i<=AGESUP;i++)
1.219     brouard  9604:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.218     brouard  9605:                                for(k=1;k<=ncovcombmax;k++)
                   9606:                                        probs[i][j][k]=0.;
1.219     brouard  9607:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9608:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   9609:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9610:                        for(i=1;i<=AGESUP;i++)
                   9611:                                for(j=1;j<=nlstate;j++)
                   9612:                                        for(k=1;k<=ncovcombmax;k++)
                   9613:                                                mobaverages[i][j][k]=0.;
                   9614:       mobaverage=mobaverages;
                   9615:       if (mobilav!=0) {
1.218     brouard  9616:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9617:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9618:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9619:                                }
1.219     brouard  9620:       }
                   9621:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   9622:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9623:       else if (mobilavproj !=0) {
1.218     brouard  9624:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9625:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9626:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9627:                                }
1.219     brouard  9628:       }
                   9629:     }/* end if moving average */
                   9630:                
1.126     brouard  9631:     /*---------- Forecasting ------------------*/
                   9632:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9633:     if(prevfcast==1){
                   9634:       /*    if(stepm ==1){*/
1.201     brouard  9635:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  9636:     }
1.217     brouard  9637:     if(backcast==1){
1.219     brouard  9638:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9639:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9640:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   9641: 
                   9642:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9643: 
                   9644:       bprlim=matrix(1,nlstate,1,nlstate);
                   9645:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   9646:       fclose(ficresplb);
                   9647: 
1.220     brouard  9648:       /* hBijx(p, bage, fage, mobaverage); */
                   9649:       /* fclose(ficrespijb); */
1.219     brouard  9650:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9651: 
                   9652:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
                   9653:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   9654:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9655:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9656:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9657:     }
1.217     brouard  9658:     
1.186     brouard  9659:  
                   9660:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9661: 
1.215     brouard  9662:     free_ivector(wav,1,imx);
                   9663:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9664:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9665:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  9666:                
                   9667:                
1.127     brouard  9668:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  9669:                
1.201     brouard  9670:     strcpy(filerese,"E_");
                   9671:     strcat(filerese,fileresu);
1.126     brouard  9672:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9673:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9674:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9675:     }
1.208     brouard  9676:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9677:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  9678:                
1.145     brouard  9679:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.219     brouard  9680:       fprintf(ficreseij,"\n#****** ");
                   9681:       for(j=1;j<=cptcoveff;j++) {
1.220     brouard  9682:                                fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  9683:       }
                   9684:       fprintf(ficreseij,"******\n");
                   9685:       
                   9686:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9687:       oldm=oldms;savm=savms;
                   9688:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  9689:       
1.219     brouard  9690:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  9691:     }
                   9692:     fclose(ficreseij);
1.208     brouard  9693:     printf("done evsij\n");fflush(stdout);
                   9694:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  9695:                
1.127     brouard  9696:     /*---------- Health expectancies and variances ------------*/
1.218     brouard  9697:                
                   9698:                
1.201     brouard  9699:     strcpy(filerest,"T_");
                   9700:     strcat(filerest,fileresu);
1.127     brouard  9701:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9702:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9703:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9704:     }
1.208     brouard  9705:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9706:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  9707:                
1.126     brouard  9708: 
1.201     brouard  9709:     strcpy(fileresstde,"STDE_");
                   9710:     strcat(fileresstde,fileresu);
1.126     brouard  9711:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9712:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9713:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9714:     }
1.208     brouard  9715:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9716:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  9717: 
1.201     brouard  9718:     strcpy(filerescve,"CVE_");
                   9719:     strcat(filerescve,fileresu);
1.126     brouard  9720:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9721:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9722:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9723:     }
1.208     brouard  9724:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9725:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  9726: 
1.201     brouard  9727:     strcpy(fileresv,"V_");
                   9728:     strcat(fileresv,fileresu);
1.126     brouard  9729:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9730:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9731:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9732:     }
1.208     brouard  9733:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9734:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  9735: 
1.145     brouard  9736:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9737:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9738:           
                   9739:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  9740:       fprintf(ficrest,"\n#****** ");
                   9741:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9742:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9743:       fprintf(ficrest,"******\n");
                   9744:       
                   9745:       fprintf(ficresstdeij,"\n#****** ");
                   9746:       fprintf(ficrescveij,"\n#****** ");
                   9747:       for(j=1;j<=cptcoveff;j++) {
1.218     brouard  9748:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9749:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9750:       }
                   9751:       fprintf(ficresstdeij,"******\n");
                   9752:       fprintf(ficrescveij,"******\n");
                   9753:       
                   9754:       fprintf(ficresvij,"\n#****** ");
                   9755:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9756:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9757:       fprintf(ficresvij,"******\n");
                   9758:       
                   9759:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9760:       oldm=oldms;savm=savms;
                   9761:       printf(" cvevsij %d, ",k);
                   9762:       fprintf(ficlog, " cvevsij %d, ",k);
                   9763:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9764:       printf(" end cvevsij \n ");
                   9765:       fprintf(ficlog, " end cvevsij \n ");
                   9766:       
                   9767:       /*
                   9768:        */
                   9769:       /* goto endfree; */
                   9770:       
                   9771:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9772:       pstamp(ficrest);
                   9773:       
                   9774:       
                   9775:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.220     brouard  9776:                                oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   9777:                                cptcod= 0; /* To be deleted */
                   9778:                                printf("varevsij %d \n",vpopbased);
                   9779:                                fprintf(ficlog, "varevsij %d \n",vpopbased);
                   9780:                                varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
                   9781:                                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 ");
                   9782:                                if(vpopbased==1)
                   9783:                                        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);
                   9784:                                else
                   9785:                                        fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   9786:                                fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   9787:                                for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   9788:                                fprintf(ficrest,"\n");
                   9789:                                /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   9790:                                epj=vector(1,nlstate+1);
                   9791:                                printf("Computing age specific period (stable) prevalences in each health state \n");
                   9792:                                fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   9793:                                for(age=bage; age <=fage ;age++){
                   9794:                                        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   9795:                                        if (vpopbased==1) {
                   9796:                                                if(mobilav ==0){
                   9797:                                                        for(i=1; i<=nlstate;i++)
                   9798:                                                                prlim[i][i]=probs[(int)age][i][k];
                   9799:                                                }else{ /* mobilav */ 
                   9800:                                                        for(i=1; i<=nlstate;i++)
                   9801:                                                                prlim[i][i]=mobaverage[(int)age][i][k];
                   9802:                                                }
                   9803:                                        }
1.219     brouard  9804:          
1.220     brouard  9805:                                        fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   9806:                                        /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   9807:                                        /* printf(" age %4.0f ",age); */
                   9808:                                        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   9809:                                                for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   9810:                                                        epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   9811:                                                        /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   9812:                                                        /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   9813:                                                }
                   9814:                                                epj[nlstate+1] +=epj[j];
                   9815:                                        }
                   9816:                                        /* printf(" age %4.0f \n",age); */
1.219     brouard  9817:          
1.220     brouard  9818:                                        for(i=1, vepp=0.;i <=nlstate;i++)
                   9819:                                                for(j=1;j <=nlstate;j++)
                   9820:                                                        vepp += vareij[i][j][(int)age];
                   9821:                                        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   9822:                                        for(j=1;j <=nlstate;j++){
                   9823:                                                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   9824:                                        }
                   9825:                                        fprintf(ficrest,"\n");
                   9826:                                }
1.208     brouard  9827:       } /* End vpopbased */
                   9828:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9829:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9830:       free_vector(epj,1,nlstate+1);
                   9831:       printf("done \n");fflush(stdout);
                   9832:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9833:       
1.145     brouard  9834:       /*}*/
1.208     brouard  9835:     } /* End k */
1.126     brouard  9836:     free_vector(weight,1,n);
1.145     brouard  9837:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  9838:     free_imatrix(s,1,maxwav+1,1,n);
                   9839:     free_matrix(anint,1,maxwav,1,n); 
                   9840:     free_matrix(mint,1,maxwav,1,n);
                   9841:     free_ivector(cod,1,n);
                   9842:     free_ivector(tab,1,NCOVMAX);
                   9843:     fclose(ficresstdeij);
                   9844:     fclose(ficrescveij);
                   9845:     fclose(ficresvij);
                   9846:     fclose(ficrest);
1.208     brouard  9847:     printf("done Health expectancies\n");fflush(stdout);
                   9848:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  9849:     fclose(ficpar);
                   9850:   
                   9851:     /*------- Variance of period (stable) prevalence------*/   
                   9852: 
1.201     brouard  9853:     strcpy(fileresvpl,"VPL_");
                   9854:     strcat(fileresvpl,fileresu);
1.126     brouard  9855:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9856:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9857:       exit(0);
                   9858:     }
1.208     brouard  9859:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9860:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  9861: 
1.145     brouard  9862:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9863:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9864:           
                   9865:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9866:        fprintf(ficresvpl,"\n#****** ");
1.218     brouard  9867:                        for(j=1;j<=cptcoveff;j++) 
                   9868:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9869:                        fprintf(ficresvpl,"******\n");
                   9870:       
                   9871:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9872:                        oldm=oldms;savm=savms;
                   9873:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   9874:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  9875:       /*}*/
1.126     brouard  9876:     }
1.218     brouard  9877:                
1.126     brouard  9878:     fclose(ficresvpl);
1.208     brouard  9879:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   9880:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  9881: 
                   9882:     /*---------- End : free ----------------*/
1.219     brouard  9883:     if (mobilav!=0 ||mobilavproj !=0)
                   9884:       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  9885:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  9886:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9887:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  9888:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  9889:  /* endfree:*/
1.126     brouard  9890:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9891:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9892:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9893:     free_matrix(covar,0,NCOVMAX,1,n);
                   9894:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  9895:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  9896:     /*free_vector(delti,1,npar);*/
                   9897:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9898:     free_matrix(agev,1,maxwav,1,imx);
                   9899:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   9900: 
1.145     brouard  9901:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  9902:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  9903:     free_ivector(Tvar,1,NCOVMAX);
                   9904:     free_ivector(Tprod,1,NCOVMAX);
                   9905:     free_ivector(Tvaraff,1,NCOVMAX);
1.220     brouard  9906:     free_ivector(invalidvarcomb,1,ncovcombmax);
1.145     brouard  9907:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  9908: 
                   9909:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  9910:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  9911:   fflush(fichtm);
                   9912:   fflush(ficgp);
                   9913:   
                   9914: 
                   9915:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  9916:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   9917:     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  9918:   }else{
                   9919:     printf("End of Imach\n");
                   9920:     fprintf(ficlog,"End of Imach\n");
                   9921:   }
                   9922:   printf("See log file on %s\n",filelog);
                   9923:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  9924:   /*(void) gettimeofday(&end_time,&tzp);*/
                   9925:   rend_time = time(NULL);  
                   9926:   end_time = *localtime(&rend_time);
                   9927:   /* tml = *localtime(&end_time.tm_sec); */
                   9928:   strcpy(strtend,asctime(&end_time));
1.126     brouard  9929:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   9930:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  9931:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  9932: 
1.157     brouard  9933:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   9934:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   9935:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  9936:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   9937: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   9938:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9939:   fclose(fichtm);
                   9940:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9941:   fclose(fichtmcov);
                   9942:   fclose(ficgp);
                   9943:   fclose(ficlog);
                   9944:   /*------ End -----------*/
                   9945: 
                   9946: 
                   9947:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  9948: #ifdef WIN32
                   9949:    if (_chdir(pathcd) != 0)
                   9950:           printf("Can't move to directory %s!\n",path);
                   9951:    if(_getcwd(pathcd,MAXLINE) > 0)
                   9952: #else
1.126     brouard  9953:    if(chdir(pathcd) != 0)
1.184     brouard  9954:           printf("Can't move to directory %s!\n", path);
                   9955:    if (getcwd(pathcd, MAXLINE) > 0)
                   9956: #endif 
1.126     brouard  9957:     printf("Current directory %s!\n",pathcd);
                   9958:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   9959:   sprintf(plotcmd,"gnuplot");
1.157     brouard  9960: #ifdef _WIN32
1.126     brouard  9961:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   9962: #endif
                   9963:   if(!stat(plotcmd,&info)){
1.158     brouard  9964:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9965:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  9966:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  9967:     }else
                   9968:       strcpy(pplotcmd,plotcmd);
1.157     brouard  9969: #ifdef __unix
1.126     brouard  9970:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   9971:     if(!stat(plotcmd,&info)){
1.158     brouard  9972:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9973:     }else
                   9974:       strcpy(pplotcmd,plotcmd);
                   9975: #endif
                   9976:   }else
                   9977:     strcpy(pplotcmd,plotcmd);
                   9978:   
                   9979:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  9980:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9981: 
                   9982:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  9983:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  9984:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  9985:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  9986:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  9987:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  9988:   }
1.158     brouard  9989:   printf(" Successful, please wait...");
1.126     brouard  9990:   while (z[0] != 'q') {
                   9991:     /* chdir(path); */
1.154     brouard  9992:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  9993:     scanf("%s",z);
                   9994: /*     if (z[0] == 'c') system("./imach"); */
                   9995:     if (z[0] == 'e') {
1.158     brouard  9996: #ifdef __APPLE__
1.152     brouard  9997:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  9998: #elif __linux
                   9999:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  10000: #else
1.152     brouard  10001:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  10002: #endif
                   10003:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10004:       system(pplotcmd);
1.126     brouard  10005:     }
                   10006:     else if (z[0] == 'g') system(plotcmd);
                   10007:     else if (z[0] == 'q') exit(0);
                   10008:   }
                   10009:   end:
                   10010:   while (z[0] != 'q') {
1.195     brouard  10011:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  10012:     scanf("%s",z);
                   10013:   }
                   10014: }

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