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

1.214   ! brouard     1: /* $Id: imach.c,v 1.213 2015/12/11 18:22:17 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.214   ! brouard     4:   Revision 1.213  2015/12/11 18:22:17  brouard
        !             5:   Summary: 0.98r4
        !             6: 
1.213     brouard     7:   Revision 1.212  2015/11/21 12:47:24  brouard
                      8:   Summary: minor typo
                      9: 
1.212     brouard    10:   Revision 1.211  2015/11/21 12:41:11  brouard
                     11:   Summary: 0.98r3 with some graph of projected cross-sectional
                     12: 
                     13:   Author: Nicolas Brouard
                     14: 
1.211     brouard    15:   Revision 1.210  2015/11/18 17:41:20  brouard
                     16:   Summary: Start working on projected prevalences
                     17: 
1.210     brouard    18:   Revision 1.209  2015/11/17 22:12:03  brouard
                     19:   Summary: Adding ftolpl parameter
                     20:   Author: N Brouard
                     21: 
                     22:   We had difficulties to get smoothed confidence intervals. It was due
                     23:   to the period prevalence which wasn't computed accurately. The inner
                     24:   parameter ftolpl is now an outer parameter of the .imach parameter
                     25:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     26:   computation are long.
                     27: 
1.209     brouard    28:   Revision 1.208  2015/11/17 14:31:57  brouard
                     29:   Summary: temporary
                     30: 
1.208     brouard    31:   Revision 1.207  2015/10/27 17:36:57  brouard
                     32:   *** empty log message ***
                     33: 
1.207     brouard    34:   Revision 1.206  2015/10/24 07:14:11  brouard
                     35:   *** empty log message ***
                     36: 
1.206     brouard    37:   Revision 1.205  2015/10/23 15:50:53  brouard
                     38:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     39: 
1.205     brouard    40:   Revision 1.204  2015/10/01 16:20:26  brouard
                     41:   Summary: Some new graphs of contribution to likelihood
                     42: 
1.204     brouard    43:   Revision 1.203  2015/09/30 17:45:14  brouard
                     44:   Summary: looking at better estimation of the hessian
                     45: 
                     46:   Also a better criteria for convergence to the period prevalence And
                     47:   therefore adding the number of years needed to converge. (The
                     48:   prevalence in any alive state shold sum to one
                     49: 
1.203     brouard    50:   Revision 1.202  2015/09/22 19:45:16  brouard
                     51:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     52: 
1.202     brouard    53:   Revision 1.201  2015/09/15 17:34:58  brouard
                     54:   Summary: 0.98r0
                     55: 
                     56:   - Some new graphs like suvival functions
                     57:   - Some bugs fixed like model=1+age+V2.
                     58: 
1.201     brouard    59:   Revision 1.200  2015/09/09 16:53:55  brouard
                     60:   Summary: Big bug thanks to Flavia
                     61: 
                     62:   Even model=1+age+V2. did not work anymore
                     63: 
1.200     brouard    64:   Revision 1.199  2015/09/07 14:09:23  brouard
                     65:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     66: 
1.199     brouard    67:   Revision 1.198  2015/09/03 07:14:39  brouard
                     68:   Summary: 0.98q5 Flavia
                     69: 
1.198     brouard    70:   Revision 1.197  2015/09/01 18:24:39  brouard
                     71:   *** empty log message ***
                     72: 
1.197     brouard    73:   Revision 1.196  2015/08/18 23:17:52  brouard
                     74:   Summary: 0.98q5
                     75: 
1.196     brouard    76:   Revision 1.195  2015/08/18 16:28:39  brouard
                     77:   Summary: Adding a hack for testing purpose
                     78: 
                     79:   After reading the title, ftol and model lines, if the comment line has
                     80:   a q, starting with #q, the answer at the end of the run is quit. It
                     81:   permits to run test files in batch with ctest. The former workaround was
                     82:   $ echo q | imach foo.imach
                     83: 
1.195     brouard    84:   Revision 1.194  2015/08/18 13:32:00  brouard
                     85:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     86: 
1.194     brouard    87:   Revision 1.193  2015/08/04 07:17:42  brouard
                     88:   Summary: 0.98q4
                     89: 
1.193     brouard    90:   Revision 1.192  2015/07/16 16:49:02  brouard
                     91:   Summary: Fixing some outputs
                     92: 
1.192     brouard    93:   Revision 1.191  2015/07/14 10:00:33  brouard
                     94:   Summary: Some fixes
                     95: 
1.191     brouard    96:   Revision 1.190  2015/05/05 08:51:13  brouard
                     97:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     98: 
                     99:   Fix 1+age+.
                    100: 
1.190     brouard   101:   Revision 1.189  2015/04/30 14:45:16  brouard
                    102:   Summary: 0.98q2
                    103: 
1.189     brouard   104:   Revision 1.188  2015/04/30 08:27:53  brouard
                    105:   *** empty log message ***
                    106: 
1.188     brouard   107:   Revision 1.187  2015/04/29 09:11:15  brouard
                    108:   *** empty log message ***
                    109: 
1.187     brouard   110:   Revision 1.186  2015/04/23 12:01:52  brouard
                    111:   Summary: V1*age is working now, version 0.98q1
                    112: 
                    113:   Some codes had been disabled in order to simplify and Vn*age was
                    114:   working in the optimization phase, ie, giving correct MLE parameters,
                    115:   but, as usual, outputs were not correct and program core dumped.
                    116: 
1.186     brouard   117:   Revision 1.185  2015/03/11 13:26:42  brouard
                    118:   Summary: Inclusion of compile and links command line for Intel Compiler
                    119: 
1.185     brouard   120:   Revision 1.184  2015/03/11 11:52:39  brouard
                    121:   Summary: Back from Windows 8. Intel Compiler
                    122: 
1.184     brouard   123:   Revision 1.183  2015/03/10 20:34:32  brouard
                    124:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    125: 
                    126:   We use directest instead of original Powell test; probably no
                    127:   incidence on the results, but better justifications;
                    128:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    129:   wrong results.
                    130: 
1.183     brouard   131:   Revision 1.182  2015/02/12 08:19:57  brouard
                    132:   Summary: Trying to keep directest which seems simpler and more general
                    133:   Author: Nicolas Brouard
                    134: 
1.182     brouard   135:   Revision 1.181  2015/02/11 23:22:24  brouard
                    136:   Summary: Comments on Powell added
                    137: 
                    138:   Author:
                    139: 
1.181     brouard   140:   Revision 1.180  2015/02/11 17:33:45  brouard
                    141:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    142: 
1.180     brouard   143:   Revision 1.179  2015/01/04 09:57:06  brouard
                    144:   Summary: back to OS/X
                    145: 
1.179     brouard   146:   Revision 1.178  2015/01/04 09:35:48  brouard
                    147:   *** empty log message ***
                    148: 
1.178     brouard   149:   Revision 1.177  2015/01/03 18:40:56  brouard
                    150:   Summary: Still testing ilc32 on OSX
                    151: 
1.177     brouard   152:   Revision 1.176  2015/01/03 16:45:04  brouard
                    153:   *** empty log message ***
                    154: 
1.176     brouard   155:   Revision 1.175  2015/01/03 16:33:42  brouard
                    156:   *** empty log message ***
                    157: 
1.175     brouard   158:   Revision 1.174  2015/01/03 16:15:49  brouard
                    159:   Summary: Still in cross-compilation
                    160: 
1.174     brouard   161:   Revision 1.173  2015/01/03 12:06:26  brouard
                    162:   Summary: trying to detect cross-compilation
                    163: 
1.173     brouard   164:   Revision 1.172  2014/12/27 12:07:47  brouard
                    165:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    166: 
1.172     brouard   167:   Revision 1.171  2014/12/23 13:26:59  brouard
                    168:   Summary: Back from Visual C
                    169: 
                    170:   Still problem with utsname.h on Windows
                    171: 
1.171     brouard   172:   Revision 1.170  2014/12/23 11:17:12  brouard
                    173:   Summary: Cleaning some \%% back to %%
                    174: 
                    175:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    176: 
1.170     brouard   177:   Revision 1.169  2014/12/22 23:08:31  brouard
                    178:   Summary: 0.98p
                    179: 
                    180:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    181: 
1.169     brouard   182:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   183:   Summary: update
1.169     brouard   184: 
1.168     brouard   185:   Revision 1.167  2014/12/22 13:50:56  brouard
                    186:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    187: 
                    188:   Testing on Linux 64
                    189: 
1.167     brouard   190:   Revision 1.166  2014/12/22 11:40:47  brouard
                    191:   *** empty log message ***
                    192: 
1.166     brouard   193:   Revision 1.165  2014/12/16 11:20:36  brouard
                    194:   Summary: After compiling on Visual C
                    195: 
                    196:   * imach.c (Module): Merging 1.61 to 1.162
                    197: 
1.165     brouard   198:   Revision 1.164  2014/12/16 10:52:11  brouard
                    199:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    200: 
                    201:   * imach.c (Module): Merging 1.61 to 1.162
                    202: 
1.164     brouard   203:   Revision 1.163  2014/12/16 10:30:11  brouard
                    204:   * imach.c (Module): Merging 1.61 to 1.162
                    205: 
1.163     brouard   206:   Revision 1.162  2014/09/25 11:43:39  brouard
                    207:   Summary: temporary backup 0.99!
                    208: 
1.162     brouard   209:   Revision 1.1  2014/09/16 11:06:58  brouard
                    210:   Summary: With some code (wrong) for nlopt
                    211: 
                    212:   Author:
                    213: 
                    214:   Revision 1.161  2014/09/15 20:41:41  brouard
                    215:   Summary: Problem with macro SQR on Intel compiler
                    216: 
1.161     brouard   217:   Revision 1.160  2014/09/02 09:24:05  brouard
                    218:   *** empty log message ***
                    219: 
1.160     brouard   220:   Revision 1.159  2014/09/01 10:34:10  brouard
                    221:   Summary: WIN32
                    222:   Author: Brouard
                    223: 
1.159     brouard   224:   Revision 1.158  2014/08/27 17:11:51  brouard
                    225:   *** empty log message ***
                    226: 
1.158     brouard   227:   Revision 1.157  2014/08/27 16:26:55  brouard
                    228:   Summary: Preparing windows Visual studio version
                    229:   Author: Brouard
                    230: 
                    231:   In order to compile on Visual studio, time.h is now correct and time_t
                    232:   and tm struct should be used. difftime should be used but sometimes I
                    233:   just make the differences in raw time format (time(&now).
                    234:   Trying to suppress #ifdef LINUX
                    235:   Add xdg-open for __linux in order to open default browser.
                    236: 
1.157     brouard   237:   Revision 1.156  2014/08/25 20:10:10  brouard
                    238:   *** empty log message ***
                    239: 
1.156     brouard   240:   Revision 1.155  2014/08/25 18:32:34  brouard
                    241:   Summary: New compile, minor changes
                    242:   Author: Brouard
                    243: 
1.155     brouard   244:   Revision 1.154  2014/06/20 17:32:08  brouard
                    245:   Summary: Outputs now all graphs of convergence to period prevalence
                    246: 
1.154     brouard   247:   Revision 1.153  2014/06/20 16:45:46  brouard
                    248:   Summary: If 3 live state, convergence to period prevalence on same graph
                    249:   Author: Brouard
                    250: 
1.153     brouard   251:   Revision 1.152  2014/06/18 17:54:09  brouard
                    252:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    253: 
1.152     brouard   254:   Revision 1.151  2014/06/18 16:43:30  brouard
                    255:   *** empty log message ***
                    256: 
1.151     brouard   257:   Revision 1.150  2014/06/18 16:42:35  brouard
                    258:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    259:   Author: brouard
                    260: 
1.150     brouard   261:   Revision 1.149  2014/06/18 15:51:14  brouard
                    262:   Summary: Some fixes in parameter files errors
                    263:   Author: Nicolas Brouard
                    264: 
1.149     brouard   265:   Revision 1.148  2014/06/17 17:38:48  brouard
                    266:   Summary: Nothing new
                    267:   Author: Brouard
                    268: 
                    269:   Just a new packaging for OS/X version 0.98nS
                    270: 
1.148     brouard   271:   Revision 1.147  2014/06/16 10:33:11  brouard
                    272:   *** empty log message ***
                    273: 
1.147     brouard   274:   Revision 1.146  2014/06/16 10:20:28  brouard
                    275:   Summary: Merge
                    276:   Author: Brouard
                    277: 
                    278:   Merge, before building revised version.
                    279: 
1.146     brouard   280:   Revision 1.145  2014/06/10 21:23:15  brouard
                    281:   Summary: Debugging with valgrind
                    282:   Author: Nicolas Brouard
                    283: 
                    284:   Lot of changes in order to output the results with some covariates
                    285:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    286:   improve the code.
                    287:   No more memory valgrind error but a lot has to be done in order to
                    288:   continue the work of splitting the code into subroutines.
                    289:   Also, decodemodel has been improved. Tricode is still not
                    290:   optimal. nbcode should be improved. Documentation has been added in
                    291:   the source code.
                    292: 
1.144     brouard   293:   Revision 1.143  2014/01/26 09:45:38  brouard
                    294:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    295: 
                    296:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    297:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    298: 
1.143     brouard   299:   Revision 1.142  2014/01/26 03:57:36  brouard
                    300:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    301: 
                    302:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    303: 
1.142     brouard   304:   Revision 1.141  2014/01/26 02:42:01  brouard
                    305:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    306: 
1.141     brouard   307:   Revision 1.140  2011/09/02 10:37:54  brouard
                    308:   Summary: times.h is ok with mingw32 now.
                    309: 
1.140     brouard   310:   Revision 1.139  2010/06/14 07:50:17  brouard
                    311:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    312:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    313: 
1.139     brouard   314:   Revision 1.138  2010/04/30 18:19:40  brouard
                    315:   *** empty log message ***
                    316: 
1.138     brouard   317:   Revision 1.137  2010/04/29 18:11:38  brouard
                    318:   (Module): Checking covariates for more complex models
                    319:   than V1+V2. A lot of change to be done. Unstable.
                    320: 
1.137     brouard   321:   Revision 1.136  2010/04/26 20:30:53  brouard
                    322:   (Module): merging some libgsl code. Fixing computation
                    323:   of likelione (using inter/intrapolation if mle = 0) in order to
                    324:   get same likelihood as if mle=1.
                    325:   Some cleaning of code and comments added.
                    326: 
1.136     brouard   327:   Revision 1.135  2009/10/29 15:33:14  brouard
                    328:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    329: 
1.135     brouard   330:   Revision 1.134  2009/10/29 13:18:53  brouard
                    331:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    332: 
1.134     brouard   333:   Revision 1.133  2009/07/06 10:21:25  brouard
                    334:   just nforces
                    335: 
1.133     brouard   336:   Revision 1.132  2009/07/06 08:22:05  brouard
                    337:   Many tings
                    338: 
1.132     brouard   339:   Revision 1.131  2009/06/20 16:22:47  brouard
                    340:   Some dimensions resccaled
                    341: 
1.131     brouard   342:   Revision 1.130  2009/05/26 06:44:34  brouard
                    343:   (Module): Max Covariate is now set to 20 instead of 8. A
                    344:   lot of cleaning with variables initialized to 0. Trying to make
                    345:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    346: 
1.130     brouard   347:   Revision 1.129  2007/08/31 13:49:27  lievre
                    348:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    349: 
1.129     lievre    350:   Revision 1.128  2006/06/30 13:02:05  brouard
                    351:   (Module): Clarifications on computing e.j
                    352: 
1.128     brouard   353:   Revision 1.127  2006/04/28 18:11:50  brouard
                    354:   (Module): Yes the sum of survivors was wrong since
                    355:   imach-114 because nhstepm was no more computed in the age
                    356:   loop. Now we define nhstepma in the age loop.
                    357:   (Module): In order to speed up (in case of numerous covariates) we
                    358:   compute health expectancies (without variances) in a first step
                    359:   and then all the health expectancies with variances or standard
                    360:   deviation (needs data from the Hessian matrices) which slows the
                    361:   computation.
                    362:   In the future we should be able to stop the program is only health
                    363:   expectancies and graph are needed without standard deviations.
                    364: 
1.127     brouard   365:   Revision 1.126  2006/04/28 17:23:28  brouard
                    366:   (Module): Yes the sum of survivors was wrong since
                    367:   imach-114 because nhstepm was no more computed in the age
                    368:   loop. Now we define nhstepma in the age loop.
                    369:   Version 0.98h
                    370: 
1.126     brouard   371:   Revision 1.125  2006/04/04 15:20:31  lievre
                    372:   Errors in calculation of health expectancies. Age was not initialized.
                    373:   Forecasting file added.
                    374: 
                    375:   Revision 1.124  2006/03/22 17:13:53  lievre
                    376:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    377:   The log-likelihood is printed in the log file
                    378: 
                    379:   Revision 1.123  2006/03/20 10:52:43  brouard
                    380:   * imach.c (Module): <title> changed, corresponds to .htm file
                    381:   name. <head> headers where missing.
                    382: 
                    383:   * imach.c (Module): Weights can have a decimal point as for
                    384:   English (a comma might work with a correct LC_NUMERIC environment,
                    385:   otherwise the weight is truncated).
                    386:   Modification of warning when the covariates values are not 0 or
                    387:   1.
                    388:   Version 0.98g
                    389: 
                    390:   Revision 1.122  2006/03/20 09:45:41  brouard
                    391:   (Module): Weights can have a decimal point as for
                    392:   English (a comma might work with a correct LC_NUMERIC environment,
                    393:   otherwise the weight is truncated).
                    394:   Modification of warning when the covariates values are not 0 or
                    395:   1.
                    396:   Version 0.98g
                    397: 
                    398:   Revision 1.121  2006/03/16 17:45:01  lievre
                    399:   * imach.c (Module): Comments concerning covariates added
                    400: 
                    401:   * imach.c (Module): refinements in the computation of lli if
                    402:   status=-2 in order to have more reliable computation if stepm is
                    403:   not 1 month. Version 0.98f
                    404: 
                    405:   Revision 1.120  2006/03/16 15:10:38  lievre
                    406:   (Module): refinements in the computation of lli if
                    407:   status=-2 in order to have more reliable computation if stepm is
                    408:   not 1 month. Version 0.98f
                    409: 
                    410:   Revision 1.119  2006/03/15 17:42:26  brouard
                    411:   (Module): Bug if status = -2, the loglikelihood was
                    412:   computed as likelihood omitting the logarithm. Version O.98e
                    413: 
                    414:   Revision 1.118  2006/03/14 18:20:07  brouard
                    415:   (Module): varevsij Comments added explaining the second
                    416:   table of variances if popbased=1 .
                    417:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    418:   (Module): Function pstamp added
                    419:   (Module): Version 0.98d
                    420: 
                    421:   Revision 1.117  2006/03/14 17:16:22  brouard
                    422:   (Module): varevsij Comments added explaining the second
                    423:   table of variances if popbased=1 .
                    424:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    425:   (Module): Function pstamp added
                    426:   (Module): Version 0.98d
                    427: 
                    428:   Revision 1.116  2006/03/06 10:29:27  brouard
                    429:   (Module): Variance-covariance wrong links and
                    430:   varian-covariance of ej. is needed (Saito).
                    431: 
                    432:   Revision 1.115  2006/02/27 12:17:45  brouard
                    433:   (Module): One freematrix added in mlikeli! 0.98c
                    434: 
                    435:   Revision 1.114  2006/02/26 12:57:58  brouard
                    436:   (Module): Some improvements in processing parameter
                    437:   filename with strsep.
                    438: 
                    439:   Revision 1.113  2006/02/24 14:20:24  brouard
                    440:   (Module): Memory leaks checks with valgrind and:
                    441:   datafile was not closed, some imatrix were not freed and on matrix
                    442:   allocation too.
                    443: 
                    444:   Revision 1.112  2006/01/30 09:55:26  brouard
                    445:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    446: 
                    447:   Revision 1.111  2006/01/25 20:38:18  brouard
                    448:   (Module): Lots of cleaning and bugs added (Gompertz)
                    449:   (Module): Comments can be added in data file. Missing date values
                    450:   can be a simple dot '.'.
                    451: 
                    452:   Revision 1.110  2006/01/25 00:51:50  brouard
                    453:   (Module): Lots of cleaning and bugs added (Gompertz)
                    454: 
                    455:   Revision 1.109  2006/01/24 19:37:15  brouard
                    456:   (Module): Comments (lines starting with a #) are allowed in data.
                    457: 
                    458:   Revision 1.108  2006/01/19 18:05:42  lievre
                    459:   Gnuplot problem appeared...
                    460:   To be fixed
                    461: 
                    462:   Revision 1.107  2006/01/19 16:20:37  brouard
                    463:   Test existence of gnuplot in imach path
                    464: 
                    465:   Revision 1.106  2006/01/19 13:24:36  brouard
                    466:   Some cleaning and links added in html output
                    467: 
                    468:   Revision 1.105  2006/01/05 20:23:19  lievre
                    469:   *** empty log message ***
                    470: 
                    471:   Revision 1.104  2005/09/30 16:11:43  lievre
                    472:   (Module): sump fixed, loop imx fixed, and simplifications.
                    473:   (Module): If the status is missing at the last wave but we know
                    474:   that the person is alive, then we can code his/her status as -2
                    475:   (instead of missing=-1 in earlier versions) and his/her
                    476:   contributions to the likelihood is 1 - Prob of dying from last
                    477:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    478:   the healthy state at last known wave). Version is 0.98
                    479: 
                    480:   Revision 1.103  2005/09/30 15:54:49  lievre
                    481:   (Module): sump fixed, loop imx fixed, and simplifications.
                    482: 
                    483:   Revision 1.102  2004/09/15 17:31:30  brouard
                    484:   Add the possibility to read data file including tab characters.
                    485: 
                    486:   Revision 1.101  2004/09/15 10:38:38  brouard
                    487:   Fix on curr_time
                    488: 
                    489:   Revision 1.100  2004/07/12 18:29:06  brouard
                    490:   Add version for Mac OS X. Just define UNIX in Makefile
                    491: 
                    492:   Revision 1.99  2004/06/05 08:57:40  brouard
                    493:   *** empty log message ***
                    494: 
                    495:   Revision 1.98  2004/05/16 15:05:56  brouard
                    496:   New version 0.97 . First attempt to estimate force of mortality
                    497:   directly from the data i.e. without the need of knowing the health
                    498:   state at each age, but using a Gompertz model: log u =a + b*age .
                    499:   This is the basic analysis of mortality and should be done before any
                    500:   other analysis, in order to test if the mortality estimated from the
                    501:   cross-longitudinal survey is different from the mortality estimated
                    502:   from other sources like vital statistic data.
                    503: 
                    504:   The same imach parameter file can be used but the option for mle should be -3.
                    505: 
1.133     brouard   506:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   507:   former routines in order to include the new code within the former code.
                    508: 
                    509:   The output is very simple: only an estimate of the intercept and of
                    510:   the slope with 95% confident intervals.
                    511: 
                    512:   Current limitations:
                    513:   A) Even if you enter covariates, i.e. with the
                    514:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    515:   B) There is no computation of Life Expectancy nor Life Table.
                    516: 
                    517:   Revision 1.97  2004/02/20 13:25:42  lievre
                    518:   Version 0.96d. Population forecasting command line is (temporarily)
                    519:   suppressed.
                    520: 
                    521:   Revision 1.96  2003/07/15 15:38:55  brouard
                    522:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    523:   rewritten within the same printf. Workaround: many printfs.
                    524: 
                    525:   Revision 1.95  2003/07/08 07:54:34  brouard
                    526:   * imach.c (Repository):
                    527:   (Repository): Using imachwizard code to output a more meaningful covariance
                    528:   matrix (cov(a12,c31) instead of numbers.
                    529: 
                    530:   Revision 1.94  2003/06/27 13:00:02  brouard
                    531:   Just cleaning
                    532: 
                    533:   Revision 1.93  2003/06/25 16:33:55  brouard
                    534:   (Module): On windows (cygwin) function asctime_r doesn't
                    535:   exist so I changed back to asctime which exists.
                    536:   (Module): Version 0.96b
                    537: 
                    538:   Revision 1.92  2003/06/25 16:30:45  brouard
                    539:   (Module): On windows (cygwin) function asctime_r doesn't
                    540:   exist so I changed back to asctime which exists.
                    541: 
                    542:   Revision 1.91  2003/06/25 15:30:29  brouard
                    543:   * imach.c (Repository): Duplicated warning errors corrected.
                    544:   (Repository): Elapsed time after each iteration is now output. It
                    545:   helps to forecast when convergence will be reached. Elapsed time
                    546:   is stamped in powell.  We created a new html file for the graphs
                    547:   concerning matrix of covariance. It has extension -cov.htm.
                    548: 
                    549:   Revision 1.90  2003/06/24 12:34:15  brouard
                    550:   (Module): Some bugs corrected for windows. Also, when
                    551:   mle=-1 a template is output in file "or"mypar.txt with the design
                    552:   of the covariance matrix to be input.
                    553: 
                    554:   Revision 1.89  2003/06/24 12:30:52  brouard
                    555:   (Module): Some bugs corrected for windows. Also, when
                    556:   mle=-1 a template is output in file "or"mypar.txt with the design
                    557:   of the covariance matrix to be input.
                    558: 
                    559:   Revision 1.88  2003/06/23 17:54:56  brouard
                    560:   * 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.
                    561: 
                    562:   Revision 1.87  2003/06/18 12:26:01  brouard
                    563:   Version 0.96
                    564: 
                    565:   Revision 1.86  2003/06/17 20:04:08  brouard
                    566:   (Module): Change position of html and gnuplot routines and added
                    567:   routine fileappend.
                    568: 
                    569:   Revision 1.85  2003/06/17 13:12:43  brouard
                    570:   * imach.c (Repository): Check when date of death was earlier that
                    571:   current date of interview. It may happen when the death was just
                    572:   prior to the death. In this case, dh was negative and likelihood
                    573:   was wrong (infinity). We still send an "Error" but patch by
                    574:   assuming that the date of death was just one stepm after the
                    575:   interview.
                    576:   (Repository): Because some people have very long ID (first column)
                    577:   we changed int to long in num[] and we added a new lvector for
                    578:   memory allocation. But we also truncated to 8 characters (left
                    579:   truncation)
                    580:   (Repository): No more line truncation errors.
                    581: 
                    582:   Revision 1.84  2003/06/13 21:44:43  brouard
                    583:   * imach.c (Repository): Replace "freqsummary" at a correct
                    584:   place. It differs from routine "prevalence" which may be called
                    585:   many times. Probs is memory consuming and must be used with
                    586:   parcimony.
                    587:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    588: 
                    589:   Revision 1.83  2003/06/10 13:39:11  lievre
                    590:   *** empty log message ***
                    591: 
                    592:   Revision 1.82  2003/06/05 15:57:20  brouard
                    593:   Add log in  imach.c and  fullversion number is now printed.
                    594: 
                    595: */
                    596: /*
                    597:    Interpolated Markov Chain
                    598: 
                    599:   Short summary of the programme:
                    600:   
                    601:   This program computes Healthy Life Expectancies from
                    602:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    603:   first survey ("cross") where individuals from different ages are
                    604:   interviewed on their health status or degree of disability (in the
                    605:   case of a health survey which is our main interest) -2- at least a
                    606:   second wave of interviews ("longitudinal") which measure each change
                    607:   (if any) in individual health status.  Health expectancies are
                    608:   computed from the time spent in each health state according to a
                    609:   model. More health states you consider, more time is necessary to reach the
                    610:   Maximum Likelihood of the parameters involved in the model.  The
                    611:   simplest model is the multinomial logistic model where pij is the
                    612:   probability to be observed in state j at the second wave
                    613:   conditional to be observed in state i at the first wave. Therefore
                    614:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    615:   'age' is age and 'sex' is a covariate. If you want to have a more
                    616:   complex model than "constant and age", you should modify the program
                    617:   where the markup *Covariates have to be included here again* invites
                    618:   you to do it.  More covariates you add, slower the
                    619:   convergence.
                    620: 
                    621:   The advantage of this computer programme, compared to a simple
                    622:   multinomial logistic model, is clear when the delay between waves is not
                    623:   identical for each individual. Also, if a individual missed an
                    624:   intermediate interview, the information is lost, but taken into
                    625:   account using an interpolation or extrapolation.  
                    626: 
                    627:   hPijx is the probability to be observed in state i at age x+h
                    628:   conditional to the observed state i at age x. The delay 'h' can be
                    629:   split into an exact number (nh*stepm) of unobserved intermediate
                    630:   states. This elementary transition (by month, quarter,
                    631:   semester or year) is modelled as a multinomial logistic.  The hPx
                    632:   matrix is simply the matrix product of nh*stepm elementary matrices
                    633:   and the contribution of each individual to the likelihood is simply
                    634:   hPijx.
                    635: 
                    636:   Also this programme outputs the covariance matrix of the parameters but also
                    637:   of the life expectancies. It also computes the period (stable) prevalence. 
                    638:   
1.133     brouard   639:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    640:            Institut national d'études démographiques, Paris.
1.126     brouard   641:   This software have been partly granted by Euro-REVES, a concerted action
                    642:   from the European Union.
                    643:   It is copyrighted identically to a GNU software product, ie programme and
                    644:   software can be distributed freely for non commercial use. Latest version
                    645:   can be accessed at http://euroreves.ined.fr/imach .
                    646: 
                    647:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    648:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    649:   
                    650:   **********************************************************************/
                    651: /*
                    652:   main
                    653:   read parameterfile
                    654:   read datafile
                    655:   concatwav
                    656:   freqsummary
                    657:   if (mle >= 1)
                    658:     mlikeli
                    659:   print results files
                    660:   if mle==1 
                    661:      computes hessian
                    662:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    663:       begin-prev-date,...
                    664:   open gnuplot file
                    665:   open html file
1.145     brouard   666:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    667:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    668:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    669:     freexexit2 possible for memory heap.
                    670: 
                    671:   h Pij x                         | pij_nom  ficrestpij
                    672:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    673:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    674:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    675: 
                    676:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    677:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    678:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    679:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    680:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    681: 
1.126     brouard   682:   forecasting if prevfcast==1 prevforecast call prevalence()
                    683:   health expectancies
                    684:   Variance-covariance of DFLE
                    685:   prevalence()
                    686:    movingaverage()
                    687:   varevsij() 
                    688:   if popbased==1 varevsij(,popbased)
                    689:   total life expectancies
                    690:   Variance of period (stable) prevalence
                    691:  end
                    692: */
                    693: 
1.187     brouard   694: /* #define DEBUG */
                    695: /* #define DEBUGBRENT */
1.203     brouard   696: /* #define DEBUGLINMIN */
                    697: /* #define DEBUGHESS */
                    698: #define DEBUGHESSIJ
                    699: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   700: #define POWELL /* Instead of NLOPT */
1.192     brouard   701: #define POWELLF1F3 /* Skip test */
1.186     brouard   702: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    703: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   704: 
                    705: #include <math.h>
                    706: #include <stdio.h>
                    707: #include <stdlib.h>
                    708: #include <string.h>
1.159     brouard   709: 
                    710: #ifdef _WIN32
                    711: #include <io.h>
1.172     brouard   712: #include <windows.h>
                    713: #include <tchar.h>
1.159     brouard   714: #else
1.126     brouard   715: #include <unistd.h>
1.159     brouard   716: #endif
1.126     brouard   717: 
                    718: #include <limits.h>
                    719: #include <sys/types.h>
1.171     brouard   720: 
                    721: #if defined(__GNUC__)
                    722: #include <sys/utsname.h> /* Doesn't work on Windows */
                    723: #endif
                    724: 
1.126     brouard   725: #include <sys/stat.h>
                    726: #include <errno.h>
1.159     brouard   727: /* extern int errno; */
1.126     brouard   728: 
1.157     brouard   729: /* #ifdef LINUX */
                    730: /* #include <time.h> */
                    731: /* #include "timeval.h" */
                    732: /* #else */
                    733: /* #include <sys/time.h> */
                    734: /* #endif */
                    735: 
1.126     brouard   736: #include <time.h>
                    737: 
1.136     brouard   738: #ifdef GSL
                    739: #include <gsl/gsl_errno.h>
                    740: #include <gsl/gsl_multimin.h>
                    741: #endif
                    742: 
1.167     brouard   743: 
1.162     brouard   744: #ifdef NLOPT
                    745: #include <nlopt.h>
                    746: typedef struct {
                    747:   double (* function)(double [] );
                    748: } myfunc_data ;
                    749: #endif
                    750: 
1.126     brouard   751: /* #include <libintl.h> */
                    752: /* #define _(String) gettext (String) */
                    753: 
1.141     brouard   754: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   755: 
                    756: #define GNUPLOTPROGRAM "gnuplot"
                    757: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    758: #define FILENAMELENGTH 132
                    759: 
                    760: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    761: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    762: 
1.144     brouard   763: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    764: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   765: 
                    766: #define NINTERVMAX 8
1.144     brouard   767: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    768: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    769: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   770: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   771: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    772: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   773: #define MAXN 20000
1.144     brouard   774: #define YEARM 12. /**< Number of months per year */
1.126     brouard   775: #define AGESUP 130
                    776: #define AGEBASE 40
1.194     brouard   777: #define AGEOVERFLOW 1.e20
1.164     brouard   778: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   779: #ifdef _WIN32
                    780: #define DIRSEPARATOR '\\'
                    781: #define CHARSEPARATOR "\\"
                    782: #define ODIRSEPARATOR '/'
                    783: #else
1.126     brouard   784: #define DIRSEPARATOR '/'
                    785: #define CHARSEPARATOR "/"
                    786: #define ODIRSEPARATOR '\\'
                    787: #endif
                    788: 
1.214   ! brouard   789: /* $Id: imach.c,v 1.213 2015/12/11 18:22:17 brouard Exp $ */
1.126     brouard   790: /* $State: Exp $ */
1.196     brouard   791: #include "version.h"
                    792: char version[]=__IMACH_VERSION__;
1.204     brouard   793: 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.214   ! brouard   794: char fullversion[]="$Revision: 1.213 $ $Date: 2015/12/11 18:22:17 $"; 
1.126     brouard   795: char strstart[80];
                    796: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   797: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   798: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   799: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    800: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    801: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    802: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    803: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    804: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    805: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    806: int cptcov=0; /* Working variable */
1.126     brouard   807: int npar=NPARMAX;
                    808: int nlstate=2; /* Number of live states */
                    809: int ndeath=1; /* Number of dead states */
1.130     brouard   810: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   811: int popbased=0;
                    812: 
                    813: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   814: int maxwav=0; /* Maxim number of waves */
                    815: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    816: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    817: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   818:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   819: int mle=1, weightopt=0;
1.126     brouard   820: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    821: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    822: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    823:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   824: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   825: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   826: double **matprod2(); /* test */
1.126     brouard   827: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    828: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   829: /*FILE *fic ; */ /* Used in readdata only */
1.214   ! brouard   830: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   831: FILE *ficlog, *ficrespow;
1.130     brouard   832: int globpr=0; /* Global variable for printing or not */
1.126     brouard   833: double fretone; /* Only one call to likelihood */
1.130     brouard   834: long ipmx=0; /* Number of contributions */
1.126     brouard   835: double sw; /* Sum of weights */
                    836: char filerespow[FILENAMELENGTH];
                    837: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    838: FILE *ficresilk;
                    839: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    840: FILE *ficresprobmorprev;
                    841: FILE *fichtm, *fichtmcov; /* Html File */
                    842: FILE *ficreseij;
                    843: char filerese[FILENAMELENGTH];
                    844: FILE *ficresstdeij;
                    845: char fileresstde[FILENAMELENGTH];
                    846: FILE *ficrescveij;
                    847: char filerescve[FILENAMELENGTH];
                    848: FILE  *ficresvij;
                    849: char fileresv[FILENAMELENGTH];
                    850: FILE  *ficresvpl;
                    851: char fileresvpl[FILENAMELENGTH];
                    852: char title[MAXLINE];
                    853: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    854: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    855: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    856: char command[FILENAMELENGTH];
                    857: int  outcmd=0;
                    858: 
                    859: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   860: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   861: char filelog[FILENAMELENGTH]; /* Log file */
                    862: char filerest[FILENAMELENGTH];
                    863: char fileregp[FILENAMELENGTH];
                    864: char popfile[FILENAMELENGTH];
                    865: 
                    866: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    867: 
1.157     brouard   868: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    869: /* struct timezone tzp; */
                    870: /* extern int gettimeofday(); */
                    871: struct tm tml, *gmtime(), *localtime();
                    872: 
                    873: extern time_t time();
                    874: 
                    875: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    876: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    877: struct tm tm;
                    878: 
1.126     brouard   879: char strcurr[80], strfor[80];
                    880: 
                    881: char *endptr;
                    882: long lval;
                    883: double dval;
                    884: 
                    885: #define NR_END 1
                    886: #define FREE_ARG char*
                    887: #define FTOL 1.0e-10
                    888: 
                    889: #define NRANSI 
                    890: #define ITMAX 200 
                    891: 
                    892: #define TOL 2.0e-4 
                    893: 
                    894: #define CGOLD 0.3819660 
                    895: #define ZEPS 1.0e-10 
                    896: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    897: 
                    898: #define GOLD 1.618034 
                    899: #define GLIMIT 100.0 
                    900: #define TINY 1.0e-20 
                    901: 
                    902: static double maxarg1,maxarg2;
                    903: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    904: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    905:   
                    906: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    907: #define rint(a) floor(a+0.5)
1.166     brouard   908: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   909: #define mytinydouble 1.0e-16
1.166     brouard   910: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    911: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    912: /* static double dsqrarg; */
                    913: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   914: static double sqrarg;
                    915: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    916: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    917: int agegomp= AGEGOMP;
                    918: 
                    919: int imx; 
                    920: int stepm=1;
                    921: /* Stepm, step in month: minimum step interpolation*/
                    922: 
                    923: int estepm;
                    924: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    925: 
                    926: int m,nb;
                    927: long *num;
1.197     brouard   928: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   929: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    930:                   covariate for which somebody answered excluding 
                    931:                   undefined. Usually 2: 0 and 1. */
                    932: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    933:                             covariate for which somebody answered including 
                    934:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   935: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    936: double **pmmij, ***probs;
                    937: double *ageexmed,*agecens;
                    938: double dateintmean=0;
                    939: 
                    940: double *weight;
                    941: int **s; /* Status */
1.141     brouard   942: double *agedc;
1.145     brouard   943: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   944:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   945:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   946: double  idx; 
                    947: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   948: int *Tage;
1.145     brouard   949: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   950: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   951: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   952: double *lsurv, *lpop, *tpop;
                    953: 
1.143     brouard   954: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    955: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   956: 
                    957: /**************** split *************************/
                    958: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    959: {
                    960:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    961:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    962:   */ 
                    963:   char *ss;                            /* pointer */
1.186     brouard   964:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   965: 
                    966:   l1 = strlen(path );                  /* length of path */
                    967:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    968:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    969:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    970:     strcpy( name, path );              /* we got the fullname name because no directory */
                    971:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    972:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    973:     /* get current working directory */
                    974:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   975: #ifdef WIN32
                    976:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    977: #else
                    978:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    979: #endif
1.126     brouard   980:       return( GLOCK_ERROR_GETCWD );
                    981:     }
                    982:     /* got dirc from getcwd*/
                    983:     printf(" DIRC = %s \n",dirc);
1.205     brouard   984:   } else {                             /* strip directory from path */
1.126     brouard   985:     ss++;                              /* after this, the filename */
                    986:     l2 = strlen( ss );                 /* length of filename */
                    987:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    988:     strcpy( name, ss );                /* save file name */
                    989:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   990:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   991:     printf(" DIRC2 = %s \n",dirc);
                    992:   }
                    993:   /* We add a separator at the end of dirc if not exists */
                    994:   l1 = strlen( dirc );                 /* length of directory */
                    995:   if( dirc[l1-1] != DIRSEPARATOR ){
                    996:     dirc[l1] =  DIRSEPARATOR;
                    997:     dirc[l1+1] = 0; 
                    998:     printf(" DIRC3 = %s \n",dirc);
                    999:   }
                   1000:   ss = strrchr( name, '.' );           /* find last / */
                   1001:   if (ss >0){
                   1002:     ss++;
                   1003:     strcpy(ext,ss);                    /* save extension */
                   1004:     l1= strlen( name);
                   1005:     l2= strlen(ss)+1;
                   1006:     strncpy( finame, name, l1-l2);
                   1007:     finame[l1-l2]= 0;
                   1008:   }
                   1009: 
                   1010:   return( 0 );                         /* we're done */
                   1011: }
                   1012: 
                   1013: 
                   1014: /******************************************/
                   1015: 
                   1016: void replace_back_to_slash(char *s, char*t)
                   1017: {
                   1018:   int i;
                   1019:   int lg=0;
                   1020:   i=0;
                   1021:   lg=strlen(t);
                   1022:   for(i=0; i<= lg; i++) {
                   1023:     (s[i] = t[i]);
                   1024:     if (t[i]== '\\') s[i]='/';
                   1025:   }
                   1026: }
                   1027: 
1.132     brouard  1028: char *trimbb(char *out, char *in)
1.137     brouard  1029: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1030:   char *s;
                   1031:   s=out;
                   1032:   while (*in != '\0'){
1.137     brouard  1033:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1034:       in++;
                   1035:     }
                   1036:     *out++ = *in++;
                   1037:   }
                   1038:   *out='\0';
                   1039:   return s;
                   1040: }
                   1041: 
1.187     brouard  1042: /* char *substrchaine(char *out, char *in, char *chain) */
                   1043: /* { */
                   1044: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1045: /*   char *s, *t; */
                   1046: /*   t=in;s=out; */
                   1047: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1048: /*     *out++ = *in++; */
                   1049: /*   } */
                   1050: 
                   1051: /*   /\* *in matches *chain *\/ */
                   1052: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1053: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1054: /*   } */
                   1055: /*   in--; chain--; */
                   1056: /*   while ( (*in != '\0')){ */
                   1057: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1058: /*     *out++ = *in++; */
                   1059: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1060: /*   } */
                   1061: /*   *out='\0'; */
                   1062: /*   out=s; */
                   1063: /*   return out; */
                   1064: /* } */
                   1065: char *substrchaine(char *out, char *in, char *chain)
                   1066: {
                   1067:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1068:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1069: 
                   1070:   char *strloc;
                   1071: 
                   1072:   strcpy (out, in); 
                   1073:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1074:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1075:   if(strloc != NULL){ 
                   1076:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1077:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1078:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1079:   }
                   1080:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1081:   return out;
                   1082: }
                   1083: 
                   1084: 
1.145     brouard  1085: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1086: {
1.187     brouard  1087:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1088:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1089:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1090:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1091:   */
1.160     brouard  1092:   char *s, *t;
1.145     brouard  1093:   t=in;s=in;
                   1094:   while ((*in != occ) && (*in != '\0')){
                   1095:     *alocc++ = *in++;
                   1096:   }
                   1097:   if( *in == occ){
                   1098:     *(alocc)='\0';
                   1099:     s=++in;
                   1100:   }
                   1101:  
                   1102:   if (s == t) {/* occ not found */
                   1103:     *(alocc-(in-s))='\0';
                   1104:     in=s;
                   1105:   }
                   1106:   while ( *in != '\0'){
                   1107:     *blocc++ = *in++;
                   1108:   }
                   1109: 
                   1110:   *blocc='\0';
                   1111:   return t;
                   1112: }
1.137     brouard  1113: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1114: {
1.187     brouard  1115:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1116:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1117:      gives blocc="abcdef2ghi" and alocc="j".
                   1118:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1119:   */
                   1120:   char *s, *t;
                   1121:   t=in;s=in;
                   1122:   while (*in != '\0'){
                   1123:     while( *in == occ){
                   1124:       *blocc++ = *in++;
                   1125:       s=in;
                   1126:     }
                   1127:     *blocc++ = *in++;
                   1128:   }
                   1129:   if (s == t) /* occ not found */
                   1130:     *(blocc-(in-s))='\0';
                   1131:   else
                   1132:     *(blocc-(in-s)-1)='\0';
                   1133:   in=s;
                   1134:   while ( *in != '\0'){
                   1135:     *alocc++ = *in++;
                   1136:   }
                   1137: 
                   1138:   *alocc='\0';
                   1139:   return s;
                   1140: }
                   1141: 
1.126     brouard  1142: int nbocc(char *s, char occ)
                   1143: {
                   1144:   int i,j=0;
                   1145:   int lg=20;
                   1146:   i=0;
                   1147:   lg=strlen(s);
                   1148:   for(i=0; i<= lg; i++) {
                   1149:   if  (s[i] == occ ) j++;
                   1150:   }
                   1151:   return j;
                   1152: }
                   1153: 
1.137     brouard  1154: /* void cutv(char *u,char *v, char*t, char occ) */
                   1155: /* { */
                   1156: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1157: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1158: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1159: /*   int i,lg,j,p=0; */
                   1160: /*   i=0; */
                   1161: /*   lg=strlen(t); */
                   1162: /*   for(j=0; j<=lg-1; j++) { */
                   1163: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1164: /*   } */
1.126     brouard  1165: 
1.137     brouard  1166: /*   for(j=0; j<p; j++) { */
                   1167: /*     (u[j] = t[j]); */
                   1168: /*   } */
                   1169: /*      u[p]='\0'; */
1.126     brouard  1170: 
1.137     brouard  1171: /*    for(j=0; j<= lg; j++) { */
                   1172: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1173: /*   } */
                   1174: /* } */
1.126     brouard  1175: 
1.160     brouard  1176: #ifdef _WIN32
                   1177: char * strsep(char **pp, const char *delim)
                   1178: {
                   1179:   char *p, *q;
                   1180:          
                   1181:   if ((p = *pp) == NULL)
                   1182:     return 0;
                   1183:   if ((q = strpbrk (p, delim)) != NULL)
                   1184:   {
                   1185:     *pp = q + 1;
                   1186:     *q = '\0';
                   1187:   }
                   1188:   else
                   1189:     *pp = 0;
                   1190:   return p;
                   1191: }
                   1192: #endif
                   1193: 
1.126     brouard  1194: /********************** nrerror ********************/
                   1195: 
                   1196: void nrerror(char error_text[])
                   1197: {
                   1198:   fprintf(stderr,"ERREUR ...\n");
                   1199:   fprintf(stderr,"%s\n",error_text);
                   1200:   exit(EXIT_FAILURE);
                   1201: }
                   1202: /*********************** vector *******************/
                   1203: double *vector(int nl, int nh)
                   1204: {
                   1205:   double *v;
                   1206:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1207:   if (!v) nrerror("allocation failure in vector");
                   1208:   return v-nl+NR_END;
                   1209: }
                   1210: 
                   1211: /************************ free vector ******************/
                   1212: void free_vector(double*v, int nl, int nh)
                   1213: {
                   1214:   free((FREE_ARG)(v+nl-NR_END));
                   1215: }
                   1216: 
                   1217: /************************ivector *******************************/
                   1218: int *ivector(long nl,long nh)
                   1219: {
                   1220:   int *v;
                   1221:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1222:   if (!v) nrerror("allocation failure in ivector");
                   1223:   return v-nl+NR_END;
                   1224: }
                   1225: 
                   1226: /******************free ivector **************************/
                   1227: void free_ivector(int *v, long nl, long nh)
                   1228: {
                   1229:   free((FREE_ARG)(v+nl-NR_END));
                   1230: }
                   1231: 
                   1232: /************************lvector *******************************/
                   1233: long *lvector(long nl,long nh)
                   1234: {
                   1235:   long *v;
                   1236:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1237:   if (!v) nrerror("allocation failure in ivector");
                   1238:   return v-nl+NR_END;
                   1239: }
                   1240: 
                   1241: /******************free lvector **************************/
                   1242: void free_lvector(long *v, long nl, long nh)
                   1243: {
                   1244:   free((FREE_ARG)(v+nl-NR_END));
                   1245: }
                   1246: 
                   1247: /******************* imatrix *******************************/
                   1248: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1249:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1250: { 
                   1251:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1252:   int **m; 
                   1253:   
                   1254:   /* allocate pointers to rows */ 
                   1255:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1256:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1257:   m += NR_END; 
                   1258:   m -= nrl; 
                   1259:   
                   1260:   
                   1261:   /* allocate rows and set pointers to them */ 
                   1262:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1263:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1264:   m[nrl] += NR_END; 
                   1265:   m[nrl] -= ncl; 
                   1266:   
                   1267:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1268:   
                   1269:   /* return pointer to array of pointers to rows */ 
                   1270:   return m; 
                   1271: } 
                   1272: 
                   1273: /****************** free_imatrix *************************/
                   1274: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1275:       int **m;
                   1276:       long nch,ncl,nrh,nrl; 
                   1277:      /* free an int matrix allocated by imatrix() */ 
                   1278: { 
                   1279:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1280:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1281: } 
                   1282: 
                   1283: /******************* matrix *******************************/
                   1284: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1285: {
                   1286:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1287:   double **m;
                   1288: 
                   1289:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1290:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1291:   m += NR_END;
                   1292:   m -= nrl;
                   1293: 
                   1294:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1295:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1296:   m[nrl] += NR_END;
                   1297:   m[nrl] -= ncl;
                   1298: 
                   1299:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1300:   return m;
1.145     brouard  1301:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1302: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1303: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1304:    */
                   1305: }
                   1306: 
                   1307: /*************************free matrix ************************/
                   1308: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1309: {
                   1310:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1311:   free((FREE_ARG)(m+nrl-NR_END));
                   1312: }
                   1313: 
                   1314: /******************* ma3x *******************************/
                   1315: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1316: {
                   1317:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1318:   double ***m;
                   1319: 
                   1320:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1321:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1322:   m += NR_END;
                   1323:   m -= nrl;
                   1324: 
                   1325:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1326:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1327:   m[nrl] += NR_END;
                   1328:   m[nrl] -= ncl;
                   1329: 
                   1330:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1331: 
                   1332:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1333:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1334:   m[nrl][ncl] += NR_END;
                   1335:   m[nrl][ncl] -= nll;
                   1336:   for (j=ncl+1; j<=nch; j++) 
                   1337:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1338:   
                   1339:   for (i=nrl+1; i<=nrh; i++) {
                   1340:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1341:     for (j=ncl+1; j<=nch; j++) 
                   1342:       m[i][j]=m[i][j-1]+nlay;
                   1343:   }
                   1344:   return m; 
                   1345:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1346:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1347:   */
                   1348: }
                   1349: 
                   1350: /*************************free ma3x ************************/
                   1351: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1352: {
                   1353:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1354:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1355:   free((FREE_ARG)(m+nrl-NR_END));
                   1356: }
                   1357: 
                   1358: /*************** function subdirf ***********/
                   1359: char *subdirf(char fileres[])
                   1360: {
                   1361:   /* Caution optionfilefiname is hidden */
                   1362:   strcpy(tmpout,optionfilefiname);
                   1363:   strcat(tmpout,"/"); /* Add to the right */
                   1364:   strcat(tmpout,fileres);
                   1365:   return tmpout;
                   1366: }
                   1367: 
                   1368: /*************** function subdirf2 ***********/
                   1369: char *subdirf2(char fileres[], char *preop)
                   1370: {
                   1371:   
                   1372:   /* Caution optionfilefiname is hidden */
                   1373:   strcpy(tmpout,optionfilefiname);
                   1374:   strcat(tmpout,"/");
                   1375:   strcat(tmpout,preop);
                   1376:   strcat(tmpout,fileres);
                   1377:   return tmpout;
                   1378: }
                   1379: 
                   1380: /*************** function subdirf3 ***********/
                   1381: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1382: {
                   1383:   
                   1384:   /* Caution optionfilefiname is hidden */
                   1385:   strcpy(tmpout,optionfilefiname);
                   1386:   strcat(tmpout,"/");
                   1387:   strcat(tmpout,preop);
                   1388:   strcat(tmpout,preop2);
                   1389:   strcat(tmpout,fileres);
                   1390:   return tmpout;
                   1391: }
1.213     brouard  1392:  
                   1393: /*************** function subdirfext ***********/
                   1394: char *subdirfext(char fileres[], char *preop, char *postop)
                   1395: {
                   1396:   
                   1397:   strcpy(tmpout,preop);
                   1398:   strcat(tmpout,fileres);
                   1399:   strcat(tmpout,postop);
                   1400:   return tmpout;
                   1401: }
1.126     brouard  1402: 
1.213     brouard  1403: /*************** function subdirfext3 ***********/
                   1404: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1405: {
                   1406:   
                   1407:   /* Caution optionfilefiname is hidden */
                   1408:   strcpy(tmpout,optionfilefiname);
                   1409:   strcat(tmpout,"/");
                   1410:   strcat(tmpout,preop);
                   1411:   strcat(tmpout,fileres);
                   1412:   strcat(tmpout,postop);
                   1413:   return tmpout;
                   1414: }
                   1415:  
1.162     brouard  1416: char *asc_diff_time(long time_sec, char ascdiff[])
                   1417: {
                   1418:   long sec_left, days, hours, minutes;
                   1419:   days = (time_sec) / (60*60*24);
                   1420:   sec_left = (time_sec) % (60*60*24);
                   1421:   hours = (sec_left) / (60*60) ;
                   1422:   sec_left = (sec_left) %(60*60);
                   1423:   minutes = (sec_left) /60;
                   1424:   sec_left = (sec_left) % (60);
                   1425:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1426:   return ascdiff;
                   1427: }
                   1428: 
1.126     brouard  1429: /***************** f1dim *************************/
                   1430: extern int ncom; 
                   1431: extern double *pcom,*xicom;
                   1432: extern double (*nrfunc)(double []); 
                   1433:  
                   1434: double f1dim(double x) 
                   1435: { 
                   1436:   int j; 
                   1437:   double f;
                   1438:   double *xt; 
                   1439:  
                   1440:   xt=vector(1,ncom); 
                   1441:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1442:   f=(*nrfunc)(xt); 
                   1443:   free_vector(xt,1,ncom); 
                   1444:   return f; 
                   1445: } 
                   1446: 
                   1447: /*****************brent *************************/
                   1448: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1449: {
                   1450:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1451:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1452:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1453:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1454:    * returned function value. 
                   1455:   */
1.126     brouard  1456:   int iter; 
                   1457:   double a,b,d,etemp;
1.159     brouard  1458:   double fu=0,fv,fw,fx;
1.164     brouard  1459:   double ftemp=0.;
1.126     brouard  1460:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1461:   double e=0.0; 
                   1462:  
                   1463:   a=(ax < cx ? ax : cx); 
                   1464:   b=(ax > cx ? ax : cx); 
                   1465:   x=w=v=bx; 
                   1466:   fw=fv=fx=(*f)(x); 
                   1467:   for (iter=1;iter<=ITMAX;iter++) { 
                   1468:     xm=0.5*(a+b); 
                   1469:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1470:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1471:     printf(".");fflush(stdout);
                   1472:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1473: #ifdef DEBUGBRENT
1.126     brouard  1474:     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);
                   1475:     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);
                   1476:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1477: #endif
                   1478:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1479:       *xmin=x; 
                   1480:       return fx; 
                   1481:     } 
                   1482:     ftemp=fu;
                   1483:     if (fabs(e) > tol1) { 
                   1484:       r=(x-w)*(fx-fv); 
                   1485:       q=(x-v)*(fx-fw); 
                   1486:       p=(x-v)*q-(x-w)*r; 
                   1487:       q=2.0*(q-r); 
                   1488:       if (q > 0.0) p = -p; 
                   1489:       q=fabs(q); 
                   1490:       etemp=e; 
                   1491:       e=d; 
                   1492:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1493:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1494:       else { 
                   1495:        d=p/q; 
                   1496:        u=x+d; 
                   1497:        if (u-a < tol2 || b-u < tol2) 
                   1498:          d=SIGN(tol1,xm-x); 
                   1499:       } 
                   1500:     } else { 
                   1501:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1502:     } 
                   1503:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1504:     fu=(*f)(u); 
                   1505:     if (fu <= fx) { 
                   1506:       if (u >= x) a=x; else b=x; 
                   1507:       SHFT(v,w,x,u) 
1.183     brouard  1508:       SHFT(fv,fw,fx,fu) 
                   1509:     } else { 
                   1510:       if (u < x) a=u; else b=u; 
                   1511:       if (fu <= fw || w == x) { 
                   1512:        v=w; 
                   1513:        w=u; 
                   1514:        fv=fw; 
                   1515:        fw=fu; 
                   1516:       } else if (fu <= fv || v == x || v == w) { 
                   1517:        v=u; 
                   1518:        fv=fu; 
                   1519:       } 
                   1520:     } 
1.126     brouard  1521:   } 
                   1522:   nrerror("Too many iterations in brent"); 
                   1523:   *xmin=x; 
                   1524:   return fx; 
                   1525: } 
                   1526: 
                   1527: /****************** mnbrak ***********************/
                   1528: 
                   1529: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1530:            double (*func)(double)) 
1.183     brouard  1531: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1532: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1533: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1534: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1535:    */
1.126     brouard  1536:   double ulim,u,r,q, dum;
                   1537:   double fu; 
1.187     brouard  1538: 
                   1539:   double scale=10.;
                   1540:   int iterscale=0;
                   1541: 
                   1542:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1543:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1544: 
                   1545: 
                   1546:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1547:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1548:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1549:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1550:   /* } */
                   1551: 
1.126     brouard  1552:   if (*fb > *fa) { 
                   1553:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1554:     SHFT(dum,*fb,*fa,dum) 
                   1555:   } 
1.126     brouard  1556:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1557:   *fc=(*func)(*cx); 
1.183     brouard  1558: #ifdef DEBUG
                   1559:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1560:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1561: #endif
                   1562:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1563:     r=(*bx-*ax)*(*fb-*fc); 
                   1564:     q=(*bx-*cx)*(*fb-*fa); 
                   1565:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1566:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1567:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1568:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1569:       fu=(*func)(u); 
1.163     brouard  1570: #ifdef DEBUG
                   1571:       /* f(x)=A(x-u)**2+f(u) */
                   1572:       double A, fparabu; 
                   1573:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1574:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1575:       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);
                   1576:       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  1577:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1578:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1579:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1580:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1581: #endif 
1.184     brouard  1582: #ifdef MNBRAKORIGINAL
1.183     brouard  1583: #else
1.191     brouard  1584: /*       if (fu > *fc) { */
                   1585: /* #ifdef DEBUG */
                   1586: /*       printf("mnbrak4  fu > fc \n"); */
                   1587: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1588: /* #endif */
                   1589: /*     /\* 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 *\\/  *\/ */
                   1590: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1591: /*     dum=u; /\* Shifting c and u *\/ */
                   1592: /*     u = *cx; */
                   1593: /*     *cx = dum; */
                   1594: /*     dum = fu; */
                   1595: /*     fu = *fc; */
                   1596: /*     *fc =dum; */
                   1597: /*       } else { /\* end *\/ */
                   1598: /* #ifdef DEBUG */
                   1599: /*       printf("mnbrak3  fu < fc \n"); */
                   1600: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1601: /* #endif */
                   1602: /*     dum=u; /\* Shifting c and u *\/ */
                   1603: /*     u = *cx; */
                   1604: /*     *cx = dum; */
                   1605: /*     dum = fu; */
                   1606: /*     fu = *fc; */
                   1607: /*     *fc =dum; */
                   1608: /*       } */
1.183     brouard  1609: #ifdef DEBUG
1.191     brouard  1610:       printf("mnbrak34  fu < or >= fc \n");
                   1611:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1612: #endif
1.191     brouard  1613:       dum=u; /* Shifting c and u */
                   1614:       u = *cx;
                   1615:       *cx = dum;
                   1616:       dum = fu;
                   1617:       fu = *fc;
                   1618:       *fc =dum;
1.183     brouard  1619: #endif
1.162     brouard  1620:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1621: #ifdef DEBUG
                   1622:       printf("mnbrak2  u after c but before ulim\n");
                   1623:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1624: #endif
1.126     brouard  1625:       fu=(*func)(u); 
                   1626:       if (fu < *fc) { 
1.183     brouard  1627: #ifdef DEBUG
                   1628:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1629:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1630: #endif
1.126     brouard  1631:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1632:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1633:       } 
1.162     brouard  1634:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1635: #ifdef DEBUG
                   1636:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1637:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1638: #endif
1.126     brouard  1639:       u=ulim; 
                   1640:       fu=(*func)(u); 
1.183     brouard  1641:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1642: #ifdef DEBUG
                   1643:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1644:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1645: #endif
1.126     brouard  1646:       u=(*cx)+GOLD*(*cx-*bx); 
                   1647:       fu=(*func)(u); 
1.183     brouard  1648:     } /* end tests */
1.126     brouard  1649:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1650:     SHFT(*fa,*fb,*fc,fu) 
                   1651: #ifdef DEBUG
                   1652:       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);
                   1653:       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);
                   1654: #endif
                   1655:   } /* 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  1656: } 
                   1657: 
                   1658: /*************** linmin ************************/
1.162     brouard  1659: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1660: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1661: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1662: the value of func at the returned location p . This is actually all accomplished by calling the
                   1663: routines mnbrak and brent .*/
1.126     brouard  1664: int ncom; 
                   1665: double *pcom,*xicom;
                   1666: double (*nrfunc)(double []); 
                   1667:  
                   1668: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1669: { 
                   1670:   double brent(double ax, double bx, double cx, 
                   1671:               double (*f)(double), double tol, double *xmin); 
                   1672:   double f1dim(double x); 
                   1673:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1674:              double *fc, double (*func)(double)); 
                   1675:   int j; 
                   1676:   double xx,xmin,bx,ax; 
                   1677:   double fx,fb,fa;
1.187     brouard  1678: 
1.203     brouard  1679: #ifdef LINMINORIGINAL
                   1680: #else
                   1681:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1682: #endif
                   1683:   
1.126     brouard  1684:   ncom=n; 
                   1685:   pcom=vector(1,n); 
                   1686:   xicom=vector(1,n); 
                   1687:   nrfunc=func; 
                   1688:   for (j=1;j<=n;j++) { 
                   1689:     pcom[j]=p[j]; 
1.202     brouard  1690:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1691:   } 
1.187     brouard  1692: 
1.203     brouard  1693: #ifdef LINMINORIGINAL
                   1694:   xx=1.;
                   1695: #else
                   1696:   axs=0.0;
                   1697:   xxs=1.;
                   1698:   do{
                   1699:     xx= xxs;
                   1700: #endif
1.187     brouard  1701:     ax=0.;
                   1702:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1703:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1704:     /* 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))   */
                   1705:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1706:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1707:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1708:     /* 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  1709: #ifdef LINMINORIGINAL
                   1710: #else
                   1711:     if (fx != fx){
                   1712:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1713:        printf("|");
                   1714:        fprintf(ficlog,"|");
                   1715: #ifdef DEBUGLINMIN
                   1716:        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);
                   1717: #endif
                   1718:     }
                   1719:   }while(fx != fx);
                   1720: #endif
                   1721:   
1.191     brouard  1722: #ifdef DEBUGLINMIN
                   1723:   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  1724:   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  1725: #endif
1.187     brouard  1726:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1727:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1728:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1729:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1730:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1731: #ifdef DEBUG
                   1732:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1733:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1734: #endif
1.191     brouard  1735: #ifdef DEBUGLINMIN
                   1736:   printf("linmin end ");
1.202     brouard  1737:   fprintf(ficlog,"linmin end ");
1.191     brouard  1738: #endif
1.126     brouard  1739:   for (j=1;j<=n;j++) { 
1.203     brouard  1740: #ifdef LINMINORIGINAL
                   1741:     xi[j] *= xmin; 
                   1742: #else
                   1743: #ifdef DEBUGLINMIN
                   1744:     if(xxs <1.0)
                   1745:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1746: #endif
                   1747:     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) */
                   1748: #ifdef DEBUGLINMIN
                   1749:     if(xxs <1.0)
                   1750:       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 );
                   1751: #endif
                   1752: #endif
1.187     brouard  1753:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1754:   } 
1.191     brouard  1755: #ifdef DEBUGLINMIN
1.203     brouard  1756:   printf("\n");
1.191     brouard  1757:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1758:   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  1759:   for (j=1;j<=n;j++) { 
1.202     brouard  1760:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1761:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1762:     if(j % ncovmodel == 0){
1.191     brouard  1763:       printf("\n");
1.202     brouard  1764:       fprintf(ficlog,"\n");
                   1765:     }
1.191     brouard  1766:   }
1.203     brouard  1767: #else
1.191     brouard  1768: #endif
1.126     brouard  1769:   free_vector(xicom,1,n); 
                   1770:   free_vector(pcom,1,n); 
                   1771: } 
                   1772: 
                   1773: 
                   1774: /*************** powell ************************/
1.162     brouard  1775: /*
                   1776: Minimization of a function func of n variables. Input consists of an initial starting point
                   1777: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1778: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1779: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1780: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1781: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1782:  */
1.126     brouard  1783: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1784:            double (*func)(double [])) 
                   1785: { 
                   1786:   void linmin(double p[], double xi[], int n, double *fret, 
                   1787:              double (*func)(double [])); 
                   1788:   int i,ibig,j; 
                   1789:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1790:   double directest;
1.126     brouard  1791:   double fp,fptt;
                   1792:   double *xits;
                   1793:   int niterf, itmp;
                   1794: 
                   1795:   pt=vector(1,n); 
                   1796:   ptt=vector(1,n); 
                   1797:   xit=vector(1,n); 
                   1798:   xits=vector(1,n); 
                   1799:   *fret=(*func)(p); 
                   1800:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1801:   rcurr_time = time(NULL);  
1.126     brouard  1802:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1803:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1804:     ibig=0; 
                   1805:     del=0.0; 
1.157     brouard  1806:     rlast_time=rcurr_time;
                   1807:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1808:     rcurr_time = time(NULL);  
                   1809:     curr_time = *localtime(&rcurr_time);
                   1810:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1811:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1812: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1813:     for (i=1;i<=n;i++) {
1.126     brouard  1814:       printf(" %d %.12f",i, p[i]);
                   1815:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1816:       fprintf(ficrespow," %.12lf", p[i]);
                   1817:     }
                   1818:     printf("\n");
                   1819:     fprintf(ficlog,"\n");
                   1820:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1821:     if(*iter <=3){
1.157     brouard  1822:       tml = *localtime(&rcurr_time);
                   1823:       strcpy(strcurr,asctime(&tml));
                   1824:       rforecast_time=rcurr_time; 
1.126     brouard  1825:       itmp = strlen(strcurr);
                   1826:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1827:        strcurr[itmp-1]='\0';
1.162     brouard  1828:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1829:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1830:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1831:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1832:        forecast_time = *localtime(&rforecast_time);
                   1833:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1834:        itmp = strlen(strfor);
                   1835:        if(strfor[itmp-1]=='\n')
                   1836:        strfor[itmp-1]='\0';
1.157     brouard  1837:        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);
                   1838:        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  1839:       }
                   1840:     }
1.187     brouard  1841:     for (i=1;i<=n;i++) { /* For each direction i */
                   1842:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1843:       fptt=(*fret); 
                   1844: #ifdef DEBUG
1.203     brouard  1845:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1846:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1847: #endif
1.203     brouard  1848:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1849:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1850:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1851:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1852:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1853:        /* because that direction will be replaced unless the gain del is small */
                   1854:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1855:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1856:        /* with the new direction. */
1.126     brouard  1857:        del=fabs(fptt-(*fret)); 
                   1858:        ibig=i; 
                   1859:       } 
                   1860: #ifdef DEBUG
                   1861:       printf("%d %.12e",i,(*fret));
                   1862:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1863:       for (j=1;j<=n;j++) {
                   1864:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1865:        printf(" x(%d)=%.12e",j,xit[j]);
                   1866:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1867:       }
                   1868:       for(j=1;j<=n;j++) {
1.162     brouard  1869:        printf(" p(%d)=%.12e",j,p[j]);
                   1870:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1871:       }
                   1872:       printf("\n");
                   1873:       fprintf(ficlog,"\n");
                   1874: #endif
1.187     brouard  1875:     } /* end loop on each direction i */
                   1876:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1877:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1878:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1879:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1880:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1881:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1882:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1883:       /* decreased of more than 3.84  */
                   1884:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1885:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1886:       /* By adding 10 parameters more the gain should be 18.31 */
                   1887: 
                   1888:       /* Starting the program with initial values given by a former maximization will simply change */
                   1889:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1890:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1891:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1892: #ifdef DEBUG
                   1893:       int k[2],l;
                   1894:       k[0]=1;
                   1895:       k[1]=-1;
                   1896:       printf("Max: %.12e",(*func)(p));
                   1897:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1898:       for (j=1;j<=n;j++) {
                   1899:        printf(" %.12e",p[j]);
                   1900:        fprintf(ficlog," %.12e",p[j]);
                   1901:       }
                   1902:       printf("\n");
                   1903:       fprintf(ficlog,"\n");
                   1904:       for(l=0;l<=1;l++) {
                   1905:        for (j=1;j<=n;j++) {
                   1906:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1907:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1908:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1909:        }
                   1910:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1911:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1912:       }
                   1913: #endif
                   1914: 
                   1915: 
                   1916:       free_vector(xit,1,n); 
                   1917:       free_vector(xits,1,n); 
                   1918:       free_vector(ptt,1,n); 
                   1919:       free_vector(pt,1,n); 
                   1920:       return; 
1.192     brouard  1921:     } /* enough precision */ 
1.126     brouard  1922:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1923:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1924:       ptt[j]=2.0*p[j]-pt[j]; 
                   1925:       xit[j]=p[j]-pt[j]; 
                   1926:       pt[j]=p[j]; 
                   1927:     } 
1.181     brouard  1928:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1929: #ifdef POWELLF1F3
                   1930: #else
1.161     brouard  1931:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1932: #endif
1.162     brouard  1933:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1934:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1935:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1936:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1937:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1938:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1939:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1940: #ifdef NRCORIGINAL
                   1941:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1942: #else
                   1943:       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  1944:       t= t- del*SQR(fp-fptt);
1.183     brouard  1945: #endif
1.202     brouard  1946:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1947: #ifdef DEBUG
1.181     brouard  1948:       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);
                   1949:       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  1950:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1951:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1952:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1953:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1954:       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);
                   1955:       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);
                   1956: #endif
1.183     brouard  1957: #ifdef POWELLORIGINAL
                   1958:       if (t < 0.0) { /* Then we use it for new direction */
                   1959: #else
1.182     brouard  1960:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1961:        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  1962:         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  1963:         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  1964:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1965:       } 
1.181     brouard  1966:       if (directest < 0.0) { /* Then we use it for new direction */
                   1967: #endif
1.191     brouard  1968: #ifdef DEBUGLINMIN
                   1969:        printf("Before linmin in direction P%d-P0\n",n);
                   1970:        for (j=1;j<=n;j++) { 
1.202     brouard  1971:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1972:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1973:          if(j % ncovmodel == 0){
1.191     brouard  1974:            printf("\n");
1.202     brouard  1975:            fprintf(ficlog,"\n");
                   1976:          }
1.191     brouard  1977:        }
                   1978: #endif
1.187     brouard  1979:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1980: #ifdef DEBUGLINMIN
                   1981:        for (j=1;j<=n;j++) { 
                   1982:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1983:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1984:          if(j % ncovmodel == 0){
1.191     brouard  1985:            printf("\n");
1.202     brouard  1986:            fprintf(ficlog,"\n");
                   1987:          }
1.191     brouard  1988:        }
                   1989: #endif
1.126     brouard  1990:        for (j=1;j<=n;j++) { 
1.181     brouard  1991:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1992:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1993:        }
1.181     brouard  1994:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1995:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1996: 
1.126     brouard  1997: #ifdef DEBUG
1.164     brouard  1998:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1999:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2000:        for(j=1;j<=n;j++){
                   2001:          printf(" %.12e",xit[j]);
                   2002:          fprintf(ficlog," %.12e",xit[j]);
                   2003:        }
                   2004:        printf("\n");
                   2005:        fprintf(ficlog,"\n");
                   2006: #endif
1.192     brouard  2007:       } /* end of t or directest negative */
                   2008: #ifdef POWELLF1F3
                   2009: #else
1.162     brouard  2010:     } /* end if (fptt < fp)  */
1.192     brouard  2011: #endif
                   2012:   } /* loop iteration */ 
1.126     brouard  2013: } 
                   2014: 
                   2015: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2016: 
1.203     brouard  2017: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2018: {
                   2019:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  2020:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2021:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2022:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2023:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2024:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2025:   /* Initial matrix pimij */
                   2026:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2027:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2028:   /*  0,                   0                  , 1} */
                   2029:   /*
                   2030:    * and after some iteration: */
                   2031:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2032:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2033:   /*  0,                   0                  , 1} */
                   2034:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2035:   /* {0.51571254859325999, 0.4842874514067399, */
                   2036:   /*  0.51326036147820708, 0.48673963852179264} */
                   2037:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2038: 
1.126     brouard  2039:   int i, ii,j,k;
1.209     brouard  2040:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2041:   /* double **matprod2(); */ /* test */
1.131     brouard  2042:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2043:   double **newm;
1.209     brouard  2044:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2045:   int ncvloop=0;
1.169     brouard  2046:   
1.209     brouard  2047:   min=vector(1,nlstate);
                   2048:   max=vector(1,nlstate);
                   2049:   meandiff=vector(1,nlstate);
                   2050: 
1.126     brouard  2051:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2052:     for (j=1;j<=nlstate+ndeath;j++){
                   2053:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2054:     }
1.169     brouard  2055:   
                   2056:   cov[1]=1.;
                   2057:   
                   2058:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2059:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2060:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2061:     ncvloop++;
1.126     brouard  2062:     newm=savm;
                   2063:     /* Covariates have to be included here again */
1.138     brouard  2064:     cov[2]=agefin;
1.187     brouard  2065:     if(nagesqr==1)
                   2066:       cov[3]= agefin*agefin;;
1.138     brouard  2067:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2068:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2069:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2070:       /* 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  2071:     }
1.186     brouard  2072:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2073:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2074:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2075:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2076:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2077:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2078:     
                   2079:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2080:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2081:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2082:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2083:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2084:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2085:     
1.126     brouard  2086:     savm=oldm;
                   2087:     oldm=newm;
1.209     brouard  2088: 
                   2089:     for(j=1; j<=nlstate; j++){
                   2090:       max[j]=0.;
                   2091:       min[j]=1.;
                   2092:     }
                   2093:     for(i=1;i<=nlstate;i++){
                   2094:       sumnew=0;
                   2095:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2096:       for(j=1; j<=nlstate; j++){ 
                   2097:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2098:        max[j]=FMAX(max[j],prlim[i][j]);
                   2099:        min[j]=FMIN(min[j],prlim[i][j]);
                   2100:       }
                   2101:     }
                   2102: 
1.126     brouard  2103:     maxmax=0.;
1.209     brouard  2104:     for(j=1; j<=nlstate; j++){
                   2105:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2106:       maxmax=FMAX(maxmax,meandiff[j]);
                   2107:       /* 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  2108:     } /* j loop */
1.203     brouard  2109:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2110:     /* 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  2111:     if(maxmax < ftolpl){
1.209     brouard  2112:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2113:       free_vector(min,1,nlstate);
                   2114:       free_vector(max,1,nlstate);
                   2115:       free_vector(meandiff,1,nlstate);
1.126     brouard  2116:       return prlim;
                   2117:     }
1.169     brouard  2118:   } /* age loop */
1.208     brouard  2119:     /* After some age loop it doesn't converge */
1.209     brouard  2120:   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  2121: 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  2122:   /* 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); */
                   2123:   free_vector(min,1,nlstate);
                   2124:   free_vector(max,1,nlstate);
                   2125:   free_vector(meandiff,1,nlstate);
1.208     brouard  2126:   
1.169     brouard  2127:   return prlim; /* should not reach here */
1.126     brouard  2128: }
                   2129: 
                   2130: /*************** transition probabilities ***************/ 
                   2131: 
                   2132: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2133: {
1.138     brouard  2134:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2135:      computes the probability to be observed in state j being in state i by appying the
                   2136:      model to the ncovmodel covariates (including constant and age).
                   2137:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2138:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2139:      ncth covariate in the global vector x is given by the formula:
                   2140:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2141:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2142:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2143:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2144:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2145:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2146:   */
                   2147:   double s1, lnpijopii;
1.126     brouard  2148:   /*double t34;*/
1.164     brouard  2149:   int i,j, nc, ii, jj;
1.126     brouard  2150: 
                   2151:     for(i=1; i<= nlstate; i++){
                   2152:       for(j=1; j<i;j++){
1.138     brouard  2153:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2154:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2155:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2156: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2157:        }
1.138     brouard  2158:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2159: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2160:       }
                   2161:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2162:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2163:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2164:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2165: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2166:        }
1.138     brouard  2167:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2168:       }
                   2169:     }
                   2170:     
                   2171:     for(i=1; i<= nlstate; i++){
                   2172:       s1=0;
1.131     brouard  2173:       for(j=1; j<i; j++){
1.138     brouard  2174:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2175:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2176:       }
                   2177:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2178:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2179:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2180:       }
1.138     brouard  2181:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2182:       ps[i][i]=1./(s1+1.);
1.138     brouard  2183:       /* Computing other pijs */
1.126     brouard  2184:       for(j=1; j<i; j++)
                   2185:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2186:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2187:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2188:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2189:     } /* end i */
                   2190:     
                   2191:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2192:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2193:        ps[ii][jj]=0;
                   2194:        ps[ii][ii]=1;
                   2195:       }
                   2196:     }
                   2197:     
1.145     brouard  2198:     
                   2199:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2200:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2201:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2202:     /*   } */
                   2203:     /*   printf("\n "); */
                   2204:     /* } */
                   2205:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2206:     /*
1.126     brouard  2207:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2208:       goto end;*/
                   2209:     return ps;
                   2210: }
                   2211: 
                   2212: /**************** Product of 2 matrices ******************/
                   2213: 
1.145     brouard  2214: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2215: {
                   2216:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2217:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2218:   /* in, b, out are matrice of pointers which should have been initialized 
                   2219:      before: only the contents of out is modified. The function returns
                   2220:      a pointer to pointers identical to out */
1.145     brouard  2221:   int i, j, k;
1.126     brouard  2222:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2223:     for(k=ncolol; k<=ncoloh; k++){
                   2224:       out[i][k]=0.;
                   2225:       for(j=ncl; j<=nch; j++)
                   2226:        out[i][k] +=in[i][j]*b[j][k];
                   2227:     }
1.126     brouard  2228:   return out;
                   2229: }
                   2230: 
                   2231: 
                   2232: /************* Higher Matrix Product ***************/
                   2233: 
                   2234: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2235: {
                   2236:   /* Computes the transition matrix starting at age 'age' over 
                   2237:      'nhstepm*hstepm*stepm' months (i.e. until
                   2238:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2239:      nhstepm*hstepm matrices. 
                   2240:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2241:      (typically every 2 years instead of every month which is too big 
                   2242:      for the memory).
                   2243:      Model is determined by parameters x and covariates have to be 
                   2244:      included manually here. 
                   2245: 
                   2246:      */
                   2247: 
                   2248:   int i, j, d, h, k;
1.131     brouard  2249:   double **out, cov[NCOVMAX+1];
1.126     brouard  2250:   double **newm;
1.187     brouard  2251:   double agexact;
1.214   ! brouard  2252:   double agebegin, ageend;
1.126     brouard  2253: 
                   2254:   /* Hstepm could be zero and should return the unit matrix */
                   2255:   for (i=1;i<=nlstate+ndeath;i++)
                   2256:     for (j=1;j<=nlstate+ndeath;j++){
                   2257:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2258:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2259:     }
                   2260:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2261:   for(h=1; h <=nhstepm; h++){
                   2262:     for(d=1; d <=hstepm; d++){
                   2263:       newm=savm;
                   2264:       /* Covariates have to be included here again */
                   2265:       cov[1]=1.;
1.214   ! brouard  2266:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2267:       cov[2]=agexact;
                   2268:       if(nagesqr==1)
                   2269:        cov[3]= agexact*agexact;
1.131     brouard  2270:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2271:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2272:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2273:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2274:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2275:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2276:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2277:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2278:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2279:        /* 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  2280: 
                   2281: 
                   2282:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2283:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2284:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2285:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2286:       savm=oldm;
                   2287:       oldm=newm;
                   2288:     }
                   2289:     for(i=1; i<=nlstate+ndeath; i++)
                   2290:       for(j=1;j<=nlstate+ndeath;j++) {
                   2291:        po[i][j][h]=newm[i][j];
1.128     brouard  2292:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2293:       }
1.128     brouard  2294:     /*printf("h=%d ",h);*/
1.126     brouard  2295:   } /* end h */
1.128     brouard  2296: /*     printf("\n H=%d \n",h); */
1.126     brouard  2297:   return po;
                   2298: }
                   2299: 
1.162     brouard  2300: #ifdef NLOPT
                   2301:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2302:   double fret;
                   2303:   double *xt;
                   2304:   int j;
                   2305:   myfunc_data *d2 = (myfunc_data *) pd;
                   2306: /* xt = (p1-1); */
                   2307:   xt=vector(1,n); 
                   2308:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2309: 
                   2310:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2311:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2312:   printf("Function = %.12lf ",fret);
                   2313:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2314:   printf("\n");
                   2315:  free_vector(xt,1,n);
                   2316:   return fret;
                   2317: }
                   2318: #endif
1.126     brouard  2319: 
                   2320: /*************** log-likelihood *************/
                   2321: double func( double *x)
                   2322: {
                   2323:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2324:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2325:   double **out;
                   2326:   double sw; /* Sum of weights */
                   2327:   double lli; /* Individual log likelihood */
                   2328:   int s1, s2;
                   2329:   double bbh, survp;
                   2330:   long ipmx;
1.187     brouard  2331:   double agexact;
1.126     brouard  2332:   /*extern weight */
                   2333:   /* We are differentiating ll according to initial status */
                   2334:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2335:   /*for(i=1;i<imx;i++) 
                   2336:     printf(" %d\n",s[4][i]);
                   2337:   */
1.162     brouard  2338: 
                   2339:   ++countcallfunc;
                   2340: 
1.126     brouard  2341:   cov[1]=1.;
                   2342: 
                   2343:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2344: 
                   2345:   if(mle==1){
                   2346:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2347:       /* Computes the values of the ncovmodel covariates of the model
                   2348:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2349:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2350:         to be observed in j being in i according to the model.
                   2351:        */
1.145     brouard  2352:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2353:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2354:       }
1.137     brouard  2355:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2356:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2357:         has been calculated etc */
1.126     brouard  2358:       for(mi=1; mi<= wav[i]-1; mi++){
                   2359:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2360:          for (j=1;j<=nlstate+ndeath;j++){
                   2361:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2362:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2363:          }
                   2364:        for(d=0; d<dh[mi][i]; d++){
                   2365:          newm=savm;
1.187     brouard  2366:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2367:          cov[2]=agexact;
                   2368:          if(nagesqr==1)
                   2369:            cov[3]= agexact*agexact;
1.126     brouard  2370:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2371:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2372:          }
                   2373:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2374:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2375:          savm=oldm;
                   2376:          oldm=newm;
                   2377:        } /* end mult */
                   2378:       
                   2379:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2380:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2381:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2382:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2383:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2384:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2385:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2386:         * probability in order to take into account the bias as a fraction of the way
                   2387:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2388:         * -stepm/2 to stepm/2 .
                   2389:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2390:         * For stepm > 1 the results are less biased than in previous versions. 
                   2391:         */
                   2392:        s1=s[mw[mi][i]][i];
                   2393:        s2=s[mw[mi+1][i]][i];
                   2394:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2395:        /* bias bh is positive if real duration
                   2396:         * is higher than the multiple of stepm and negative otherwise.
                   2397:         */
                   2398:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2399:        if( s2 > nlstate){ 
                   2400:          /* i.e. if s2 is a death state and if the date of death is known 
                   2401:             then the contribution to the likelihood is the probability to 
                   2402:             die between last step unit time and current  step unit time, 
                   2403:             which is also equal to probability to die before dh 
                   2404:             minus probability to die before dh-stepm . 
                   2405:             In version up to 0.92 likelihood was computed
                   2406:        as if date of death was unknown. Death was treated as any other
                   2407:        health state: the date of the interview describes the actual state
                   2408:        and not the date of a change in health state. The former idea was
                   2409:        to consider that at each interview the state was recorded
                   2410:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2411:        introduced the exact date of death then we should have modified
                   2412:        the contribution of an exact death to the likelihood. This new
                   2413:        contribution is smaller and very dependent of the step unit
                   2414:        stepm. It is no more the probability to die between last interview
                   2415:        and month of death but the probability to survive from last
                   2416:        interview up to one month before death multiplied by the
                   2417:        probability to die within a month. Thanks to Chris
                   2418:        Jackson for correcting this bug.  Former versions increased
                   2419:        mortality artificially. The bad side is that we add another loop
                   2420:        which slows down the processing. The difference can be up to 10%
                   2421:        lower mortality.
                   2422:          */
1.183     brouard  2423:        /* If, at the beginning of the maximization mostly, the
                   2424:           cumulative probability or probability to be dead is
                   2425:           constant (ie = 1) over time d, the difference is equal to
                   2426:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2427:           s1 at precedent wave, to be dead a month before current
                   2428:           wave is equal to probability, being at state s1 at
                   2429:           precedent wave, to be dead at mont of the current
                   2430:           wave. Then the observed probability (that this person died)
                   2431:           is null according to current estimated parameter. In fact,
                   2432:           it should be very low but not zero otherwise the log go to
                   2433:           infinity.
                   2434:        */
                   2435: /* #ifdef INFINITYORIGINAL */
                   2436: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2437: /* #else */
                   2438: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2439: /*         lli=log(mytinydouble); */
                   2440: /*       else */
                   2441: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2442: /* #endif */
                   2443:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2444: 
                   2445:        } else if  (s2==-2) {
                   2446:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2447:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2448:          /*survp += out[s1][j]; */
                   2449:          lli= log(survp);
                   2450:        }
                   2451:        
                   2452:        else if  (s2==-4) { 
                   2453:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2454:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2455:          lli= log(survp); 
                   2456:        } 
                   2457: 
                   2458:        else if  (s2==-5) { 
                   2459:          for (j=1,survp=0. ; j<=2; j++)  
                   2460:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2461:          lli= log(survp); 
                   2462:        } 
                   2463:        
                   2464:        else{
                   2465:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2466:          /*  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 */
                   2467:        } 
                   2468:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2469:        /*if(lli ==000.0)*/
                   2470:        /*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); */
                   2471:        ipmx +=1;
                   2472:        sw += weight[i];
                   2473:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2474:        /* if (lli < log(mytinydouble)){ */
                   2475:        /*   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); */
                   2476:        /*   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]); */
                   2477:        /* } */
1.126     brouard  2478:       } /* end of wave */
                   2479:     } /* end of individual */
                   2480:   }  else if(mle==2){
                   2481:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2482:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2483:       for(mi=1; mi<= wav[i]-1; mi++){
                   2484:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2485:          for (j=1;j<=nlstate+ndeath;j++){
                   2486:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2487:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2488:          }
                   2489:        for(d=0; d<=dh[mi][i]; d++){
                   2490:          newm=savm;
1.187     brouard  2491:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2492:          cov[2]=agexact;
                   2493:          if(nagesqr==1)
                   2494:            cov[3]= agexact*agexact;
1.126     brouard  2495:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2496:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2497:          }
                   2498:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2499:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2500:          savm=oldm;
                   2501:          oldm=newm;
                   2502:        } /* end mult */
                   2503:       
                   2504:        s1=s[mw[mi][i]][i];
                   2505:        s2=s[mw[mi+1][i]][i];
                   2506:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2507:        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 */
                   2508:        ipmx +=1;
                   2509:        sw += weight[i];
                   2510:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2511:       } /* end of wave */
                   2512:     } /* end of individual */
                   2513:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2514:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2515:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2516:       for(mi=1; mi<= wav[i]-1; mi++){
                   2517:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2518:          for (j=1;j<=nlstate+ndeath;j++){
                   2519:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2520:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2521:          }
                   2522:        for(d=0; d<dh[mi][i]; d++){
                   2523:          newm=savm;
1.187     brouard  2524:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2525:          cov[2]=agexact;
                   2526:          if(nagesqr==1)
                   2527:            cov[3]= agexact*agexact;
1.126     brouard  2528:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2529:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2530:          }
                   2531:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2532:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2533:          savm=oldm;
                   2534:          oldm=newm;
                   2535:        } /* end mult */
                   2536:       
                   2537:        s1=s[mw[mi][i]][i];
                   2538:        s2=s[mw[mi+1][i]][i];
                   2539:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2540:        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 */
                   2541:        ipmx +=1;
                   2542:        sw += weight[i];
                   2543:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2544:       } /* end of wave */
                   2545:     } /* end of individual */
                   2546:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2547:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2548:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2549:       for(mi=1; mi<= wav[i]-1; mi++){
                   2550:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2551:          for (j=1;j<=nlstate+ndeath;j++){
                   2552:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2553:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2554:          }
                   2555:        for(d=0; d<dh[mi][i]; d++){
                   2556:          newm=savm;
1.187     brouard  2557:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2558:          cov[2]=agexact;
                   2559:          if(nagesqr==1)
                   2560:            cov[3]= agexact*agexact;
1.126     brouard  2561:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2562:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2563:          }
                   2564:        
                   2565:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2566:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2567:          savm=oldm;
                   2568:          oldm=newm;
                   2569:        } /* end mult */
                   2570:       
                   2571:        s1=s[mw[mi][i]][i];
                   2572:        s2=s[mw[mi+1][i]][i];
                   2573:        if( s2 > nlstate){ 
                   2574:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2575:        }else{
                   2576:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2577:        }
                   2578:        ipmx +=1;
                   2579:        sw += weight[i];
                   2580:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2581: /*     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]); */
                   2582:       } /* end of wave */
                   2583:     } /* end of individual */
                   2584:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2585:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2586:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2587:       for(mi=1; mi<= wav[i]-1; mi++){
                   2588:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2589:          for (j=1;j<=nlstate+ndeath;j++){
                   2590:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2591:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2592:          }
                   2593:        for(d=0; d<dh[mi][i]; d++){
                   2594:          newm=savm;
1.187     brouard  2595:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2596:          cov[2]=agexact;
                   2597:          if(nagesqr==1)
                   2598:            cov[3]= agexact*agexact;
1.126     brouard  2599:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2600:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2601:          }
                   2602:        
                   2603:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2604:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2605:          savm=oldm;
                   2606:          oldm=newm;
                   2607:        } /* end mult */
                   2608:       
                   2609:        s1=s[mw[mi][i]][i];
                   2610:        s2=s[mw[mi+1][i]][i];
                   2611:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2612:        ipmx +=1;
                   2613:        sw += weight[i];
                   2614:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2615:        /*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]);*/
                   2616:       } /* end of wave */
                   2617:     } /* end of individual */
                   2618:   } /* End of if */
                   2619:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2620:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2621:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2622:   return -l;
                   2623: }
                   2624: 
                   2625: /*************** log-likelihood *************/
                   2626: double funcone( double *x)
                   2627: {
                   2628:   /* Same as likeli but slower because of a lot of printf and if */
                   2629:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2630:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2631:   double **out;
                   2632:   double lli; /* Individual log likelihood */
                   2633:   double llt;
                   2634:   int s1, s2;
                   2635:   double bbh, survp;
1.187     brouard  2636:   double agexact;
1.214   ! brouard  2637:   double agebegin, ageend;
1.126     brouard  2638:   /*extern weight */
                   2639:   /* We are differentiating ll according to initial status */
                   2640:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2641:   /*for(i=1;i<imx;i++) 
                   2642:     printf(" %d\n",s[4][i]);
                   2643:   */
                   2644:   cov[1]=1.;
                   2645: 
                   2646:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2647: 
                   2648:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2649:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2650:     for(mi=1; mi<= wav[i]-1; mi++){
                   2651:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2652:        for (j=1;j<=nlstate+ndeath;j++){
                   2653:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2654:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2655:        }
1.214   ! brouard  2656:       
        !          2657:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
        !          2658:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
        !          2659:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
        !          2660:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          2661:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  2662:        newm=savm;
1.187     brouard  2663:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2664:        cov[2]=agexact;
                   2665:        if(nagesqr==1)
                   2666:          cov[3]= agexact*agexact;
1.126     brouard  2667:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2668:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2669:        }
1.187     brouard  2670: 
1.145     brouard  2671:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2672:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2673:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2674:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2675:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2676:        savm=oldm;
                   2677:        oldm=newm;
                   2678:       } /* end mult */
                   2679:       
                   2680:       s1=s[mw[mi][i]][i];
                   2681:       s2=s[mw[mi+1][i]][i];
                   2682:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2683:       /* bias is positive if real duration
                   2684:        * is higher than the multiple of stepm and negative otherwise.
                   2685:        */
                   2686:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2687:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2688:       } else if  (s2==-2) {
                   2689:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2690:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2691:        lli= log(survp);
                   2692:       }else if (mle==1){
                   2693:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2694:       } else if(mle==2){
                   2695:        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 */
                   2696:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2697:        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 */
                   2698:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2699:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2700:       } else{  /* mle=0 back to 1 */
                   2701:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2702:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2703:       } /* End of if */
                   2704:       ipmx +=1;
                   2705:       sw += weight[i];
                   2706:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2707:       /*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  2708:       if(globpr){
1.214   ! brouard  2709:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2710:  %11.6f %11.6f %11.6f ", \
1.214   ! brouard  2711:                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  2712:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2713:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2714:          llt +=ll[k]*gipmx/gsw;
                   2715:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2716:        }
                   2717:        fprintf(ficresilk," %10.6f\n", -llt);
                   2718:       }
                   2719:     } /* end of wave */
                   2720:   } /* end of individual */
                   2721:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2722:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2723:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2724:   if(globpr==0){ /* First time we count the contributions and weights */
                   2725:     gipmx=ipmx;
                   2726:     gsw=sw;
                   2727:   }
                   2728:   return -l;
                   2729: }
                   2730: 
                   2731: 
                   2732: /*************** function likelione ***********/
                   2733: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2734: {
                   2735:   /* This routine should help understanding what is done with 
                   2736:      the selection of individuals/waves and
                   2737:      to check the exact contribution to the likelihood.
                   2738:      Plotting could be done.
                   2739:    */
                   2740:   int k;
                   2741: 
                   2742:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2743:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2744:     strcat(fileresilk,fileresu);
1.126     brouard  2745:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2746:       printf("Problem with resultfile: %s\n", fileresilk);
                   2747:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2748:     }
1.214   ! brouard  2749:     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");
        !          2750:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2751:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2752:     for(k=1; k<=nlstate; k++) 
                   2753:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2754:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2755:   }
                   2756: 
                   2757:   *fretone=(*funcone)(p);
                   2758:   if(*globpri !=0){
                   2759:     fclose(ficresilk);
1.205     brouard  2760:     if (mle ==0)
                   2761:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2762:     else if(mle >=1)
                   2763:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2764:     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  2765:     
1.208     brouard  2766:       
                   2767:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  2768:       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  2769: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2770:     }
1.207     brouard  2771:     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  2772: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2773:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2774: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2775:     fflush(fichtm);
1.205     brouard  2776:   }
1.126     brouard  2777:   return;
                   2778: }
                   2779: 
                   2780: 
                   2781: /*********** Maximum Likelihood Estimation ***************/
                   2782: 
                   2783: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2784: {
1.165     brouard  2785:   int i,j, iter=0;
1.126     brouard  2786:   double **xi;
                   2787:   double fret;
                   2788:   double fretone; /* Only one call to likelihood */
                   2789:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2790: 
                   2791: #ifdef NLOPT
                   2792:   int creturn;
                   2793:   nlopt_opt opt;
                   2794:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2795:   double *lb;
                   2796:   double minf; /* the minimum objective value, upon return */
                   2797:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2798:   myfunc_data dinst, *d = &dinst;
                   2799: #endif
                   2800: 
                   2801: 
1.126     brouard  2802:   xi=matrix(1,npar,1,npar);
                   2803:   for (i=1;i<=npar;i++)
                   2804:     for (j=1;j<=npar;j++)
                   2805:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2806:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2807:   strcpy(filerespow,"POW_"); 
1.126     brouard  2808:   strcat(filerespow,fileres);
                   2809:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2810:     printf("Problem with resultfile: %s\n", filerespow);
                   2811:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2812:   }
                   2813:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2814:   for (i=1;i<=nlstate;i++)
                   2815:     for(j=1;j<=nlstate+ndeath;j++)
                   2816:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2817:   fprintf(ficrespow,"\n");
1.162     brouard  2818: #ifdef POWELL
1.126     brouard  2819:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2820: #endif
1.126     brouard  2821: 
1.162     brouard  2822: #ifdef NLOPT
                   2823: #ifdef NEWUOA
                   2824:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2825: #else
                   2826:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2827: #endif
                   2828:   lb=vector(0,npar-1);
                   2829:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2830:   nlopt_set_lower_bounds(opt, lb);
                   2831:   nlopt_set_initial_step1(opt, 0.1);
                   2832:   
                   2833:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2834:   d->function = func;
                   2835:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2836:   nlopt_set_min_objective(opt, myfunc, d);
                   2837:   nlopt_set_xtol_rel(opt, ftol);
                   2838:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2839:     printf("nlopt failed! %d\n",creturn); 
                   2840:   }
                   2841:   else {
                   2842:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2843:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2844:     iter=1; /* not equal */
                   2845:   }
                   2846:   nlopt_destroy(opt);
                   2847: #endif
1.126     brouard  2848:   free_matrix(xi,1,npar,1,npar);
                   2849:   fclose(ficrespow);
1.203     brouard  2850:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2851:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2852:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2853: 
                   2854: }
                   2855: 
                   2856: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2857: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2858: {
                   2859:   double  **a,**y,*x,pd;
1.203     brouard  2860:   /* double **hess; */
1.164     brouard  2861:   int i, j;
1.126     brouard  2862:   int *indx;
                   2863: 
                   2864:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2865:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2866:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2867:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2868:   double gompertz(double p[]);
1.203     brouard  2869:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2870: 
                   2871:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2872:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2873:   for (i=1;i<=npar;i++){
1.203     brouard  2874:     printf("%d-",i);fflush(stdout);
                   2875:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2876:    
                   2877:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2878:     
                   2879:     /*  printf(" %f ",p[i]);
                   2880:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2881:   }
                   2882:   
                   2883:   for (i=1;i<=npar;i++) {
                   2884:     for (j=1;j<=npar;j++)  {
                   2885:       if (j>i) { 
1.203     brouard  2886:        printf(".%d-%d",i,j);fflush(stdout);
                   2887:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2888:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2889:        
                   2890:        hess[j][i]=hess[i][j];    
                   2891:        /*printf(" %lf ",hess[i][j]);*/
                   2892:       }
                   2893:     }
                   2894:   }
                   2895:   printf("\n");
                   2896:   fprintf(ficlog,"\n");
                   2897: 
                   2898:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2899:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2900:   
                   2901:   a=matrix(1,npar,1,npar);
                   2902:   y=matrix(1,npar,1,npar);
                   2903:   x=vector(1,npar);
                   2904:   indx=ivector(1,npar);
                   2905:   for (i=1;i<=npar;i++)
                   2906:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2907:   ludcmp(a,npar,indx,&pd);
                   2908: 
                   2909:   for (j=1;j<=npar;j++) {
                   2910:     for (i=1;i<=npar;i++) x[i]=0;
                   2911:     x[j]=1;
                   2912:     lubksb(a,npar,indx,x);
                   2913:     for (i=1;i<=npar;i++){ 
                   2914:       matcov[i][j]=x[i];
                   2915:     }
                   2916:   }
                   2917: 
                   2918:   printf("\n#Hessian matrix#\n");
                   2919:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2920:   for (i=1;i<=npar;i++) { 
                   2921:     for (j=1;j<=npar;j++) { 
1.203     brouard  2922:       printf("%.6e ",hess[i][j]);
                   2923:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2924:     }
                   2925:     printf("\n");
                   2926:     fprintf(ficlog,"\n");
                   2927:   }
                   2928: 
1.203     brouard  2929:   /* printf("\n#Covariance matrix#\n"); */
                   2930:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2931:   /* for (i=1;i<=npar;i++) {  */
                   2932:   /*   for (j=1;j<=npar;j++) {  */
                   2933:   /*     printf("%.6e ",matcov[i][j]); */
                   2934:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2935:   /*   } */
                   2936:   /*   printf("\n"); */
                   2937:   /*   fprintf(ficlog,"\n"); */
                   2938:   /* } */
                   2939: 
1.126     brouard  2940:   /* Recompute Inverse */
1.203     brouard  2941:   /* for (i=1;i<=npar;i++) */
                   2942:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2943:   /* ludcmp(a,npar,indx,&pd); */
                   2944: 
                   2945:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2946: 
                   2947:   /* for (j=1;j<=npar;j++) { */
                   2948:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2949:   /*   x[j]=1; */
                   2950:   /*   lubksb(a,npar,indx,x); */
                   2951:   /*   for (i=1;i<=npar;i++){  */
                   2952:   /*     y[i][j]=x[i]; */
                   2953:   /*     printf("%.3e ",y[i][j]); */
                   2954:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2955:   /*   } */
                   2956:   /*   printf("\n"); */
                   2957:   /*   fprintf(ficlog,"\n"); */
                   2958:   /* } */
                   2959: 
                   2960:   /* Verifying the inverse matrix */
                   2961: #ifdef DEBUGHESS
                   2962:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2963: 
1.203     brouard  2964:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2965:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2966: 
                   2967:   for (j=1;j<=npar;j++) {
                   2968:     for (i=1;i<=npar;i++){ 
1.203     brouard  2969:       printf("%.2f ",y[i][j]);
                   2970:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2971:     }
                   2972:     printf("\n");
                   2973:     fprintf(ficlog,"\n");
                   2974:   }
1.203     brouard  2975: #endif
1.126     brouard  2976: 
                   2977:   free_matrix(a,1,npar,1,npar);
                   2978:   free_matrix(y,1,npar,1,npar);
                   2979:   free_vector(x,1,npar);
                   2980:   free_ivector(indx,1,npar);
1.203     brouard  2981:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2982: 
                   2983: 
                   2984: }
                   2985: 
                   2986: /*************** hessian matrix ****************/
                   2987: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2988: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2989:   int i;
                   2990:   int l=1, lmax=20;
1.203     brouard  2991:   double k1,k2, res, fx;
1.132     brouard  2992:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2993:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2994:   int k=0,kmax=10;
                   2995:   double l1;
                   2996: 
                   2997:   fx=func(x);
                   2998:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2999:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3000:     l1=pow(10,l);
                   3001:     delts=delt;
                   3002:     for(k=1 ; k <kmax; k=k+1){
                   3003:       delt = delta*(l1*k);
                   3004:       p2[theta]=x[theta] +delt;
1.145     brouard  3005:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3006:       p2[theta]=x[theta]-delt;
                   3007:       k2=func(p2)-fx;
                   3008:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3009:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3010:       
1.203     brouard  3011: #ifdef DEBUGHESSII
1.126     brouard  3012:       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);
                   3013:       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);
                   3014: #endif
                   3015:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3016:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3017:        k=kmax;
                   3018:       }
                   3019:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3020:        k=kmax; l=lmax*10;
1.126     brouard  3021:       }
                   3022:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3023:        delts=delt;
                   3024:       }
1.203     brouard  3025:     } /* End loop k */
1.126     brouard  3026:   }
                   3027:   delti[theta]=delts;
                   3028:   return res; 
                   3029:   
                   3030: }
                   3031: 
1.203     brouard  3032: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3033: {
                   3034:   int i;
1.164     brouard  3035:   int l=1, lmax=20;
1.126     brouard  3036:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3037:   double p2[MAXPARM+1];
1.203     brouard  3038:   int k, kmax=1;
                   3039:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3040: 
                   3041:   int firstime=0;
1.203     brouard  3042:   
1.126     brouard  3043:   fx=func(x);
1.203     brouard  3044:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3045:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3046:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3047:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3048:     k1=func(p2)-fx;
                   3049:   
1.203     brouard  3050:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3051:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3052:     k2=func(p2)-fx;
                   3053:   
1.203     brouard  3054:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3055:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3056:     k3=func(p2)-fx;
                   3057:   
1.203     brouard  3058:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3059:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3060:     k4=func(p2)-fx;
1.203     brouard  3061:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3062:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3063:       firstime=1;
1.203     brouard  3064:       kmax=kmax+10;
1.208     brouard  3065:     }
                   3066:     if(kmax >=10 || firstime ==1){
1.203     brouard  3067:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3068:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3069:       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);
                   3070:       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);
                   3071:     }
                   3072: #ifdef DEBUGHESSIJ
                   3073:     v1=hess[thetai][thetai];
                   3074:     v2=hess[thetaj][thetaj];
                   3075:     cv12=res;
                   3076:     /* Computing eigen value of Hessian matrix */
                   3077:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3078:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3079:     if ((lc2 <0) || (lc1 <0) ){
                   3080:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3081:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3082:       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);
                   3083:       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);
                   3084:     }
1.126     brouard  3085: #endif
                   3086:   }
                   3087:   return res;
                   3088: }
                   3089: 
1.203     brouard  3090:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3091: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3092: /* { */
                   3093: /*   int i; */
                   3094: /*   int l=1, lmax=20; */
                   3095: /*   double k1,k2,k3,k4,res,fx; */
                   3096: /*   double p2[MAXPARM+1]; */
                   3097: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3098: /*   int k=0,kmax=10; */
                   3099: /*   double l1; */
                   3100:   
                   3101: /*   fx=func(x); */
                   3102: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3103: /*     l1=pow(10,l); */
                   3104: /*     delts=delt; */
                   3105: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3106: /*       delt = delti*(l1*k); */
                   3107: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3108: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3109: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3110: /*       k1=func(p2)-fx; */
                   3111:       
                   3112: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3113: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3114: /*       k2=func(p2)-fx; */
                   3115:       
                   3116: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3117: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3118: /*       k3=func(p2)-fx; */
                   3119:       
                   3120: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3121: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3122: /*       k4=func(p2)-fx; */
                   3123: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3124: /* #ifdef DEBUGHESSIJ */
                   3125: /*       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); */
                   3126: /*       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); */
                   3127: /* #endif */
                   3128: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3129: /*     k=kmax; */
                   3130: /*       } */
                   3131: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3132: /*     k=kmax; l=lmax*10; */
                   3133: /*       } */
                   3134: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3135: /*     delts=delt; */
                   3136: /*       } */
                   3137: /*     } /\* End loop k *\/ */
                   3138: /*   } */
                   3139: /*   delti[theta]=delts; */
                   3140: /*   return res;  */
                   3141: /* } */
                   3142: 
                   3143: 
1.126     brouard  3144: /************** Inverse of matrix **************/
                   3145: void ludcmp(double **a, int n, int *indx, double *d) 
                   3146: { 
                   3147:   int i,imax,j,k; 
                   3148:   double big,dum,sum,temp; 
                   3149:   double *vv; 
                   3150:  
                   3151:   vv=vector(1,n); 
                   3152:   *d=1.0; 
                   3153:   for (i=1;i<=n;i++) { 
                   3154:     big=0.0; 
                   3155:     for (j=1;j<=n;j++) 
                   3156:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3157:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3158:     vv[i]=1.0/big; 
                   3159:   } 
                   3160:   for (j=1;j<=n;j++) { 
                   3161:     for (i=1;i<j;i++) { 
                   3162:       sum=a[i][j]; 
                   3163:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3164:       a[i][j]=sum; 
                   3165:     } 
                   3166:     big=0.0; 
                   3167:     for (i=j;i<=n;i++) { 
                   3168:       sum=a[i][j]; 
                   3169:       for (k=1;k<j;k++) 
                   3170:        sum -= a[i][k]*a[k][j]; 
                   3171:       a[i][j]=sum; 
                   3172:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3173:        big=dum; 
                   3174:        imax=i; 
                   3175:       } 
                   3176:     } 
                   3177:     if (j != imax) { 
                   3178:       for (k=1;k<=n;k++) { 
                   3179:        dum=a[imax][k]; 
                   3180:        a[imax][k]=a[j][k]; 
                   3181:        a[j][k]=dum; 
                   3182:       } 
                   3183:       *d = -(*d); 
                   3184:       vv[imax]=vv[j]; 
                   3185:     } 
                   3186:     indx[j]=imax; 
                   3187:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3188:     if (j != n) { 
                   3189:       dum=1.0/(a[j][j]); 
                   3190:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3191:     } 
                   3192:   } 
                   3193:   free_vector(vv,1,n);  /* Doesn't work */
                   3194: ;
                   3195: } 
                   3196: 
                   3197: void lubksb(double **a, int n, int *indx, double b[]) 
                   3198: { 
                   3199:   int i,ii=0,ip,j; 
                   3200:   double sum; 
                   3201:  
                   3202:   for (i=1;i<=n;i++) { 
                   3203:     ip=indx[i]; 
                   3204:     sum=b[ip]; 
                   3205:     b[ip]=b[i]; 
                   3206:     if (ii) 
                   3207:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3208:     else if (sum) ii=i; 
                   3209:     b[i]=sum; 
                   3210:   } 
                   3211:   for (i=n;i>=1;i--) { 
                   3212:     sum=b[i]; 
                   3213:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3214:     b[i]=sum/a[i][i]; 
                   3215:   } 
                   3216: } 
                   3217: 
                   3218: void pstamp(FILE *fichier)
                   3219: {
1.196     brouard  3220:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3221: }
                   3222: 
                   3223: /************ Frequencies ********************/
1.214   ! brouard  3224: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
        !          3225:                  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
        !          3226:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.126     brouard  3227: {  /* Some frequencies */
                   3228:   
1.164     brouard  3229:   int i, m, jk, j1, bool, z1,j;
1.214   ! brouard  3230:   int mi; /* Effective wave */
1.126     brouard  3231:   int first;
                   3232:   double ***freq; /* Frequencies */
                   3233:   double *pp, **prop;
                   3234:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.214   ! brouard  3235:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
        !          3236:   double agebegin, ageend;
        !          3237:     
1.126     brouard  3238:   pp=vector(1,nlstate);
                   3239:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3240:   strcpy(fileresp,"P_");
                   3241:   strcat(fileresp,fileresu);
1.213     brouard  3242:   /*strcat(fileresphtm,fileresu);*/
1.126     brouard  3243:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3244:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3245:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3246:     exit(0);
                   3247:   }
1.214   ! brouard  3248: 
1.213     brouard  3249:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3250:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3251:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3252:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3253:     fflush(ficlog);
                   3254:     exit(70); 
                   3255:   }
1.214   ! brouard  3256:   else{
        !          3257:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
        !          3258: <hr size=\"2\" color=\"#EC5E5E\"> \n\
        !          3259: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
        !          3260:          fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        !          3261:   }
        !          3262:     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);
        !          3263:     
        !          3264:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
        !          3265:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
        !          3266:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
        !          3267:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
        !          3268:     fflush(ficlog);
        !          3269:     exit(70); 
        !          3270:   }
        !          3271:   else{
        !          3272:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
        !          3273: <hr size=\"2\" color=\"#EC5E5E\"> \n\
        !          3274: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
        !          3275:          fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        !          3276:   }
        !          3277:   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);
        !          3278: 
1.126     brouard  3279:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3280:   j1=0;
                   3281:   
                   3282:   j=cptcoveff;
                   3283:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3284: 
                   3285:   first=1;
                   3286: 
1.214   ! brouard  3287:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
1.126     brouard  3288:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3289:        scanf("%d", i);*/
                   3290:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3291:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3292:          for(m=iagemin; m <= iagemax+3; m++)
                   3293:            freq[i][jk][m]=0;
1.143     brouard  3294:       
                   3295:       for (i=1; i<=nlstate; i++)  
                   3296:        for(m=iagemin; m <= iagemax+3; m++)
                   3297:          prop[i][m]=0;
1.126     brouard  3298:       
                   3299:       dateintsum=0;
                   3300:       k2cpt=0;
1.214   ! brouard  3301:       for (i=1; i<=imx; i++) { /* For each individual i */
1.126     brouard  3302:        bool=1;
1.210     brouard  3303:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3304:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3305:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3306:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3307:               bool=0;
1.198     brouard  3308:               /* 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", 
                   3309:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3310:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3311:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3312:             } 
1.210     brouard  3313:        } /* cptcovn > 0 */
1.214   ! brouard  3314: 
1.126     brouard  3315:        if (bool==1){
1.214   ! brouard  3316:          /* for(m=firstpass; m<=lastpass; m++){ */
        !          3317:          for(mi=1; mi<wav[i];mi++){
        !          3318:            m=mw[mi][i];
        !          3319:            /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
        !          3320:               and mw[mi+1][i]. dh depends on stepm. */
        !          3321:            agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
        !          3322:            ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
        !          3323:            if(m >=firstpass && m <=lastpass){
        !          3324:              k2=anint[m][i]+(mint[m][i]/12.);
        !          3325:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
        !          3326:              if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
        !          3327:              if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
        !          3328:              if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
        !          3329:                prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
1.126     brouard  3330:              if (m<lastpass) {
1.214   ! brouard  3331:                /* if(s[m][i]==4 && s[m+1][i]==4) */
        !          3332:                /*   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
        !          3333:                if(s[m][i]==-1)
        !          3334:                  printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
        !          3335:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
        !          3336:                /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
        !          3337:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
1.126     brouard  3338:              }
1.214   ! brouard  3339:            }  
        !          3340:            if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
        !          3341:              dateintsum=dateintsum+k2;
        !          3342:              k2cpt++;
        !          3343:              /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
        !          3344:            }
        !          3345:            /*}*/
1.210     brouard  3346:          } /* end m */
                   3347:        } /* end bool */
                   3348:       } /* end i = 1 to imx */
1.126     brouard  3349:        
                   3350:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3351:       pstamp(ficresp);
                   3352:       if  (cptcovn>0) {
                   3353:        fprintf(ficresp, "\n#********** Variable "); 
1.214   ! brouard  3354:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
        !          3355:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.213     brouard  3356:        for (z1=1; z1<=cptcoveff; z1++){
                   3357:          fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3358:          fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214   ! brouard  3359:          fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.213     brouard  3360:        }
                   3361:          fprintf(ficresp, "**********\n#");
1.214   ! brouard  3362:        fprintf(ficresphtm, "**********</h3>\n");
        !          3363:        fprintf(ficresphtmfr, "**********</h3>\n");
1.143     brouard  3364:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3365:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214   ! brouard  3366:        fprintf(ficlog, "**********\n");
1.126     brouard  3367:       }
1.214   ! brouard  3368:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.213     brouard  3369:       for(i=1; i<=nlstate;i++) {
1.126     brouard  3370:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213     brouard  3371:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3372:       }
1.126     brouard  3373:       fprintf(ficresp, "\n");
1.213     brouard  3374:       fprintf(ficresphtm, "\n");
1.126     brouard  3375:       
1.214   ! brouard  3376:       /* Header of frequency table by age */
        !          3377:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
        !          3378:       fprintf(ficresphtmfr,"<th>Age</th> ");
        !          3379:       for(jk=-1; jk <=nlstate+ndeath; jk++){
        !          3380:        for(m=-1; m <=nlstate+ndeath; m++){
        !          3381:          if(jk!=0 && m!=0)
        !          3382:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
        !          3383:        }
        !          3384:       }
        !          3385:       fprintf(ficresphtmfr, "\n");
        !          3386:       
        !          3387:       /* For each age */
1.126     brouard  3388:       for(i=iagemin; i <= iagemax+3; i++){
1.213     brouard  3389:        fprintf(ficresphtm,"<tr>");
1.214   ! brouard  3390:        if(i==iagemax+1){
        !          3391:          fprintf(ficlog,"1");
        !          3392:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
        !          3393:        }else if(i==iagemax+2){
        !          3394:          fprintf(ficlog,"0");
        !          3395:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
        !          3396:        }else if(i==iagemax+3){
1.126     brouard  3397:          fprintf(ficlog,"Total");
1.214   ! brouard  3398:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.126     brouard  3399:        }else{
                   3400:          if(first==1){
                   3401:            first=0;
                   3402:            printf("See log file for details...\n");
                   3403:          }
1.214   ! brouard  3404:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
1.126     brouard  3405:          fprintf(ficlog,"Age %d", i);
                   3406:        }
                   3407:        for(jk=1; jk <=nlstate ; jk++){
                   3408:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3409:            pp[jk] += freq[jk][m][i]; 
                   3410:        }
                   3411:        for(jk=1; jk <=nlstate ; jk++){
                   3412:          for(m=-1, pos=0; m <=0 ; m++)
                   3413:            pos += freq[jk][m][i];
                   3414:          if(pp[jk]>=1.e-10){
                   3415:            if(first==1){
1.132     brouard  3416:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3417:            }
                   3418:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3419:          }else{
                   3420:            if(first==1)
                   3421:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3422:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3423:          }
                   3424:        }
                   3425: 
                   3426:        for(jk=1; jk <=nlstate ; jk++){
                   3427:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3428:            pp[jk] += freq[jk][m][i];
                   3429:        }       
                   3430:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3431:          pos += pp[jk];
                   3432:          posprop += prop[jk][i];
                   3433:        }
                   3434:        for(jk=1; jk <=nlstate ; jk++){
                   3435:          if(pos>=1.e-5){
                   3436:            if(first==1)
                   3437:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3438:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3439:          }else{
                   3440:            if(first==1)
                   3441:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3442:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3443:          }
                   3444:          if( i <= iagemax){
                   3445:            if(pos>=1.e-5){
                   3446:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213     brouard  3447:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.126     brouard  3448:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3449:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3450:            }
1.213     brouard  3451:            else{
1.126     brouard  3452:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213     brouard  3453:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
                   3454:            }
1.126     brouard  3455:          }
                   3456:        }
                   3457:        
1.214   ! brouard  3458:        for(jk=-1; jk <=nlstate+ndeath; jk++){
        !          3459:          for(m=-1; m <=nlstate+ndeath; m++){
        !          3460:            if(freq[jk][m][i] !=0 ) { /* minimizing output */
        !          3461:              if(first==1){
        !          3462:                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
        !          3463:              }
1.126     brouard  3464:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3465:            }
1.214   ! brouard  3466:            if(jk!=0 && m!=0)
        !          3467:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
        !          3468:          }
        !          3469:        }
        !          3470:        fprintf(ficresphtmfr,"</tr>\n ");
1.213     brouard  3471:        if(i <= iagemax){
1.126     brouard  3472:          fprintf(ficresp,"\n");
1.213     brouard  3473:          fprintf(ficresphtm,"</tr>\n");
                   3474:        }
1.126     brouard  3475:        if(first==1)
                   3476:          printf("Others in log...\n");
                   3477:        fprintf(ficlog,"\n");
1.210     brouard  3478:       } /* end loop i */
1.213     brouard  3479:       fprintf(ficresphtm,"</table>\n");
1.214   ! brouard  3480:       fprintf(ficresphtmfr,"</table>\n");
1.145     brouard  3481:       /*}*/
1.210     brouard  3482:   } /* end j1 */
1.126     brouard  3483:   dateintmean=dateintsum/k2cpt; 
                   3484:  
                   3485:   fclose(ficresp);
1.213     brouard  3486:   fclose(ficresphtm);
1.214   ! brouard  3487:   fclose(ficresphtmfr);
1.126     brouard  3488:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3489:   free_vector(pp,1,nlstate);
                   3490:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3491:   /* End of Freq */
                   3492: }
                   3493: 
                   3494: /************ Prevalence ********************/
                   3495: 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)
                   3496: {  
                   3497:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3498:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3499:      We still use firstpass and lastpass as another selection.
                   3500:   */
                   3501:  
1.164     brouard  3502:   int i, m, jk, j1, bool, z1,j;
1.214   ! brouard  3503:   int mi; /* Effective wave */
        !          3504:   int iage;
        !          3505:   double agebegin, ageend;
1.164     brouard  3506: 
                   3507:   double **prop;
                   3508:   double posprop; 
1.126     brouard  3509:   double  y2; /* in fractional years */
                   3510:   int iagemin, iagemax;
1.145     brouard  3511:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3512: 
                   3513:   iagemin= (int) agemin;
                   3514:   iagemax= (int) agemax;
                   3515:   /*pp=vector(1,nlstate);*/
                   3516:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3517:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3518:   j1=0;
                   3519:   
1.145     brouard  3520:   /*j=cptcoveff;*/
1.126     brouard  3521:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3522:   
1.145     brouard  3523:   first=1;
                   3524:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
1.214   ! brouard  3525:     for (i=1; i<=nlstate; i++)  
        !          3526:       for(iage=iagemin; iage <= iagemax+3; iage++)
        !          3527:        prop[i][iage]=0.0;
        !          3528:     
        !          3529:     for (i=1; i<=imx; i++) { /* Each individual */
        !          3530:       bool=1;
        !          3531:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          3532:        for (z1=1; z1<=cptcoveff; z1++) 
        !          3533:          if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
        !          3534:            bool=0;
        !          3535:       } 
        !          3536:       if (bool==1) { 
        !          3537:        /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
        !          3538:        for(mi=1; mi<wav[i];mi++){
        !          3539:          m=mw[mi][i];
        !          3540:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
        !          3541:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
        !          3542:          if(m >=firstpass && m <=lastpass){
1.126     brouard  3543:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3544:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3545:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3546:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3547:              if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
1.214   ! brouard  3548:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
1.126     brouard  3549:                /*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]]);*/
1.214   ! brouard  3550:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
        !          3551:                prop[s[m][i]][iagemax+3] += weight[i]; 
        !          3552:              } /* end valid statuses */ 
        !          3553:            } /* end selection of dates */
1.126     brouard  3554:          } /* end selection of waves */
1.214   ! brouard  3555:        } /* end effective waves */
        !          3556:       } /* end bool */
        !          3557:     }
        !          3558:     for(i=iagemin; i <= iagemax+3; i++){  
        !          3559:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
        !          3560:        posprop += prop[jk][i]; 
        !          3561:       } 
        !          3562:       
        !          3563:       for(jk=1; jk <=nlstate ; jk++){      
        !          3564:        if( i <=  iagemax){ 
        !          3565:          if(posprop>=1.e-5){ 
        !          3566:            probs[i][jk][j1]= prop[jk][i]/posprop;
        !          3567:          } else{
        !          3568:            if(first==1){
        !          3569:              first=0;
        !          3570:              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]);
1.145     brouard  3571:            }
1.214   ! brouard  3572:          }
        !          3573:        } 
        !          3574:       }/* end jk */ 
        !          3575:     }/* end i */ 
1.145     brouard  3576:     /*} *//* end i1 */
                   3577:   } /* end j1 */
1.126     brouard  3578:   
                   3579:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3580:   /*free_vector(pp,1,nlstate);*/
                   3581:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3582: }  /* End of prevalence */
                   3583: 
                   3584: /************* Waves Concatenation ***************/
                   3585: 
                   3586: 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)
                   3587: {
                   3588:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3589:      Death is a valid wave (if date is known).
                   3590:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3591:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3592:      and mw[mi+1][i]. dh depends on stepm.
                   3593:      */
                   3594: 
                   3595:   int i, mi, m;
                   3596:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3597:      double sum=0., jmean=0.;*/
1.214   ! brouard  3598:   int first, firstwo;
1.126     brouard  3599:   int j, k=0,jk, ju, jl;
                   3600:   double sum=0.;
                   3601:   first=0;
1.214   ! brouard  3602:   firstwo=0;
1.164     brouard  3603:   jmin=100000;
1.126     brouard  3604:   jmax=-1;
                   3605:   jmean=0.;
1.214   ! brouard  3606:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  3607:     mi=0;
                   3608:     m=firstpass;
1.214   ! brouard  3609:     while(s[m][i] <= nlstate){  /* a live state */
1.126     brouard  3610:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3611:        mw[++mi][i]=m;
                   3612:       if(m >=lastpass)
                   3613:        break;
                   3614:       else
                   3615:        m++;
                   3616:     }/* end while */
1.214   ! brouard  3617:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  3618:       mi++;    /* Death is another wave */
                   3619:       /* if(mi==0)  never been interviewed correctly before death */
                   3620:         /* Only death is a correct wave */
                   3621:       mw[mi][i]=m;
1.214   ! brouard  3622:     }else if (andc[i] != 9999) { /* A death occured after lastpass */
        !          3623:       m++;
        !          3624:       mi++;
        !          3625:       s[m][i]=nlstate+1;  /* We are setting the status to the last of non live state */
        !          3626:       mw[mi][i]=m;
        !          3627:       nbwarn++;
        !          3628:       if(firstwo==0){
        !          3629:        printf("Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\nOthers in log file only\n",num[i],i,lastpass,nlstate+1, m);
        !          3630:        fprintf(ficlog,"Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
        !          3631:        firstwo=1;
        !          3632:       }
        !          3633:       if(firstwo==1){
        !          3634:        fprintf(ficlog,"Warning! Death for individual %ld line=%d  occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
        !          3635:       }
1.126     brouard  3636:     }
                   3637:     wav[i]=mi;
                   3638:     if(mi==0){
                   3639:       nbwarn++;
                   3640:       if(first==0){
                   3641:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3642:        first=1;
                   3643:       }
                   3644:       if(first==1){
                   3645:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3646:       }
                   3647:     } /* end mi==0 */
                   3648:   } /* End individuals */
1.214   ! brouard  3649:   /* wav and mw are no more changed */
1.126     brouard  3650: 
1.214   ! brouard  3651:   
1.126     brouard  3652:   for(i=1; i<=imx; i++){
                   3653:     for(mi=1; mi<wav[i];mi++){
                   3654:       if (stepm <=0)
                   3655:        dh[mi][i]=1;
                   3656:       else{
                   3657:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3658:          if (agedc[i] < 2*AGESUP) {
                   3659:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3660:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3661:            else if(j<0){
                   3662:              nberr++;
                   3663:              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]);
                   3664:              j=1; /* Temporary Dangerous patch */
                   3665:              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);
                   3666:              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]);
                   3667:              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);
                   3668:            }
                   3669:            k=k+1;
                   3670:            if (j >= jmax){
                   3671:              jmax=j;
                   3672:              ijmax=i;
                   3673:            }
                   3674:            if (j <= jmin){
                   3675:              jmin=j;
                   3676:              ijmin=i;
                   3677:            }
                   3678:            sum=sum+j;
                   3679:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3680:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3681:          }
                   3682:        }
                   3683:        else{
                   3684:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3685: /*       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]); */
                   3686: 
                   3687:          k=k+1;
                   3688:          if (j >= jmax) {
                   3689:            jmax=j;
                   3690:            ijmax=i;
                   3691:          }
                   3692:          else if (j <= jmin){
                   3693:            jmin=j;
                   3694:            ijmin=i;
                   3695:          }
                   3696:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3697:          /*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]);*/
                   3698:          if(j<0){
                   3699:            nberr++;
                   3700:            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]);
                   3701:            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]);
                   3702:          }
                   3703:          sum=sum+j;
                   3704:        }
                   3705:        jk= j/stepm;
                   3706:        jl= j -jk*stepm;
                   3707:        ju= j -(jk+1)*stepm;
                   3708:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3709:          if(jl==0){
                   3710:            dh[mi][i]=jk;
                   3711:            bh[mi][i]=0;
                   3712:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3713:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3714:            dh[mi][i]=jk+1;
                   3715:            bh[mi][i]=ju;
                   3716:          }
                   3717:        }else{
                   3718:          if(jl <= -ju){
                   3719:            dh[mi][i]=jk;
                   3720:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3721:                                 * is higher than the multiple of stepm and negative otherwise.
                   3722:                                 */
                   3723:          }
                   3724:          else{
                   3725:            dh[mi][i]=jk+1;
                   3726:            bh[mi][i]=ju;
                   3727:          }
                   3728:          if(dh[mi][i]==0){
                   3729:            dh[mi][i]=1; /* At least one step */
                   3730:            bh[mi][i]=ju; /* At least one step */
                   3731:            /*  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);*/
                   3732:          }
                   3733:        } /* end if mle */
                   3734:       }
                   3735:     } /* end wave */
                   3736:   }
                   3737:   jmean=sum/k;
                   3738:   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  3739:   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  3740:  }
                   3741: 
                   3742: /*********** Tricode ****************************/
1.145     brouard  3743: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3744: {
1.144     brouard  3745:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3746:   /*     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  3747:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3748:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3749:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3750:   */
1.130     brouard  3751: 
1.145     brouard  3752:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3753:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3754:   int cptcode=0; /* Modality max of covariates j */
                   3755:   int modmincovj=0; /* Modality min of covariates j */
                   3756: 
                   3757: 
1.126     brouard  3758:   cptcoveff=0; 
                   3759:  
1.144     brouard  3760:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3761: 
1.145     brouard  3762:   /* Loop on covariates without age and products */
1.186     brouard  3763:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3764:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3765:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3766:                               modality of this covariate Vj*/ 
1.145     brouard  3767:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3768:                                    * If product of Vn*Vm, still boolean *:
                   3769:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3770:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3771:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3772:                                      modality of the nth covariate of individual i. */
1.145     brouard  3773:       if (ij > modmaxcovj)
                   3774:         modmaxcovj=ij; 
                   3775:       else if (ij < modmincovj) 
                   3776:        modmincovj=ij; 
                   3777:       if ((ij < -1) && (ij > NCOVMAX)){
                   3778:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3779:        exit(1);
                   3780:       }else
1.136     brouard  3781:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3782:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3783:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3784:       /* getting the maximum value of the modality of the covariate
                   3785:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3786:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3787:     } /* end for loop on individuals i */
1.145     brouard  3788:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3789:     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  3790:     cptcode=modmaxcovj;
1.137     brouard  3791:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3792:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3793:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3794:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3795:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3796:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3797:        if( k != -1){
                   3798:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3799:                             covariate for which somebody answered excluding 
                   3800:                             undefined. Usually 2: 0 and 1. */
                   3801:        }
                   3802:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3803:                             covariate for which somebody answered including 
                   3804:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3805:       }
                   3806:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3807:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3808:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3809: 
1.136     brouard  3810:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3811:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3812:        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  3813:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3814:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3815:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3816:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3817:        nbcode[Tvar[j]][ij]=k;
                   3818:        nbcode[Tvar[j]][1]=0;
                   3819:        nbcode[Tvar[j]][2]=1;
                   3820:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3821:        To be continued (not working yet).
1.145     brouard  3822:     */
1.197     brouard  3823:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3824:     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*/
                   3825:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3826:          break;
                   3827:        }
                   3828:        ij++;
1.197     brouard  3829:        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  3830:        cptcode = ij; /* New max modality for covar j */
                   3831:     } /* end of loop on modality i=-1 to 1 or more */
                   3832:       
                   3833:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3834:     /*         /\*recode from 0 *\/ */
                   3835:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3836:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3837:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3838:     /*         } */
                   3839:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3840:     /*         if (ij > ncodemax[j]) { */
                   3841:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3842:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3843:     /*           break; */
                   3844:     /*         } */
                   3845:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3846:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3847:   
1.145     brouard  3848:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3849:   
1.187     brouard  3850:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3851:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3852:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3853:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3854:  } 
1.126     brouard  3855: 
1.192     brouard  3856:  ij=0;
1.145     brouard  3857:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3858:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3859:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3860:      ij++;
1.145     brouard  3861:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3862:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3863:    }else{
                   3864:        /* Tvaraff[ij]=0; */
                   3865:    }
1.126     brouard  3866:  }
1.192     brouard  3867:  /* ij--; */
1.144     brouard  3868:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3869: 
1.126     brouard  3870: }
                   3871: 
1.145     brouard  3872: 
1.126     brouard  3873: /*********** Health Expectancies ****************/
                   3874: 
1.127     brouard  3875: 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  3876: 
                   3877: {
                   3878:   /* Health expectancies, no variances */
1.164     brouard  3879:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3880:   int nhstepma, nstepma; /* Decreasing with age */
                   3881:   double age, agelim, hf;
                   3882:   double ***p3mat;
                   3883:   double eip;
                   3884: 
                   3885:   pstamp(ficreseij);
                   3886:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3887:   fprintf(ficreseij,"# Age");
                   3888:   for(i=1; i<=nlstate;i++){
                   3889:     for(j=1; j<=nlstate;j++){
                   3890:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3891:     }
                   3892:     fprintf(ficreseij," e%1d. ",i);
                   3893:   }
                   3894:   fprintf(ficreseij,"\n");
                   3895: 
                   3896:   
                   3897:   if(estepm < stepm){
                   3898:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3899:   }
                   3900:   else  hstepm=estepm;   
                   3901:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3902:    * This is mainly to measure the difference between two models: for example
                   3903:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3904:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3905:    * progression in between and thus overestimating or underestimating according
                   3906:    * to the curvature of the survival function. If, for the same date, we 
                   3907:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3908:    * to compare the new estimate of Life expectancy with the same linear 
                   3909:    * hypothesis. A more precise result, taking into account a more precise
                   3910:    * curvature will be obtained if estepm is as small as stepm. */
                   3911: 
                   3912:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3913:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3914:      nhstepm is the number of hstepm from age to agelim 
                   3915:      nstepm is the number of stepm from age to agelin. 
                   3916:      Look at hpijx to understand the reason of that which relies in memory size
                   3917:      and note for a fixed period like estepm months */
                   3918:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3919:      survival function given by stepm (the optimization length). Unfortunately it
                   3920:      means that if the survival funtion is printed only each two years of age and if
                   3921:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3922:      results. So we changed our mind and took the option of the best precision.
                   3923:   */
                   3924:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3925: 
                   3926:   agelim=AGESUP;
                   3927:   /* If stepm=6 months */
                   3928:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3929:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3930:     
                   3931: /* nhstepm age range expressed in number of stepm */
                   3932:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3933:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3934:   /* if (stepm >= YEARM) hstepm=1;*/
                   3935:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3936:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3937: 
                   3938:   for (age=bage; age<=fage; age ++){ 
                   3939:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3940:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3941:     /* if (stepm >= YEARM) hstepm=1;*/
                   3942:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3943: 
                   3944:     /* If stepm=6 months */
                   3945:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3946:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3947:     
                   3948:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3949:     
                   3950:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3951:     
                   3952:     printf("%d|",(int)age);fflush(stdout);
                   3953:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3954:     
                   3955:     /* Computing expectancies */
                   3956:     for(i=1; i<=nlstate;i++)
                   3957:       for(j=1; j<=nlstate;j++)
                   3958:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3959:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3960:          
                   3961:          /* 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]);*/
                   3962: 
                   3963:        }
                   3964: 
                   3965:     fprintf(ficreseij,"%3.0f",age );
                   3966:     for(i=1; i<=nlstate;i++){
                   3967:       eip=0;
                   3968:       for(j=1; j<=nlstate;j++){
                   3969:        eip +=eij[i][j][(int)age];
                   3970:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3971:       }
                   3972:       fprintf(ficreseij,"%9.4f", eip );
                   3973:     }
                   3974:     fprintf(ficreseij,"\n");
                   3975:     
                   3976:   }
                   3977:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3978:   printf("\n");
                   3979:   fprintf(ficlog,"\n");
                   3980:   
                   3981: }
                   3982: 
1.127     brouard  3983: 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  3984: 
                   3985: {
                   3986:   /* Covariances of health expectancies eij and of total life expectancies according
                   3987:    to initial status i, ei. .
                   3988:   */
                   3989:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3990:   int nhstepma, nstepma; /* Decreasing with age */
                   3991:   double age, agelim, hf;
                   3992:   double ***p3matp, ***p3matm, ***varhe;
                   3993:   double **dnewm,**doldm;
                   3994:   double *xp, *xm;
                   3995:   double **gp, **gm;
                   3996:   double ***gradg, ***trgradg;
                   3997:   int theta;
                   3998: 
                   3999:   double eip, vip;
                   4000: 
                   4001:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4002:   xp=vector(1,npar);
                   4003:   xm=vector(1,npar);
                   4004:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4005:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4006:   
                   4007:   pstamp(ficresstdeij);
                   4008:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4009:   fprintf(ficresstdeij,"# Age");
                   4010:   for(i=1; i<=nlstate;i++){
                   4011:     for(j=1; j<=nlstate;j++)
                   4012:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4013:     fprintf(ficresstdeij," e%1d. ",i);
                   4014:   }
                   4015:   fprintf(ficresstdeij,"\n");
                   4016: 
                   4017:   pstamp(ficrescveij);
                   4018:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4019:   fprintf(ficrescveij,"# Age");
                   4020:   for(i=1; i<=nlstate;i++)
                   4021:     for(j=1; j<=nlstate;j++){
                   4022:       cptj= (j-1)*nlstate+i;
                   4023:       for(i2=1; i2<=nlstate;i2++)
                   4024:        for(j2=1; j2<=nlstate;j2++){
                   4025:          cptj2= (j2-1)*nlstate+i2;
                   4026:          if(cptj2 <= cptj)
                   4027:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4028:        }
                   4029:     }
                   4030:   fprintf(ficrescveij,"\n");
                   4031:   
                   4032:   if(estepm < stepm){
                   4033:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4034:   }
                   4035:   else  hstepm=estepm;   
                   4036:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4037:    * This is mainly to measure the difference between two models: for example
                   4038:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4039:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4040:    * progression in between and thus overestimating or underestimating according
                   4041:    * to the curvature of the survival function. If, for the same date, we 
                   4042:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4043:    * to compare the new estimate of Life expectancy with the same linear 
                   4044:    * hypothesis. A more precise result, taking into account a more precise
                   4045:    * curvature will be obtained if estepm is as small as stepm. */
                   4046: 
                   4047:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4048:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4049:      nhstepm is the number of hstepm from age to agelim 
                   4050:      nstepm is the number of stepm from age to agelin. 
                   4051:      Look at hpijx to understand the reason of that which relies in memory size
                   4052:      and note for a fixed period like estepm months */
                   4053:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4054:      survival function given by stepm (the optimization length). Unfortunately it
                   4055:      means that if the survival funtion is printed only each two years of age and if
                   4056:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4057:      results. So we changed our mind and took the option of the best precision.
                   4058:   */
                   4059:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4060: 
                   4061:   /* If stepm=6 months */
                   4062:   /* nhstepm age range expressed in number of stepm */
                   4063:   agelim=AGESUP;
                   4064:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4065:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4066:   /* if (stepm >= YEARM) hstepm=1;*/
                   4067:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4068:   
                   4069:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4070:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4071:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4072:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4073:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4074:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4075: 
                   4076:   for (age=bage; age<=fage; age ++){ 
                   4077:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4078:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4079:     /* if (stepm >= YEARM) hstepm=1;*/
                   4080:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4081: 
                   4082:     /* If stepm=6 months */
                   4083:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4084:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4085:     
                   4086:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4087: 
                   4088:     /* Computing  Variances of health expectancies */
                   4089:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4090:        decrease memory allocation */
                   4091:     for(theta=1; theta <=npar; theta++){
                   4092:       for(i=1; i<=npar; i++){ 
                   4093:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4094:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   4095:       }
                   4096:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4097:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   4098:   
                   4099:       for(j=1; j<= nlstate; j++){
                   4100:        for(i=1; i<=nlstate; i++){
                   4101:          for(h=0; h<=nhstepm-1; h++){
                   4102:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4103:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4104:          }
                   4105:        }
                   4106:       }
                   4107:      
                   4108:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   4109:        for(h=0; h<=nhstepm-1; h++){
                   4110:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4111:        }
                   4112:     }/* End theta */
                   4113:     
                   4114:     
                   4115:     for(h=0; h<=nhstepm-1; h++)
                   4116:       for(j=1; j<=nlstate*nlstate;j++)
                   4117:        for(theta=1; theta <=npar; theta++)
                   4118:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4119:     
                   4120: 
                   4121:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   4122:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   4123:        varhe[ij][ji][(int)age] =0.;
                   4124: 
                   4125:      printf("%d|",(int)age);fflush(stdout);
                   4126:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4127:      for(h=0;h<=nhstepm-1;h++){
                   4128:       for(k=0;k<=nhstepm-1;k++){
                   4129:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4130:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4131:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4132:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4133:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   4134:       }
                   4135:     }
                   4136: 
                   4137:     /* Computing expectancies */
                   4138:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4139:     for(i=1; i<=nlstate;i++)
                   4140:       for(j=1; j<=nlstate;j++)
                   4141:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4142:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4143:          
                   4144:          /* 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]);*/
                   4145: 
                   4146:        }
                   4147: 
                   4148:     fprintf(ficresstdeij,"%3.0f",age );
                   4149:     for(i=1; i<=nlstate;i++){
                   4150:       eip=0.;
                   4151:       vip=0.;
                   4152:       for(j=1; j<=nlstate;j++){
                   4153:        eip += eij[i][j][(int)age];
                   4154:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4155:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4156:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4157:       }
                   4158:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4159:     }
                   4160:     fprintf(ficresstdeij,"\n");
                   4161: 
                   4162:     fprintf(ficrescveij,"%3.0f",age );
                   4163:     for(i=1; i<=nlstate;i++)
                   4164:       for(j=1; j<=nlstate;j++){
                   4165:        cptj= (j-1)*nlstate+i;
                   4166:        for(i2=1; i2<=nlstate;i2++)
                   4167:          for(j2=1; j2<=nlstate;j2++){
                   4168:            cptj2= (j2-1)*nlstate+i2;
                   4169:            if(cptj2 <= cptj)
                   4170:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4171:          }
                   4172:       }
                   4173:     fprintf(ficrescveij,"\n");
                   4174:    
                   4175:   }
                   4176:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4177:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4178:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4179:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4180:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4181:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4182:   printf("\n");
                   4183:   fprintf(ficlog,"\n");
                   4184: 
                   4185:   free_vector(xm,1,npar);
                   4186:   free_vector(xp,1,npar);
                   4187:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4188:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4189:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4190: }
                   4191: 
                   4192: /************ Variance ******************/
1.209     brouard  4193:  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.126     brouard  4194: {
                   4195:   /* Variance of health expectancies */
                   4196:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4197:   /* double **newm;*/
1.169     brouard  4198:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4199:   
                   4200:   int movingaverage();
1.126     brouard  4201:   double **dnewm,**doldm;
                   4202:   double **dnewmp,**doldmp;
                   4203:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4204:   int k;
1.126     brouard  4205:   double *xp;
                   4206:   double **gp, **gm;  /* for var eij */
                   4207:   double ***gradg, ***trgradg; /*for var eij */
                   4208:   double **gradgp, **trgradgp; /* for var p point j */
                   4209:   double *gpp, *gmp; /* for var p point j */
                   4210:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4211:   double ***p3mat;
                   4212:   double age,agelim, hf;
                   4213:   double ***mobaverage;
                   4214:   int theta;
                   4215:   char digit[4];
                   4216:   char digitp[25];
                   4217: 
                   4218:   char fileresprobmorprev[FILENAMELENGTH];
                   4219: 
                   4220:   if(popbased==1){
                   4221:     if(mobilav!=0)
1.201     brouard  4222:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4223:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4224:   }
                   4225:   else 
1.201     brouard  4226:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4227: 
                   4228:   if (mobilav!=0) {
                   4229:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4230:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4231:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4232:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4233:     }
                   4234:   }
                   4235: 
1.201     brouard  4236:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4237:   sprintf(digit,"%-d",ij);
                   4238:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4239:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4240:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4241:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4242:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4243:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4244:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4245:   }
                   4246:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4247:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4248:   pstamp(ficresprobmorprev);
                   4249:   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);
                   4250:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4251:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4252:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4253:     for(i=1; i<=nlstate;i++)
                   4254:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4255:   }  
                   4256:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4257:   
1.126     brouard  4258:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4259:   fprintf(ficgp,"\nunset title \n");
                   4260: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4261:   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");
                   4262:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4263: /*   } */
                   4264:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4265:   pstamp(ficresvij);
                   4266:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4267:   if(popbased==1)
1.128     brouard  4268:     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);
1.126     brouard  4269:   else
                   4270:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4271:   fprintf(ficresvij,"# Age");
                   4272:   for(i=1; i<=nlstate;i++)
                   4273:     for(j=1; j<=nlstate;j++)
                   4274:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4275:   fprintf(ficresvij,"\n");
                   4276: 
                   4277:   xp=vector(1,npar);
                   4278:   dnewm=matrix(1,nlstate,1,npar);
                   4279:   doldm=matrix(1,nlstate,1,nlstate);
                   4280:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4281:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4282: 
                   4283:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4284:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4285:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4286:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4287:   
                   4288:   if(estepm < stepm){
                   4289:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4290:   }
                   4291:   else  hstepm=estepm;   
                   4292:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4293:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4294:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4295:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4296:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4297:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4298:      survival function given by stepm (the optimization length). Unfortunately it
                   4299:      means that if the survival funtion is printed every two years of age and if
                   4300:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4301:      results. So we changed our mind and took the option of the best precision.
                   4302:   */
                   4303:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4304:   agelim = AGESUP;
                   4305:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4306:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4307:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4308:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4309:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4310:     gp=matrix(0,nhstepm,1,nlstate);
                   4311:     gm=matrix(0,nhstepm,1,nlstate);
                   4312: 
                   4313: 
                   4314:     for(theta=1; theta <=npar; theta++){
                   4315:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4316:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4317:       }
1.209     brouard  4318: 
                   4319:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4320: 
                   4321:       if (popbased==1) {
                   4322:        if(mobilav ==0){
                   4323:          for(i=1; i<=nlstate;i++)
                   4324:            prlim[i][i]=probs[(int)age][i][ij];
                   4325:        }else{ /* mobilav */ 
                   4326:          for(i=1; i<=nlstate;i++)
                   4327:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4328:        }
                   4329:       }
                   4330:   
1.209     brouard  4331:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4332:       for(j=1; j<= nlstate; j++){
                   4333:        for(h=0; h<=nhstepm; h++){
                   4334:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4335:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4336:        }
                   4337:       }
1.209     brouard  4338:       /* Next for computing probability of death (h=1 means
1.126     brouard  4339:          computed over hstepm matrices product = hstepm*stepm months) 
                   4340:          as a weighted average of prlim.
                   4341:       */
                   4342:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4343:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4344:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4345:       }    
                   4346:       /* end probability of death */
                   4347: 
                   4348:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4349:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4350: 
                   4351:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4352:  
                   4353:       if (popbased==1) {
                   4354:        if(mobilav ==0){
                   4355:          for(i=1; i<=nlstate;i++)
                   4356:            prlim[i][i]=probs[(int)age][i][ij];
                   4357:        }else{ /* mobilav */ 
                   4358:          for(i=1; i<=nlstate;i++)
                   4359:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4360:        }
                   4361:       }
                   4362: 
1.209     brouard  4363:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4364: 
1.128     brouard  4365:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4366:        for(h=0; h<=nhstepm; h++){
                   4367:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4368:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4369:        }
                   4370:       }
                   4371:       /* This for computing probability of death (h=1 means
                   4372:          computed over hstepm matrices product = hstepm*stepm months) 
                   4373:          as a weighted average of prlim.
                   4374:       */
                   4375:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4376:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4377:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4378:       }    
                   4379:       /* end probability of death */
                   4380: 
                   4381:       for(j=1; j<= nlstate; j++) /* vareij */
                   4382:        for(h=0; h<=nhstepm; h++){
                   4383:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4384:        }
                   4385: 
                   4386:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4387:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4388:       }
                   4389: 
                   4390:     } /* End theta */
                   4391: 
                   4392:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4393: 
                   4394:     for(h=0; h<=nhstepm; h++) /* veij */
                   4395:       for(j=1; j<=nlstate;j++)
                   4396:        for(theta=1; theta <=npar; theta++)
                   4397:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4398: 
                   4399:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4400:       for(theta=1; theta <=npar; theta++)
                   4401:        trgradgp[j][theta]=gradgp[theta][j];
                   4402:   
                   4403: 
                   4404:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4405:     for(i=1;i<=nlstate;i++)
                   4406:       for(j=1;j<=nlstate;j++)
                   4407:        vareij[i][j][(int)age] =0.;
                   4408: 
                   4409:     for(h=0;h<=nhstepm;h++){
                   4410:       for(k=0;k<=nhstepm;k++){
                   4411:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4412:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4413:        for(i=1;i<=nlstate;i++)
                   4414:          for(j=1;j<=nlstate;j++)
                   4415:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4416:       }
                   4417:     }
                   4418:   
                   4419:     /* pptj */
                   4420:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4421:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4422:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4423:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4424:        varppt[j][i]=doldmp[j][i];
                   4425:     /* end ppptj */
                   4426:     /*  x centered again */
1.209     brouard  4427: 
                   4428:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4429:  
                   4430:     if (popbased==1) {
                   4431:       if(mobilav ==0){
                   4432:        for(i=1; i<=nlstate;i++)
                   4433:          prlim[i][i]=probs[(int)age][i][ij];
                   4434:       }else{ /* mobilav */ 
                   4435:        for(i=1; i<=nlstate;i++)
                   4436:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4437:       }
                   4438:     }
                   4439:              
                   4440:     /* This for computing probability of death (h=1 means
                   4441:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4442:        as a weighted average of prlim.
                   4443:     */
1.209     brouard  4444:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4445:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4446:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4447:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4448:     }    
                   4449:     /* end probability of death */
                   4450: 
                   4451:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4452:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4453:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4454:       for(i=1; i<=nlstate;i++){
                   4455:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4456:       }
                   4457:     } 
                   4458:     fprintf(ficresprobmorprev,"\n");
                   4459: 
                   4460:     fprintf(ficresvij,"%.0f ",age );
                   4461:     for(i=1; i<=nlstate;i++)
                   4462:       for(j=1; j<=nlstate;j++){
                   4463:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4464:       }
                   4465:     fprintf(ficresvij,"\n");
                   4466:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4467:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4468:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4469:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4470:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4471:   } /* End age */
                   4472:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4473:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4474:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4475:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4476:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4477:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4478:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4479:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4480:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4481: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4482: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4483: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4484:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4485:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4486:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4487:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201     brouard  4488:   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);
1.199     brouard  4489:   /*  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  4490: */
1.199     brouard  4491: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4492:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4493: 
                   4494:   free_vector(xp,1,npar);
                   4495:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4496:   free_matrix(dnewm,1,nlstate,1,npar);
                   4497:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4498:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4499:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4500:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4501:   fclose(ficresprobmorprev);
                   4502:   fflush(ficgp);
                   4503:   fflush(fichtm); 
                   4504: }  /* end varevsij */
                   4505: 
                   4506: /************ Variance of prevlim ******************/
1.209     brouard  4507:  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  4508: {
1.205     brouard  4509:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4510:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4511: 
1.126     brouard  4512:   double **dnewm,**doldm;
                   4513:   int i, j, nhstepm, hstepm;
                   4514:   double *xp;
                   4515:   double *gp, *gm;
                   4516:   double **gradg, **trgradg;
1.208     brouard  4517:   double **mgm, **mgp;
1.126     brouard  4518:   double age,agelim;
                   4519:   int theta;
                   4520:   
                   4521:   pstamp(ficresvpl);
                   4522:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4523:   fprintf(ficresvpl,"# Age");
                   4524:   for(i=1; i<=nlstate;i++)
                   4525:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4526:   fprintf(ficresvpl,"\n");
                   4527: 
                   4528:   xp=vector(1,npar);
                   4529:   dnewm=matrix(1,nlstate,1,npar);
                   4530:   doldm=matrix(1,nlstate,1,nlstate);
                   4531:   
                   4532:   hstepm=1*YEARM; /* Every year of age */
                   4533:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4534:   agelim = AGESUP;
                   4535:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4536:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4537:     if (stepm >= YEARM) hstepm=1;
                   4538:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4539:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4540:     mgp=matrix(1,npar,1,nlstate);
                   4541:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4542:     gp=vector(1,nlstate);
                   4543:     gm=vector(1,nlstate);
                   4544: 
                   4545:     for(theta=1; theta <=npar; theta++){
                   4546:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4547:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4548:       }
1.209     brouard  4549:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4550:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4551:       else
                   4552:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4553:       for(i=1;i<=nlstate;i++){
1.126     brouard  4554:        gp[i] = prlim[i][i];
1.208     brouard  4555:        mgp[theta][i] = prlim[i][i];
                   4556:       }
1.126     brouard  4557:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4558:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4559:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4560:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4561:       else
                   4562:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4563:       for(i=1;i<=nlstate;i++){
1.126     brouard  4564:        gm[i] = prlim[i][i];
1.208     brouard  4565:        mgm[theta][i] = prlim[i][i];
                   4566:       }
1.126     brouard  4567:       for(i=1;i<=nlstate;i++)
                   4568:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4569:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4570:     } /* End theta */
                   4571: 
                   4572:     trgradg =matrix(1,nlstate,1,npar);
                   4573: 
                   4574:     for(j=1; j<=nlstate;j++)
                   4575:       for(theta=1; theta <=npar; theta++)
                   4576:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4577:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4578:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4579:     /*   for(j=1; j<=nlstate;j++){ */
                   4580:     /*         printf(" %d ",j); */
                   4581:     /*         for(theta=1; theta <=npar; theta++) */
                   4582:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4583:     /*         printf("\n "); */
                   4584:     /*   } */
                   4585:     /* } */
                   4586:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4587:     /*   printf("\n gradg %d ",(int)age); */
                   4588:     /*   for(j=1; j<=nlstate;j++){ */
                   4589:     /*         printf("%d ",j); */
                   4590:     /*         for(theta=1; theta <=npar; theta++) */
                   4591:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4592:     /*         printf("\n "); */
                   4593:     /*   } */
                   4594:     /* } */
1.126     brouard  4595: 
                   4596:     for(i=1;i<=nlstate;i++)
                   4597:       varpl[i][(int)age] =0.;
1.209     brouard  4598:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4599:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4600:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4601:     }else{
1.126     brouard  4602:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4603:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4604:     }
1.126     brouard  4605:     for(i=1;i<=nlstate;i++)
                   4606:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4607: 
                   4608:     fprintf(ficresvpl,"%.0f ",age );
                   4609:     for(i=1; i<=nlstate;i++)
                   4610:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4611:     fprintf(ficresvpl,"\n");
                   4612:     free_vector(gp,1,nlstate);
                   4613:     free_vector(gm,1,nlstate);
1.208     brouard  4614:     free_matrix(mgm,1,npar,1,nlstate);
                   4615:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4616:     free_matrix(gradg,1,npar,1,nlstate);
                   4617:     free_matrix(trgradg,1,nlstate,1,npar);
                   4618:   } /* End age */
                   4619: 
                   4620:   free_vector(xp,1,npar);
                   4621:   free_matrix(doldm,1,nlstate,1,npar);
                   4622:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4623: 
                   4624: }
                   4625: 
                   4626: /************ Variance of one-step probabilities  ******************/
                   4627: 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[])
                   4628: {
1.164     brouard  4629:   int i, j=0,  k1, l1, tj;
1.126     brouard  4630:   int k2, l2, j1,  z1;
1.164     brouard  4631:   int k=0, l;
1.145     brouard  4632:   int first=1, first1, first2;
1.126     brouard  4633:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4634:   double **dnewm,**doldm;
                   4635:   double *xp;
                   4636:   double *gp, *gm;
                   4637:   double **gradg, **trgradg;
                   4638:   double **mu;
1.164     brouard  4639:   double age, cov[NCOVMAX+1];
1.126     brouard  4640:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4641:   int theta;
                   4642:   char fileresprob[FILENAMELENGTH];
                   4643:   char fileresprobcov[FILENAMELENGTH];
                   4644:   char fileresprobcor[FILENAMELENGTH];
                   4645:   double ***varpij;
                   4646: 
1.201     brouard  4647:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4648:   strcat(fileresprob,fileres);
                   4649:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4650:     printf("Problem with resultfile: %s\n", fileresprob);
                   4651:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4652:   }
1.201     brouard  4653:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4654:   strcat(fileresprobcov,fileresu);
1.126     brouard  4655:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4656:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4657:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4658:   }
1.201     brouard  4659:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4660:   strcat(fileresprobcor,fileresu);
1.126     brouard  4661:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4662:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4663:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4664:   }
                   4665:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4666:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4667:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4668:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4669:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4670:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4671:   pstamp(ficresprob);
                   4672:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4673:   fprintf(ficresprob,"# Age");
                   4674:   pstamp(ficresprobcov);
                   4675:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4676:   fprintf(ficresprobcov,"# Age");
                   4677:   pstamp(ficresprobcor);
                   4678:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4679:   fprintf(ficresprobcor,"# Age");
                   4680: 
                   4681: 
                   4682:   for(i=1; i<=nlstate;i++)
                   4683:     for(j=1; j<=(nlstate+ndeath);j++){
                   4684:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4685:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4686:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4687:     }  
                   4688:  /* fprintf(ficresprob,"\n");
                   4689:   fprintf(ficresprobcov,"\n");
                   4690:   fprintf(ficresprobcor,"\n");
                   4691:  */
1.131     brouard  4692:   xp=vector(1,npar);
1.126     brouard  4693:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4694:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4695:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4696:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4697:   first=1;
                   4698:   fprintf(ficgp,"\n# Routine varprob");
                   4699:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4700:   fprintf(fichtm,"\n");
                   4701: 
1.200     brouard  4702:   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  4703:   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);
                   4704:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4705: and drawn. It helps understanding how is the covariance between two incidences.\
                   4706:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4707:   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. \
                   4708: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4709: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4710: standard deviations wide on each axis. <br>\
                   4711:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4712:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4713: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4714: 
                   4715:   cov[1]=1;
1.145     brouard  4716:   /* tj=cptcoveff; */
                   4717:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4718:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4719:   j1=0;
1.145     brouard  4720:   for(j1=1; j1<=tj;j1++){
                   4721:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4722:     /*j1++;*/
1.126     brouard  4723:       if  (cptcovn>0) {
                   4724:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4725:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4726:        fprintf(ficresprob, "**********\n#\n");
                   4727:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4728:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4729:        fprintf(ficresprobcov, "**********\n#\n");
                   4730:        
                   4731:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4732:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4733:        fprintf(ficgp, "**********\n#\n");
                   4734:        
                   4735:        
                   4736:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4737:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4738:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4739:        
                   4740:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4741:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4742:        fprintf(ficresprobcor, "**********\n#");    
                   4743:       }
                   4744:       
1.145     brouard  4745:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4746:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4747:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4748:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4749:       for (age=bage; age<=fage; age ++){ 
                   4750:        cov[2]=age;
1.187     brouard  4751:        if(nagesqr==1)
                   4752:          cov[3]= age*age;
1.126     brouard  4753:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4754:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4755:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4756:                                                         * 1  1 1 1 1
                   4757:                                                         * 2  2 1 1 1
                   4758:                                                         * 3  1 2 1 1
                   4759:                                                         */
                   4760:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4761:        }
1.186     brouard  4762:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4763:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4764:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4765:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4766:        
                   4767:     
                   4768:        for(theta=1; theta <=npar; theta++){
                   4769:          for(i=1; i<=npar; i++)
                   4770:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4771:          
                   4772:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4773:          
                   4774:          k=0;
                   4775:          for(i=1; i<= (nlstate); i++){
                   4776:            for(j=1; j<=(nlstate+ndeath);j++){
                   4777:              k=k+1;
                   4778:              gp[k]=pmmij[i][j];
                   4779:            }
                   4780:          }
                   4781:          
                   4782:          for(i=1; i<=npar; i++)
                   4783:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4784:     
                   4785:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4786:          k=0;
                   4787:          for(i=1; i<=(nlstate); i++){
                   4788:            for(j=1; j<=(nlstate+ndeath);j++){
                   4789:              k=k+1;
                   4790:              gm[k]=pmmij[i][j];
                   4791:            }
                   4792:          }
                   4793:      
                   4794:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4795:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4796:        }
                   4797: 
                   4798:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4799:          for(theta=1; theta <=npar; theta++)
                   4800:            trgradg[j][theta]=gradg[theta][j];
                   4801:        
                   4802:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4803:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4804: 
                   4805:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4806:        
                   4807:        k=0;
                   4808:        for(i=1; i<=(nlstate); i++){
                   4809:          for(j=1; j<=(nlstate+ndeath);j++){
                   4810:            k=k+1;
                   4811:            mu[k][(int) age]=pmmij[i][j];
                   4812:          }
                   4813:        }
                   4814:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4815:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4816:            varpij[i][j][(int)age] = doldm[i][j];
                   4817: 
                   4818:        /*printf("\n%d ",(int)age);
                   4819:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4820:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4821:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4822:          }*/
                   4823: 
                   4824:        fprintf(ficresprob,"\n%d ",(int)age);
                   4825:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4826:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4827: 
                   4828:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4829:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4830:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4831:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4832:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4833:        }
                   4834:        i=0;
                   4835:        for (k=1; k<=(nlstate);k++){
                   4836:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4837:            i++;
1.126     brouard  4838:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4839:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4840:            for (j=1; j<=i;j++){
1.145     brouard  4841:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4842:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4843:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4844:            }
                   4845:          }
                   4846:        }/* end of loop for state */
                   4847:       } /* end of loop for age */
1.145     brouard  4848:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4849:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4850:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4851:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4852:       
1.126     brouard  4853:       /* Confidence intervalle of pij  */
                   4854:       /*
1.131     brouard  4855:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4856:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4857:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4858:        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);
                   4859:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4860:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4861:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4862:       */
                   4863: 
                   4864:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4865:       first1=1;first2=2;
1.126     brouard  4866:       for (k2=1; k2<=(nlstate);k2++){
                   4867:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4868:          if(l2==k2) continue;
                   4869:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4870:          for (k1=1; k1<=(nlstate);k1++){
                   4871:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4872:              if(l1==k1) continue;
                   4873:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4874:              if(i<=j) continue;
                   4875:              for (age=bage; age<=fage; age ++){ 
                   4876:                if ((int)age %5==0){
                   4877:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4878:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4879:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4880:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4881:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4882:                  c12=cv12/sqrt(v1*v2);
                   4883:                  /* Computing eigen value of matrix of covariance */
                   4884:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4885:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4886:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4887:                    if(first2==1){
                   4888:                      first1=0;
                   4889:                    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);
                   4890:                    }
                   4891:                    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);
                   4892:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4893:                    /* lc2=fabs(lc2); */
1.135     brouard  4894:                  }
                   4895: 
1.126     brouard  4896:                  /* Eigen vectors */
                   4897:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4898:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4899:                  v21=(lc1-v1)/cv12*v11;
                   4900:                  v12=-v21;
                   4901:                  v22=v11;
                   4902:                  tnalp=v21/v11;
                   4903:                  if(first1==1){
                   4904:                    first1=0;
                   4905:                    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);
                   4906:                  }
                   4907:                  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);
                   4908:                  /*printf(fignu*/
                   4909:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4910:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4911:                  if(first==1){
                   4912:                    first=0;
1.200     brouard  4913:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4914:                    fprintf(ficgp,"\nset parametric;unset label");
                   4915:                    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);
1.199     brouard  4916:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4917:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4918:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4919: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4920:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4921:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4922:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4923:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4924:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4925:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4926:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4927:                    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",\
                   4928:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4929:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4930:                  }else{
                   4931:                    first=0;
                   4932:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4933:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4934:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4935:                    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",\
                   4936:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4937:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4938:                  }/* if first */
                   4939:                } /* age mod 5 */
                   4940:              } /* end loop age */
1.201     brouard  4941:              fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4942:              first=1;
                   4943:            } /*l12 */
                   4944:          } /* k12 */
                   4945:        } /*l1 */
                   4946:       }/* k1 */
1.169     brouard  4947:       /* } */ /* loop covariates */
1.126     brouard  4948:   }
                   4949:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4950:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4951:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4952:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4953:   free_vector(xp,1,npar);
                   4954:   fclose(ficresprob);
                   4955:   fclose(ficresprobcov);
                   4956:   fclose(ficresprobcor);
                   4957:   fflush(ficgp);
                   4958:   fflush(fichtmcov);
                   4959: }
                   4960: 
                   4961: 
                   4962: /******************* Printing html file ***********/
1.201     brouard  4963: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4964:                  int lastpass, int stepm, int weightopt, char model[],\
                   4965:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211     brouard  4966:                  int popforecast, int prevfcast, int estepm ,          \
1.213     brouard  4967:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   4968:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  4969:   int jj1, k1, i1, cpt;
                   4970: 
                   4971:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4972:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4973: </ul>");
1.214   ! brouard  4974:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
        !          4975:    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",
        !          4976:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
        !          4977:    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  4978:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   4979:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4980:    fprintf(fichtm,"\
                   4981:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4982:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4983:    fprintf(fichtm,"\
                   4984:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4985:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4986:    fprintf(fichtm,"\
1.211     brouard  4987:  - (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  4988:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4989:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  4990:    if(prevfcast==1){
                   4991:      fprintf(fichtm,"\
                   4992:  - Prevalence projections by age and states:                           \
1.201     brouard  4993:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  4994:    }
1.126     brouard  4995: 
                   4996: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4997: 
1.145     brouard  4998:  m=pow(2,cptcoveff);
1.126     brouard  4999:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5000: 
                   5001:  jj1=0;
                   5002:  for(k1=1; k1<=m;k1++){
1.192     brouard  5003:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5004:      jj1++;
                   5005:      if (cptcovn > 0) {
                   5006:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  5007:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  5008:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5009:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  5010:        }
1.126     brouard  5011:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5012:      }
1.201     brouard  5013:      /* aij, bij */
1.211     brouard  5014:      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> \
                   5015: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  5016:      /* Pij */
1.211     brouard  5017:      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  5018: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  5019:      /* Quasi-incidences */
1.211     brouard  5020:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.201     brouard  5021:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211     brouard  5022:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5023: 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  5024: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5025:      /* Survival functions (period) in state j */
                   5026:      for(cpt=1; cpt<=nlstate;cpt++){
                   5027:        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> \
                   5028: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5029:      }
                   5030:      /* State specific survival functions (period) */
                   5031:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  5032:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  5033:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   5034:  <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);
                   5035:      }
                   5036:      /* Period (stable) prevalence in each health state */
                   5037:      for(cpt=1; cpt<=nlstate;cpt++){
                   5038:        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> \
                   5039: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5040:      }
1.211     brouard  5041:     if(prevfcast==1){
                   5042:       /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5043:       for(cpt=1; cpt<=nlstate;cpt++){
1.214   ! brouard  5044:        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  5045: <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.211     brouard  5046:       }
                   5047:     }
                   5048: 
1.126     brouard  5049:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  5050:        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  5051: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.126     brouard  5052:      }
1.192     brouard  5053:    /* } /\* end i1 *\/ */
1.126     brouard  5054:  }/* End k1 */
                   5055:  fprintf(fichtm,"</ul>");
                   5056: 
                   5057:  fprintf(fichtm,"\
                   5058: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5059:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5060:  - 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  5061: But because parameters are usually highly correlated (a higher incidence of disability \
                   5062: and a higher incidence of recovery can give very close observed transition) it might \
                   5063: be very useful to look not only at linear confidence intervals estimated from the \
                   5064: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5065: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5066: covariance matrix of the one-step probabilities. \
                   5067: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5068: 
1.193     brouard  5069:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5070:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5071:  fprintf(fichtm,"\
                   5072:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5073:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5074: 
                   5075:  fprintf(fichtm,"\
                   5076:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5077:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5078:  fprintf(fichtm,"\
                   5079:  - 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): \
                   5080:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5081:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5082:  fprintf(fichtm,"\
                   5083:  - (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): \
                   5084:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5085:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5086:  fprintf(fichtm,"\
1.128     brouard  5087:  - 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  5088:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5089:  fprintf(fichtm,"\
1.128     brouard  5090:  - 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  5091:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5092:  fprintf(fichtm,"\
                   5093:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5094:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5095: 
                   5096: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5097: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5098: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5099: /*     <br>",fileres,fileres,fileres,fileres); */
                   5100: /*  else  */
                   5101: /*    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); */
                   5102:  fflush(fichtm);
                   5103:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5104: 
1.145     brouard  5105:  m=pow(2,cptcoveff);
1.126     brouard  5106:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5107: 
                   5108:  jj1=0;
                   5109:  for(k1=1; k1<=m;k1++){
1.192     brouard  5110:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5111:      jj1++;
                   5112:      if (cptcovn > 0) {
                   5113:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5114:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  5115:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5116:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5117:      }
                   5118:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5119:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  5120: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   5121: <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  5122:      }
                   5123:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5124: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5125: true period expectancies (those weighted with period prevalences are also\
                   5126:  drawn in addition to the population based expectancies computed using\
1.205     brouard  5127:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   5128: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5129:    /* } /\* end i1 *\/ */
1.126     brouard  5130:  }/* End k1 */
                   5131:  fprintf(fichtm,"</ul>");
                   5132:  fflush(fichtm);
                   5133: }
                   5134: 
                   5135: /******************* Gnuplot file **************/
1.211     brouard  5136:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126     brouard  5137: 
                   5138:   char dirfileres[132],optfileres[132];
1.164     brouard  5139:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5140:   int lv=0, vlv=0, kl=0;
1.130     brouard  5141:   int ng=0;
1.201     brouard  5142:   int vpopbased;
1.126     brouard  5143: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5144: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5145: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5146: /*   } */
                   5147: 
                   5148:   /*#ifdef windows */
                   5149:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5150:     /*#endif */
                   5151:   m=pow(2,cptcoveff);
                   5152: 
1.202     brouard  5153:   /* Contribution to likelihood */
                   5154:   /* Plot the probability implied in the likelihood */
                   5155:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5156:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5157:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5158:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5159: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5160:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5161: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5162:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5163:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214   ! brouard  5164:     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  5165:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214   ! brouard  5166:     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  5167:     for (i=1; i<= nlstate ; i ++) {
                   5168:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5169:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214   ! brouard  5170:       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  5171:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.214   ! brouard  5172:        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  5173:       }
                   5174:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5175:     }
                   5176:     /* 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 */             
                   5177:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5178:     /* 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  5179:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5180:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5181: 
1.126     brouard  5182:   strcpy(dirfileres,optionfilefiname);
                   5183:   strcpy(optfileres,"vpl");
                   5184:  /* 1eme*/
1.211     brouard  5185:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5186:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
                   5187:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5188:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
                   5189:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5190:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5191:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5192:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5193:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5194:        vlv= nbcode[Tvaraff[lv]][lv];
                   5195:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5196:       }
                   5197:       fprintf(ficgp,"\n#\n");
                   5198: 
1.201     brouard  5199:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5200:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5201:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5202: set ylabel \"Probability\" \n\
1.199     brouard  5203: set ter svg size 640, 480\n\
1.201     brouard  5204: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5205: 
                   5206:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5207:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5208:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5209:      }
1.201     brouard  5210:      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);
1.126     brouard  5211:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5212:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5213:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5214:      } 
1.201     brouard  5215:      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); 
1.126     brouard  5216:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5217:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5218:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5219:      }  
1.201     brouard  5220:      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));
                   5221:      fprintf(ficgp,"\nset out \n");
                   5222:     } /* k1 */
                   5223:   } /* cpt */
1.126     brouard  5224:   /*2 eme*/
                   5225:   for (k1=1; k1<= m ; k1 ++) { 
1.211     brouard  5226:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5227:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5228:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5229:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5230:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5231:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5232:        vlv= nbcode[Tvaraff[lv]][lv];
                   5233:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5234:       }
                   5235:       fprintf(ficgp,"\n#\n");
                   5236: 
1.201     brouard  5237:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5238:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5239:       if(vpopbased==0)
                   5240:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5241:       else
                   5242:        fprintf(ficgp,"\nreplot ");
                   5243:       for (i=1; i<= nlstate+1 ; i ++) {
                   5244:        k=2*i;
                   5245:        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);
                   5246:        for (j=1; j<= nlstate+1 ; j ++) {
                   5247:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5248:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5249:        }   
                   5250:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5251:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5252:        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);
                   5253:        for (j=1; j<= nlstate+1 ; j ++) {
                   5254:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5255:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5256:        }   
                   5257:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5258:        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);
                   5259:        for (j=1; j<= nlstate+1 ; j ++) {
                   5260:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5261:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5262:        }   
                   5263:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5264:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5265:       } /* state */
                   5266:     } /* vpopbased */
                   5267:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5268:   } /* k1 */
1.211     brouard  5269: 
                   5270: 
1.126     brouard  5271:   /*3eme*/
                   5272:   for (k1=1; k1<= m ; k1 ++) { 
                   5273:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5274:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5275:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5276:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5277:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5278:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5279:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5280:        vlv= nbcode[Tvaraff[lv]][lv];
                   5281:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5282:       }
                   5283:       fprintf(ficgp,"\n#\n");
                   5284: 
1.126     brouard  5285:       /*       k=2+nlstate*(2*cpt-2); */
                   5286:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5287:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5288:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5289: 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  5290:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5291:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5292:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5293:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5294:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5295:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5296:        
                   5297:       */
                   5298:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5299:        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);
1.126     brouard  5300:        /*      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);*/
                   5301:        
                   5302:       } 
1.201     brouard  5303:       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  5304:     }
                   5305:   }
                   5306:   
1.201     brouard  5307:   /* Survival functions (period) from state i in state j by initial state i */
                   5308:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5309:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5310:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5311:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5312:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5313:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5314:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5315:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5316:        vlv= nbcode[Tvaraff[lv]][lv];
                   5317:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5318:       }
                   5319:       fprintf(ficgp,"\n#\n");
                   5320: 
1.201     brouard  5321:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5322:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5323: set ter svg size 640, 480\n\
                   5324: unset log y\n\
                   5325: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5326:       k=3;
1.201     brouard  5327:       for (i=1; i<= nlstate ; i ++){
                   5328:        if(i==1)
                   5329:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5330:        else
                   5331:          fprintf(ficgp,", '' ");
                   5332:        l=(nlstate+ndeath)*(i-1)+1;
                   5333:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5334:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5335:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5336:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5337:       } /* nlstate */
                   5338:       fprintf(ficgp,"\nset out\n");
                   5339:     } /* end cpt state*/ 
                   5340:   } /* end covariate */  
                   5341: 
                   5342:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5343:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5344:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5345:       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  5346:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5347:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5348:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5349:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5350:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5351:        vlv= nbcode[Tvaraff[lv]][lv];
                   5352:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5353:       }
                   5354:       fprintf(ficgp,"\n#\n");
                   5355: 
1.201     brouard  5356:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5357:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5358: set ter svg size 640, 480\n\
                   5359: unset log y\n\
                   5360: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5361:       k=3;
1.201     brouard  5362:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5363:        if(j==1)
                   5364:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5365:        else
                   5366:          fprintf(ficgp,", '' ");
                   5367:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5368:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5369:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5370:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5371:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5372:       } /* nlstate */
                   5373:       fprintf(ficgp,", '' ");
                   5374:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5375:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5376:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5377:        if(j < nlstate)
                   5378:          fprintf(ficgp,"$%d +",k+l);
                   5379:        else
                   5380:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5381:       }
                   5382:       fprintf(ficgp,"\nset out\n");
                   5383:     } /* end cpt state*/ 
                   5384:   } /* end covariate */  
                   5385: 
1.202     brouard  5386:   /* CV preval stable (period) for each covariate */
1.211     brouard  5387:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5388:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5389:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5390:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5391:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5392:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5393:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5394:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5395:        vlv= nbcode[Tvaraff[lv]][lv];
                   5396:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5397:       }
                   5398:       fprintf(ficgp,"\n#\n");
                   5399: 
1.201     brouard  5400:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5401:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5402: set ter svg size 640, 480\n\
1.126     brouard  5403: unset log y\n\
1.153     brouard  5404: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5405:       k=3; /* Offset */
1.153     brouard  5406:       for (i=1; i<= nlstate ; i ++){
                   5407:        if(i==1)
1.201     brouard  5408:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5409:        else
                   5410:          fprintf(ficgp,", '' ");
1.154     brouard  5411:        l=(nlstate+ndeath)*(i-1)+1;
                   5412:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5413:        for (j=2; j<= nlstate ; j ++)
                   5414:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5415:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5416:       } /* nlstate */
1.201     brouard  5417:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5418:     } /* end cpt state*/ 
                   5419:   } /* end covariate */  
1.201     brouard  5420: 
1.211     brouard  5421:   if(prevfcast==1){
                   5422:   /* Projection from cross-sectional to stable (period) for each covariate */
                   5423: 
                   5424:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   5425:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5426:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   5427:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   5428:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5429:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5430:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5431:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5432:          vlv= nbcode[Tvaraff[lv]][lv];
                   5433:          fprintf(ficgp," V%d=%d ",k,vlv);
                   5434:        }
                   5435:        fprintf(ficgp,"\n#\n");
                   5436:        
                   5437:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   5438:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   5439:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   5440: set ter svg size 640, 480\n\
                   5441: unset log y\n\
                   5442: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5443:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   5444:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5445:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5446:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5447:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5448:          if(i==1){
                   5449:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   5450:          }else{
                   5451:            fprintf(ficgp,",\\\n '' ");
                   5452:          }
                   5453:          if(cptcoveff ==0){ /* No covariate */
                   5454:            fprintf(ficgp," u 2:("); /* Age is in 2 */
                   5455:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   5456:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   5457:            if(i==nlstate+1)
                   5458:              fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
                   5459:                        2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5460:            else
                   5461:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
                   5462:                      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5463:          }else{
                   5464:            fprintf(ficgp,"u 6:(("); /* Age is in 6 */
                   5465:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5466:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5467:            kl=0;
                   5468:            for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
                   5469:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5470:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5471:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5472:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5473:              vlv= nbcode[Tvaraff[lv]][lv];
                   5474:              kl++;
                   5475:              /* 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 *\/ */
                   5476:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5477:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5478:              /* ''  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*/
                   5479:              if(k==cptcoveff)
                   5480:                if(i==nlstate+1)
                   5481:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5482:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5483:                else
                   5484:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5485:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5486:              else{
                   5487:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
                   5488:                kl++;
                   5489:              }
                   5490:            } /* end covariate */
                   5491:          } /* end if covariate */
                   5492:        } /* nlstate */
                   5493:        fprintf(ficgp,"\nset out\n");
                   5494:       } /* end cpt state*/
                   5495:     } /* end covariate */
                   5496:   } /* End if prevfcast */
                   5497: 
                   5498: 
1.126     brouard  5499:   /* proba elementaires */
1.187     brouard  5500:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5501:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5502:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5503:     for(k=1; k <=(nlstate+ndeath); k++){
                   5504:       if (k != i) {
1.187     brouard  5505:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5506:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5507:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5508:          jk++; 
                   5509:        }
1.187     brouard  5510:        fprintf(ficgp,"\n");
1.126     brouard  5511:       }
                   5512:     }
                   5513:    }
1.187     brouard  5514:   fprintf(ficgp,"##############\n#\n");
                   5515: 
1.145     brouard  5516:   /*goto avoid;*/
1.200     brouard  5517:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5518:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5519:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5520:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5521:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5522:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5523:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5524:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5525:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5526:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5527:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5528:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5529:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5530:   fprintf(ficgp,"#\n");
1.201     brouard  5531:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5532:      fprintf(ficgp,"# ng=%d\n",ng);
                   5533:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5534:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5535:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5536:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5537:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5538:        if (ng==1){
                   5539:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5540:         fprintf(ficgp,"\nunset log y");
                   5541:        }else if (ng==2){
                   5542:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5543:         fprintf(ficgp,"\nset log y");
                   5544:        }else if (ng==3){
1.126     brouard  5545:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5546:         fprintf(ficgp,"\nset log y");
                   5547:        }else
                   5548:         fprintf(ficgp,"\nunset title ");
                   5549:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5550:        i=1;
                   5551:        for(k2=1; k2<=nlstate; k2++) {
                   5552:         k3=i;
                   5553:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5554:           if (k != k2){
1.201     brouard  5555:             switch( ng) {
                   5556:             case 1:
1.187     brouard  5557:               if(nagesqr==0)
1.201     brouard  5558:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5559:               else /* nagesqr =1 */
1.201     brouard  5560:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5561:               break;
                   5562:             case 2: /* ng=2 */
1.187     brouard  5563:               if(nagesqr==0)
                   5564:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5565:               else /* nagesqr =1 */
1.201     brouard  5566:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5567:               break;
                   5568:             case 3:
                   5569:               if(nagesqr==0)
                   5570:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5571:               else /* nagesqr =1 */
                   5572:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5573:               break;
                   5574:             }
1.141     brouard  5575:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5576:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5577:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5578:               if(ij <=cptcovage) { /* Bug valgrind */
                   5579:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5580:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5581:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5582:                   ij++;
                   5583:                 }
1.186     brouard  5584:               }
                   5585:               else
1.198     brouard  5586:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5587:             }
1.201     brouard  5588:             if(ng != 1){
                   5589:               fprintf(ficgp,")/(1");
1.126     brouard  5590:             
1.201     brouard  5591:               for(k1=1; k1 <=nlstate; k1++){ 
                   5592:                 if(nagesqr==0)
                   5593:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5594:                 else /* nagesqr =1 */
                   5595:                   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);
                   5596:                 
                   5597:                 ij=1;
                   5598:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5599:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5600:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5601:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5602:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5603:                       ij++;
                   5604:                     }
1.197     brouard  5605:                   }
1.201     brouard  5606:                   else
                   5607:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5608:                 }
1.201     brouard  5609:                 fprintf(ficgp,")");
1.126     brouard  5610:               }
                   5611:               fprintf(ficgp,")");
1.201     brouard  5612:               if(ng ==2)
                   5613:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5614:               else /* ng= 3 */
                   5615:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5616:             }else{ /* end ng <> 1 */
                   5617:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5618:             }
                   5619:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5620:             i=i+ncovmodel;
                   5621:           }
                   5622:         } /* end k */
                   5623:        } /* end k2 */
1.201     brouard  5624:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5625:      } /* end jk */
                   5626:    } /* end ng */
1.164     brouard  5627:  /* avoid: */
1.126     brouard  5628:    fflush(ficgp); 
                   5629: }  /* end gnuplot */
                   5630: 
                   5631: 
                   5632: /*************** Moving average **************/
                   5633: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5634: 
                   5635:   int i, cpt, cptcod;
                   5636:   int modcovmax =1;
                   5637:   int mobilavrange, mob;
                   5638:   double age;
                   5639: 
                   5640:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5641:                           a covariate has 2 modalities */
                   5642:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5643: 
                   5644:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5645:     if(mobilav==1) mobilavrange=5; /* default */
                   5646:     else mobilavrange=mobilav;
                   5647:     for (age=bage; age<=fage; age++)
                   5648:       for (i=1; i<=nlstate;i++)
                   5649:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5650:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5651:     /* We keep the original values on the extreme ages bage, fage and for 
                   5652:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5653:        we use a 5 terms etc. until the borders are no more concerned. 
                   5654:     */ 
                   5655:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5656:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5657:        for (i=1; i<=nlstate;i++){
                   5658:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5659:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5660:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5661:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5662:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5663:              }
                   5664:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5665:          }
                   5666:        }
                   5667:       }/* end age */
                   5668:     }/* end mob */
                   5669:   }else return -1;
                   5670:   return 0;
                   5671: }/* End movingaverage */
                   5672: 
                   5673: 
                   5674: /************** Forecasting ******************/
1.169     brouard  5675: 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  5676:   /* proj1, year, month, day of starting projection 
                   5677:      agemin, agemax range of age
                   5678:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5679:      anproj2 year of en of projection (same day and month as proj1).
                   5680:   */
1.164     brouard  5681:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5682:   double agec; /* generic age */
                   5683:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5684:   double *popeffectif,*popcount;
                   5685:   double ***p3mat;
                   5686:   double ***mobaverage;
                   5687:   char fileresf[FILENAMELENGTH];
                   5688: 
                   5689:   agelim=AGESUP;
1.211     brouard  5690:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5691:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5692:      We still use firstpass and lastpass as another selection.
                   5693:   */
1.214   ! brouard  5694:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
        !          5695:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  5696:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5697:  
1.201     brouard  5698:   strcpy(fileresf,"F_"); 
                   5699:   strcat(fileresf,fileresu);
1.126     brouard  5700:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5701:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5702:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5703:   }
                   5704:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5705:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5706: 
                   5707:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5708: 
                   5709:   if (mobilav!=0) {
                   5710:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5711:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5712:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5713:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5714:     }
                   5715:   }
                   5716: 
                   5717:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5718:   if (stepm<=12) stepsize=1;
                   5719:   if(estepm < stepm){
                   5720:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5721:   }
                   5722:   else  hstepm=estepm;   
                   5723: 
                   5724:   hstepm=hstepm/stepm; 
                   5725:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5726:                                fractional in yp1 */
                   5727:   anprojmean=yp;
                   5728:   yp2=modf((yp1*12),&yp);
                   5729:   mprojmean=yp;
                   5730:   yp1=modf((yp2*30.5),&yp);
                   5731:   jprojmean=yp;
                   5732:   if(jprojmean==0) jprojmean=1;
                   5733:   if(mprojmean==0) jprojmean=1;
                   5734: 
                   5735:   i1=cptcoveff;
                   5736:   if (cptcovn < 1){i1=1;}
                   5737:   
                   5738:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5739:   
                   5740:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5741: 
                   5742: /*           if (h==(int)(YEARM*yearp)){ */
                   5743:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5744:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5745:       k=k+1;
1.211     brouard  5746:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  5747:       for(j=1;j<=cptcoveff;j++) {
1.211     brouard  5748:        fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5749:       }
1.211     brouard  5750:       fprintf(ficresf," yearproj age");
1.126     brouard  5751:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5752:        for(i=1; i<=nlstate;i++)              
                   5753:           fprintf(ficresf," p%d%d",i,j);
                   5754:        fprintf(ficresf," p.%d",j);
                   5755:       }
                   5756:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5757:        fprintf(ficresf,"\n");
                   5758:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5759: 
                   5760:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5761:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5762:          nhstepm = nhstepm/hstepm; 
                   5763:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5764:          oldm=oldms;savm=savms;
                   5765:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5766:        
                   5767:          for (h=0; h<=nhstepm; h++){
                   5768:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5769:               fprintf(ficresf,"\n");
                   5770:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5771:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5772:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5773:            } 
                   5774:            for(j=1; j<=nlstate+ndeath;j++) {
                   5775:              ppij=0.;
                   5776:              for(i=1; i<=nlstate;i++) {
                   5777:                if (mobilav==1) 
                   5778:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5779:                else {
                   5780:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5781:                }
                   5782:                if (h*hstepm/YEARM*stepm== yearp) {
                   5783:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5784:                }
                   5785:              } /* end i */
                   5786:              if (h*hstepm/YEARM*stepm==yearp) {
                   5787:                fprintf(ficresf," %.3f", ppij);
                   5788:              }
                   5789:            }/* end j */
                   5790:          } /* end h */
                   5791:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5792:        } /* end agec */
                   5793:       } /* end yearp */
                   5794:     } /* end cptcod */
                   5795:   } /* end  cptcov */
                   5796:        
                   5797:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5798: 
                   5799:   fclose(ficresf);
                   5800: }
                   5801: 
                   5802: /************** Forecasting *****not tested NB*************/
1.169     brouard  5803: 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  5804:   
                   5805:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5806:   int *popage;
                   5807:   double calagedatem, agelim, kk1, kk2;
                   5808:   double *popeffectif,*popcount;
                   5809:   double ***p3mat,***tabpop,***tabpopprev;
                   5810:   double ***mobaverage;
                   5811:   char filerespop[FILENAMELENGTH];
                   5812: 
                   5813:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5814:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5815:   agelim=AGESUP;
                   5816:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5817:   
                   5818:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5819:   
                   5820:   
1.201     brouard  5821:   strcpy(filerespop,"POP_"); 
                   5822:   strcat(filerespop,fileresu);
1.126     brouard  5823:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5824:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5825:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5826:   }
                   5827:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5828:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5829: 
                   5830:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5831: 
                   5832:   if (mobilav!=0) {
                   5833:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5834:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5835:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5836:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5837:     }
                   5838:   }
                   5839: 
                   5840:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5841:   if (stepm<=12) stepsize=1;
                   5842:   
                   5843:   agelim=AGESUP;
                   5844:   
                   5845:   hstepm=1;
                   5846:   hstepm=hstepm/stepm; 
                   5847:   
                   5848:   if (popforecast==1) {
                   5849:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5850:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5851:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5852:     } 
                   5853:     popage=ivector(0,AGESUP);
                   5854:     popeffectif=vector(0,AGESUP);
                   5855:     popcount=vector(0,AGESUP);
                   5856:     
                   5857:     i=1;   
                   5858:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5859:    
                   5860:     imx=i;
                   5861:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5862:   }
                   5863: 
                   5864:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5865:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5866:       k=k+1;
                   5867:       fprintf(ficrespop,"\n#******");
                   5868:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5869:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5870:       }
                   5871:       fprintf(ficrespop,"******\n");
                   5872:       fprintf(ficrespop,"# Age");
                   5873:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5874:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5875:       
                   5876:       for (cpt=0; cpt<=0;cpt++) { 
                   5877:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5878:        
                   5879:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5880:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5881:          nhstepm = nhstepm/hstepm; 
                   5882:          
                   5883:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5884:          oldm=oldms;savm=savms;
                   5885:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5886:        
                   5887:          for (h=0; h<=nhstepm; h++){
                   5888:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5889:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5890:            } 
                   5891:            for(j=1; j<=nlstate+ndeath;j++) {
                   5892:              kk1=0.;kk2=0;
                   5893:              for(i=1; i<=nlstate;i++) {              
                   5894:                if (mobilav==1) 
                   5895:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5896:                else {
                   5897:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5898:                }
                   5899:              }
                   5900:              if (h==(int)(calagedatem+12*cpt)){
                   5901:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5902:                  /*fprintf(ficrespop," %.3f", kk1);
                   5903:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5904:              }
                   5905:            }
                   5906:            for(i=1; i<=nlstate;i++){
                   5907:              kk1=0.;
                   5908:                for(j=1; j<=nlstate;j++){
                   5909:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5910:                }
                   5911:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5912:            }
                   5913: 
                   5914:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5915:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5916:          }
                   5917:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5918:        }
                   5919:       }
                   5920:  
                   5921:   /******/
                   5922: 
                   5923:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5924:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5925:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5926:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5927:          nhstepm = nhstepm/hstepm; 
                   5928:          
                   5929:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5930:          oldm=oldms;savm=savms;
                   5931:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5932:          for (h=0; h<=nhstepm; h++){
                   5933:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5934:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5935:            } 
                   5936:            for(j=1; j<=nlstate+ndeath;j++) {
                   5937:              kk1=0.;kk2=0;
                   5938:              for(i=1; i<=nlstate;i++) {              
                   5939:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5940:              }
                   5941:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5942:            }
                   5943:          }
                   5944:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5945:        }
                   5946:       }
                   5947:    } 
                   5948:   }
                   5949:  
                   5950:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5951: 
                   5952:   if (popforecast==1) {
                   5953:     free_ivector(popage,0,AGESUP);
                   5954:     free_vector(popeffectif,0,AGESUP);
                   5955:     free_vector(popcount,0,AGESUP);
                   5956:   }
                   5957:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5958:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5959:   fclose(ficrespop);
                   5960: } /* End of popforecast */
                   5961: 
                   5962: int fileappend(FILE *fichier, char *optionfich)
                   5963: {
                   5964:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5965:     printf("Problem with file: %s\n", optionfich);
                   5966:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5967:     return (0);
                   5968:   }
                   5969:   fflush(fichier);
                   5970:   return (1);
                   5971: }
                   5972: 
                   5973: 
                   5974: /**************** function prwizard **********************/
                   5975: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5976: {
                   5977: 
                   5978:   /* Wizard to print covariance matrix template */
                   5979: 
1.164     brouard  5980:   char ca[32], cb[32];
                   5981:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5982:   int numlinepar;
                   5983: 
                   5984:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5985:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5986:   for(i=1; i <=nlstate; i++){
                   5987:     jj=0;
                   5988:     for(j=1; j <=nlstate+ndeath; j++){
                   5989:       if(j==i) continue;
                   5990:       jj++;
                   5991:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5992:       printf("%1d%1d",i,j);
                   5993:       fprintf(ficparo,"%1d%1d",i,j);
                   5994:       for(k=1; k<=ncovmodel;k++){
                   5995:        /*        printf(" %lf",param[i][j][k]); */
                   5996:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5997:        printf(" 0.");
                   5998:        fprintf(ficparo," 0.");
                   5999:       }
                   6000:       printf("\n");
                   6001:       fprintf(ficparo,"\n");
                   6002:     }
                   6003:   }
                   6004:   printf("# Scales (for hessian or gradient estimation)\n");
                   6005:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6006:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6007:   for(i=1; i <=nlstate; i++){
                   6008:     jj=0;
                   6009:     for(j=1; j <=nlstate+ndeath; j++){
                   6010:       if(j==i) continue;
                   6011:       jj++;
                   6012:       fprintf(ficparo,"%1d%1d",i,j);
                   6013:       printf("%1d%1d",i,j);
                   6014:       fflush(stdout);
                   6015:       for(k=1; k<=ncovmodel;k++){
                   6016:        /*      printf(" %le",delti3[i][j][k]); */
                   6017:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6018:        printf(" 0.");
                   6019:        fprintf(ficparo," 0.");
                   6020:       }
                   6021:       numlinepar++;
                   6022:       printf("\n");
                   6023:       fprintf(ficparo,"\n");
                   6024:     }
                   6025:   }
                   6026:   printf("# Covariance matrix\n");
                   6027: /* # 121 Var(a12)\n\ */
                   6028: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6029: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6030: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6031: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6032: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6033: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6034: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6035:   fflush(stdout);
                   6036:   fprintf(ficparo,"# Covariance matrix\n");
                   6037:   /* # 121 Var(a12)\n\ */
                   6038:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6039:   /* #   ...\n\ */
                   6040:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6041:   
                   6042:   for(itimes=1;itimes<=2;itimes++){
                   6043:     jj=0;
                   6044:     for(i=1; i <=nlstate; i++){
                   6045:       for(j=1; j <=nlstate+ndeath; j++){
                   6046:        if(j==i) continue;
                   6047:        for(k=1; k<=ncovmodel;k++){
                   6048:          jj++;
                   6049:          ca[0]= k+'a'-1;ca[1]='\0';
                   6050:          if(itimes==1){
                   6051:            printf("#%1d%1d%d",i,j,k);
                   6052:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6053:          }else{
                   6054:            printf("%1d%1d%d",i,j,k);
                   6055:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6056:            /*  printf(" %.5le",matcov[i][j]); */
                   6057:          }
                   6058:          ll=0;
                   6059:          for(li=1;li <=nlstate; li++){
                   6060:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6061:              if(lj==li) continue;
                   6062:              for(lk=1;lk<=ncovmodel;lk++){
                   6063:                ll++;
                   6064:                if(ll<=jj){
                   6065:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6066:                  if(ll<jj){
                   6067:                    if(itimes==1){
                   6068:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6069:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6070:                    }else{
                   6071:                      printf(" 0.");
                   6072:                      fprintf(ficparo," 0.");
                   6073:                    }
                   6074:                  }else{
                   6075:                    if(itimes==1){
                   6076:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6077:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6078:                    }else{
                   6079:                      printf(" 0.");
                   6080:                      fprintf(ficparo," 0.");
                   6081:                    }
                   6082:                  }
                   6083:                }
                   6084:              } /* end lk */
                   6085:            } /* end lj */
                   6086:          } /* end li */
                   6087:          printf("\n");
                   6088:          fprintf(ficparo,"\n");
                   6089:          numlinepar++;
                   6090:        } /* end k*/
                   6091:       } /*end j */
                   6092:     } /* end i */
                   6093:   } /* end itimes */
                   6094: 
                   6095: } /* end of prwizard */
                   6096: /******************* Gompertz Likelihood ******************************/
                   6097: double gompertz(double x[])
                   6098: { 
                   6099:   double A,B,L=0.0,sump=0.,num=0.;
                   6100:   int i,n=0; /* n is the size of the sample */
                   6101: 
                   6102:   for (i=0;i<=imx-1 ; i++) {
                   6103:     sump=sump+weight[i];
                   6104:     /*    sump=sump+1;*/
                   6105:     num=num+1;
                   6106:   }
                   6107:  
                   6108:  
                   6109:   /* for (i=0; i<=imx; i++) 
                   6110:      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]);*/
                   6111: 
                   6112:   for (i=1;i<=imx ; i++)
                   6113:     {
                   6114:       if (cens[i] == 1 && wav[i]>1)
                   6115:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   6116:       
                   6117:       if (cens[i] == 0 && wav[i]>1)
                   6118:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   6119:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   6120:       
                   6121:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6122:       if (wav[i] > 1 ) { /* ??? */
                   6123:        L=L+A*weight[i];
                   6124:        /*      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]);*/
                   6125:       }
                   6126:     }
                   6127: 
                   6128:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6129:  
                   6130:   return -2*L*num/sump;
                   6131: }
                   6132: 
1.136     brouard  6133: #ifdef GSL
                   6134: /******************* Gompertz_f Likelihood ******************************/
                   6135: double gompertz_f(const gsl_vector *v, void *params)
                   6136: { 
                   6137:   double A,B,LL=0.0,sump=0.,num=0.;
                   6138:   double *x= (double *) v->data;
                   6139:   int i,n=0; /* n is the size of the sample */
                   6140: 
                   6141:   for (i=0;i<=imx-1 ; i++) {
                   6142:     sump=sump+weight[i];
                   6143:     /*    sump=sump+1;*/
                   6144:     num=num+1;
                   6145:   }
                   6146:  
                   6147:  
                   6148:   /* for (i=0; i<=imx; i++) 
                   6149:      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]);*/
                   6150:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   6151:   for (i=1;i<=imx ; i++)
                   6152:     {
                   6153:       if (cens[i] == 1 && wav[i]>1)
                   6154:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   6155:       
                   6156:       if (cens[i] == 0 && wav[i]>1)
                   6157:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   6158:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   6159:       
                   6160:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6161:       if (wav[i] > 1 ) { /* ??? */
                   6162:        LL=LL+A*weight[i];
                   6163:        /*      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]);*/
                   6164:       }
                   6165:     }
                   6166: 
                   6167:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6168:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6169:  
                   6170:   return -2*LL*num/sump;
                   6171: }
                   6172: #endif
                   6173: 
1.126     brouard  6174: /******************* Printing html file ***********/
1.201     brouard  6175: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6176:                  int lastpass, int stepm, int weightopt, char model[],\
                   6177:                  int imx,  double p[],double **matcov,double agemortsup){
                   6178:   int i,k;
                   6179: 
                   6180:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   6181:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   6182:   for (i=1;i<=2;i++) 
                   6183:     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  6184:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  6185:   fprintf(fichtm,"</ul>");
                   6186: 
                   6187: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   6188: 
                   6189:  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>");
                   6190: 
                   6191:  for (k=agegomp;k<(agemortsup-2);k++) 
                   6192:    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]);
                   6193: 
                   6194:  
                   6195:   fflush(fichtm);
                   6196: }
                   6197: 
                   6198: /******************* Gnuplot file **************/
1.201     brouard  6199: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  6200: 
                   6201:   char dirfileres[132],optfileres[132];
1.164     brouard  6202: 
1.126     brouard  6203:   int ng;
                   6204: 
                   6205: 
                   6206:   /*#ifdef windows */
                   6207:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   6208:     /*#endif */
                   6209: 
                   6210: 
                   6211:   strcpy(dirfileres,optionfilefiname);
                   6212:   strcpy(optfileres,"vpl");
1.199     brouard  6213:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  6214:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  6215:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  6216:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  6217:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   6218: 
                   6219: } 
                   6220: 
1.136     brouard  6221: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   6222: {
1.126     brouard  6223: 
1.136     brouard  6224:   /*-------- data file ----------*/
                   6225:   FILE *fic;
                   6226:   char dummy[]="                         ";
1.164     brouard  6227:   int i=0, j=0, n=0;
1.136     brouard  6228:   int linei, month, year,iout;
                   6229:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  6230:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  6231:   char *stratrunc;
                   6232:   int lstra;
1.126     brouard  6233: 
                   6234: 
1.136     brouard  6235:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  6236:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   6237:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  6238:   }
1.126     brouard  6239: 
1.136     brouard  6240:   i=1;
                   6241:   linei=0;
                   6242:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   6243:     linei=linei+1;
                   6244:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   6245:       if(line[j] == '\t')
                   6246:        line[j] = ' ';
                   6247:     }
                   6248:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   6249:       ;
                   6250:     };
                   6251:     line[j+1]=0;  /* Trims blanks at end of line */
                   6252:     if(line[0]=='#'){
                   6253:       fprintf(ficlog,"Comment line\n%s\n",line);
                   6254:       printf("Comment line\n%s\n",line);
                   6255:       continue;
                   6256:     }
                   6257:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  6258:     strcpy(line, linetmp);
1.136     brouard  6259:   
1.126     brouard  6260: 
1.136     brouard  6261:     for (j=maxwav;j>=1;j--){
1.137     brouard  6262:       cutv(stra, strb, line, ' '); 
1.136     brouard  6263:       if(strb[0]=='.') { /* Missing status */
                   6264:        lval=-1;
                   6265:       }else{
                   6266:        errno=0;
                   6267:        lval=strtol(strb,&endptr,10); 
                   6268:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   6269:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6270:          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);
                   6271:          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  6272:          return 1;
                   6273:        }
                   6274:       }
                   6275:       s[j][i]=lval;
                   6276:       
                   6277:       strcpy(line,stra);
                   6278:       cutv(stra, strb,line,' ');
1.169     brouard  6279:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6280:       }
1.169     brouard  6281:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6282:        month=99;
                   6283:        year=9999;
                   6284:       }else{
1.141     brouard  6285:        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);
                   6286:        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  6287:        return 1;
                   6288:       }
                   6289:       anint[j][i]= (double) year; 
                   6290:       mint[j][i]= (double)month; 
                   6291:       strcpy(line,stra);
                   6292:     } /* ENd Waves */
                   6293:     
                   6294:     cutv(stra, strb,line,' '); 
1.169     brouard  6295:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6296:     }
1.169     brouard  6297:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6298:       month=99;
                   6299:       year=9999;
                   6300:     }else{
1.141     brouard  6301:       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);
                   6302:        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  6303:        return 1;
                   6304:     }
                   6305:     andc[i]=(double) year; 
                   6306:     moisdc[i]=(double) month; 
                   6307:     strcpy(line,stra);
                   6308:     
                   6309:     cutv(stra, strb,line,' '); 
1.169     brouard  6310:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6311:     }
1.169     brouard  6312:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  6313:       month=99;
                   6314:       year=9999;
                   6315:     }else{
1.141     brouard  6316:       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);
                   6317:       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  6318:        return 1;
                   6319:     }
                   6320:     if (year==9999) {
1.141     brouard  6321:       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);
                   6322:       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  6323:        return 1;
1.126     brouard  6324: 
1.136     brouard  6325:     }
                   6326:     annais[i]=(double)(year);
                   6327:     moisnais[i]=(double)(month); 
                   6328:     strcpy(line,stra);
                   6329:     
                   6330:     cutv(stra, strb,line,' '); 
                   6331:     errno=0;
                   6332:     dval=strtod(strb,&endptr); 
                   6333:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6334:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6335:       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  6336:       fflush(ficlog);
                   6337:       return 1;
                   6338:     }
                   6339:     weight[i]=dval; 
                   6340:     strcpy(line,stra);
                   6341:     
                   6342:     for (j=ncovcol;j>=1;j--){
                   6343:       cutv(stra, strb,line,' '); 
                   6344:       if(strb[0]=='.') { /* Missing status */
                   6345:        lval=-1;
                   6346:       }else{
                   6347:        errno=0;
                   6348:        lval=strtol(strb,&endptr,10); 
                   6349:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6350:          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);
                   6351:          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  6352:          return 1;
                   6353:        }
                   6354:       }
                   6355:       if(lval <-1 || lval >1){
1.141     brouard  6356:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6357:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6358:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6359:  For example, for multinomial values like 1, 2 and 3,\n \
                   6360:  build V1=0 V2=0 for the reference value (1),\n \
                   6361:         V1=1 V2=0 for (2) \n \
                   6362:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6363:  output of IMaCh is often meaningless.\n \
                   6364:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6365:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6366:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6367:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6368:  For example, for multinomial values like 1, 2 and 3,\n \
                   6369:  build V1=0 V2=0 for the reference value (1),\n \
                   6370:         V1=1 V2=0 for (2) \n \
                   6371:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6372:  output of IMaCh is often meaningless.\n \
                   6373:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6374:        return 1;
                   6375:       }
                   6376:       covar[j][i]=(double)(lval);
                   6377:       strcpy(line,stra);
                   6378:     }  
                   6379:     lstra=strlen(stra);
                   6380:      
                   6381:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6382:       stratrunc = &(stra[lstra-9]);
                   6383:       num[i]=atol(stratrunc);
                   6384:     }
                   6385:     else
                   6386:       num[i]=atol(stra);
                   6387:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6388:       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;}*/
                   6389:     
                   6390:     i=i+1;
                   6391:   } /* End loop reading  data */
1.126     brouard  6392: 
1.136     brouard  6393:   *imax=i-1; /* Number of individuals */
                   6394:   fclose(fic);
                   6395:  
                   6396:   return (0);
1.164     brouard  6397:   /* endread: */
1.136     brouard  6398:     printf("Exiting readdata: ");
                   6399:     fclose(fic);
                   6400:     return (1);
1.126     brouard  6401: 
                   6402: 
                   6403: 
1.136     brouard  6404: }
1.145     brouard  6405: void removespace(char *str) {
                   6406:   char *p1 = str, *p2 = str;
                   6407:   do
                   6408:     while (*p2 == ' ')
                   6409:       p2++;
1.169     brouard  6410:   while (*p1++ == *p2++);
1.145     brouard  6411: }
                   6412: 
                   6413: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6414:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6415:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6416:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6417:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6418:    * - cptcovage number of covariates with age*products =2
                   6419:    * - cptcovs number of simple covariates
                   6420:    * - 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
                   6421:    *     which is a new column after the 9 (ncovcol) variables. 
                   6422:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6423:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6424:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6425:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6426:  */
1.136     brouard  6427: {
1.145     brouard  6428:   int i, j, k, ks;
1.164     brouard  6429:   int  j1, k1, k2;
1.136     brouard  6430:   char modelsav[80];
1.145     brouard  6431:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6432:   char *strpt;
1.136     brouard  6433: 
1.145     brouard  6434:   /*removespace(model);*/
1.136     brouard  6435:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6436:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6437:     if (strstr(model,"AGE") !=0){
1.192     brouard  6438:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6439:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6440:       return 1;
                   6441:     }
1.141     brouard  6442:     if (strstr(model,"v") !=0){
                   6443:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6444:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6445:       return 1;
                   6446:     }
1.187     brouard  6447:     strcpy(modelsav,model); 
                   6448:     if ((strpt=strstr(model,"age*age")) !=0){
                   6449:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6450:       if(strpt != model){
                   6451:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6452:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6453:  corresponding column of parameters.\n",model);
                   6454:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6455:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6456:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6457:       return 1;
                   6458:     }
                   6459: 
                   6460:       nagesqr=1;
                   6461:       if (strstr(model,"+age*age") !=0)
                   6462:        substrchaine(modelsav, model, "+age*age");
                   6463:       else if (strstr(model,"age*age+") !=0)
                   6464:        substrchaine(modelsav, model, "age*age+");
                   6465:       else 
                   6466:        substrchaine(modelsav, model, "age*age");
                   6467:     }else
                   6468:       nagesqr=0;
                   6469:     if (strlen(modelsav) >1){
                   6470:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6471:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6472:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6473:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6474:                   * cst, age and age*age 
                   6475:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6476:                   /* including age products which are counted in cptcovage.
                   6477:                  * but the covariates which are products must be treated 
                   6478:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6479:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6480:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6481: 
                   6482:     
                   6483:       /*   Design
                   6484:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6485:        *  <          ncovcol=8                >
                   6486:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6487:        *   k=  1    2      3       4     5       6      7        8
                   6488:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6489:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6490:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6491:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6492:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6493:        *  Tage[++cptcovage]=k
                   6494:        *       if products, new covar are created after ncovcol with k1
                   6495:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6496:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6497:        *  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
                   6498:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6499:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6500:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6501:        *  <          ncovcol=8                >
                   6502:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6503:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6504:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6505:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6506:        * p Tprod[1]@2={                         6, 5}
                   6507:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6508:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6509:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6510:        *How to reorganize?
                   6511:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6512:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6513:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6514:        * Struct []
                   6515:        */
1.145     brouard  6516: 
1.187     brouard  6517:       /* This loop fills the array Tvar from the string 'model'.*/
                   6518:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6519:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6520:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6521:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6522:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6523:       /*       k=1 Tvar[1]=2 (from V2) */
                   6524:       /*       k=5 Tvar[5] */
                   6525:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6526:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6527:       /*       } */
1.198     brouard  6528:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6529:       /*
                   6530:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6531:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6532:         Tvar[k]=0;
1.187     brouard  6533:       cptcovage=0;
                   6534:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6535:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6536:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6537:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6538:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6539:        /*scanf("%d",i);*/
                   6540:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6541:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6542:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6543:            /* covar is not filled and then is empty */
                   6544:            cptcovprod--;
                   6545:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6546:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6547:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6548:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6549:            /*printf("stre=%s ", stre);*/
                   6550:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6551:            cptcovprod--;
                   6552:            cutl(stre,strb,strc,'V');
                   6553:            Tvar[k]=atoi(stre);
                   6554:            cptcovage++;
                   6555:            Tage[cptcovage]=k;
                   6556:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6557:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6558:            cptcovn++;
                   6559:            cptcovprodnoage++;k1++;
                   6560:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6561:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6562:                                   because this model-covariate is a construction we invent a new column
                   6563:                                   ncovcol + k1
                   6564:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6565:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6566:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6567:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6568:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6569:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6570:            k2=k2+2;
                   6571:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6572:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6573:            for (i=1; i<=lastobs;i++){
                   6574:              /* Computes the new covariate which is a product of
                   6575:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6576:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6577:            }
                   6578:          } /* End age is not in the model */
                   6579:        } /* End if model includes a product */
                   6580:        else { /* no more sum */
                   6581:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6582:          /*  scanf("%d",i);*/
                   6583:          cutl(strd,strc,strb,'V');
                   6584:          ks++; /**< Number of simple covariates */
1.145     brouard  6585:          cptcovn++;
1.187     brouard  6586:          Tvar[k]=atoi(strd);
                   6587:        }
                   6588:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6589:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6590:          scanf("%d",i);*/
                   6591:       } /* end of loop + on total covariates */
                   6592:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6593:   } /* end if strlen(model == 0) */
1.136     brouard  6594:   
                   6595:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6596:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6597: 
                   6598:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6599:   printf("cptcovprod=%d ", cptcovprod);
                   6600:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6601: 
                   6602:   scanf("%d ",i);*/
                   6603: 
                   6604: 
1.137     brouard  6605:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6606:   /*endread:*/
1.136     brouard  6607:     printf("Exiting decodemodel: ");
                   6608:     return (1);
                   6609: }
                   6610: 
1.169     brouard  6611: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6612: {
                   6613:   int i, m;
                   6614: 
                   6615:   for (i=1; i<=imx; i++) {
                   6616:     for(m=2; (m<= maxwav); m++) {
                   6617:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6618:        anint[m][i]=9999;
                   6619:        s[m][i]=-1;
                   6620:       }
                   6621:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6622:        *nberr = *nberr + 1;
                   6623:        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 are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
                   6624:        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 are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136     brouard  6625:        s[m][i]=-1;
                   6626:       }
                   6627:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6628:        (*nberr)++;
1.136     brouard  6629:        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]); 
                   6630:        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]); 
                   6631:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6632:       }
                   6633:     }
                   6634:   }
                   6635: 
                   6636:   for (i=1; i<=imx; i++)  {
                   6637:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6638:     for(m=firstpass; (m<= lastpass); m++){
1.214   ! brouard  6639:       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  6640:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6641:          if(agedc[i]>0){
                   6642:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6643:              agev[m][i]=agedc[i];
1.214   ! brouard  6644:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6645:            }else {
1.136     brouard  6646:              if ((int)andc[i]!=9999){
                   6647:                nbwarn++;
                   6648:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6649:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6650:                agev[m][i]=-1;
                   6651:              }
                   6652:            }
1.169     brouard  6653:          } /* agedc > 0 */
1.214   ! brouard  6654:        } /* end if */
1.136     brouard  6655:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6656:                                 years but with the precision of a month */
                   6657:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6658:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6659:            agev[m][i]=1;
                   6660:          else if(agev[m][i] < *agemin){ 
                   6661:            *agemin=agev[m][i];
                   6662:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6663:          }
                   6664:          else if(agev[m][i] >*agemax){
                   6665:            *agemax=agev[m][i];
1.156     brouard  6666:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6667:          }
                   6668:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6669:          /*     agev[m][i] = age[i]+2*m;*/
1.214   ! brouard  6670:        } /* en if 9*/
1.136     brouard  6671:        else { /* =9 */
1.214   ! brouard  6672:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  6673:          agev[m][i]=1;
                   6674:          s[m][i]=-1;
                   6675:        }
                   6676:       }
1.214   ! brouard  6677:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  6678:        agev[m][i]=1;
1.214   ! brouard  6679:       else{
        !          6680:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
        !          6681:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
        !          6682:        agev[m][i]=0;
        !          6683:       }
        !          6684:     } /* End for lastpass */
        !          6685:   }
1.136     brouard  6686:     
                   6687:   for (i=1; i<=imx; i++)  {
                   6688:     for(m=firstpass; (m<=lastpass); m++){
                   6689:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6690:        (*nberr)++;
1.136     brouard  6691:        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);     
                   6692:        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);     
                   6693:        return 1;
                   6694:       }
                   6695:     }
                   6696:   }
                   6697: 
                   6698:   /*for (i=1; i<=imx; i++){
                   6699:   for (m=firstpass; (m<lastpass); m++){
                   6700:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6701: }
                   6702: 
                   6703: }*/
                   6704: 
                   6705: 
1.139     brouard  6706:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6707:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6708: 
                   6709:   return (0);
1.164     brouard  6710:  /* endread:*/
1.136     brouard  6711:     printf("Exiting calandcheckages: ");
                   6712:     return (1);
                   6713: }
                   6714: 
1.172     brouard  6715: #if defined(_MSC_VER)
                   6716: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6717: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6718: //#include "stdafx.h"
                   6719: //#include <stdio.h>
                   6720: //#include <tchar.h>
                   6721: //#include <windows.h>
                   6722: //#include <iostream>
                   6723: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6724: 
                   6725: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6726: 
                   6727: BOOL IsWow64()
                   6728: {
                   6729:        BOOL bIsWow64 = FALSE;
                   6730: 
                   6731:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6732:        //  (HANDLE, PBOOL);
                   6733: 
                   6734:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6735: 
                   6736:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6737:        const char funcName[] = "IsWow64Process";
                   6738:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6739:                GetProcAddress(module, funcName);
                   6740: 
                   6741:        if (NULL != fnIsWow64Process)
                   6742:        {
                   6743:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6744:                        &bIsWow64))
                   6745:                        //throw std::exception("Unknown error");
                   6746:                        printf("Unknown error\n");
                   6747:        }
                   6748:        return bIsWow64 != FALSE;
                   6749: }
                   6750: #endif
1.177     brouard  6751: 
1.191     brouard  6752: void syscompilerinfo(int logged)
1.167     brouard  6753:  {
                   6754:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6755:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6756:    /* /GS /W3 /Gy
                   6757:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6758:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6759:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6760:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6761:    */ 
                   6762:    /* 64 bits */
1.185     brouard  6763:    /*
                   6764:      /GS /W3 /Gy
                   6765:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6766:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6767:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6768:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6769:    /* Optimization are useless and O3 is slower than O2 */
                   6770:    /*
                   6771:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6772:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6773:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6774:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6775:    */
1.186     brouard  6776:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6777:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6778:       /PDB:"visual studio
                   6779:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6780:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6781:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6782:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6783:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6784:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6785:       uiAccess='false'"
                   6786:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6787:       /NOLOGO /TLBID:1
                   6788:    */
1.177     brouard  6789: #if defined __INTEL_COMPILER
1.178     brouard  6790: #if defined(__GNUC__)
                   6791:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6792: #endif
1.177     brouard  6793: #elif defined(__GNUC__) 
1.179     brouard  6794: #ifndef  __APPLE__
1.174     brouard  6795: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6796: #endif
1.177     brouard  6797:    struct utsname sysInfo;
1.178     brouard  6798:    int cross = CROSS;
                   6799:    if (cross){
                   6800:           printf("Cross-");
1.191     brouard  6801:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6802:    }
1.174     brouard  6803: #endif
                   6804: 
1.171     brouard  6805: #include <stdint.h>
1.178     brouard  6806: 
1.191     brouard  6807:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6808: #if defined(__clang__)
1.191     brouard  6809:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6810: #endif
                   6811: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6812:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6813: #endif
                   6814: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6815:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6816: #endif
                   6817: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6818:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6819: #endif
                   6820: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6821:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6822: #endif
                   6823: #if defined(_MSC_VER)
1.191     brouard  6824:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6825: #endif
                   6826: #if defined(__PGI)
1.191     brouard  6827:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6828: #endif
                   6829: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6830:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6831: #endif
1.191     brouard  6832:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6833:    
1.167     brouard  6834: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6835: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6836:     // Windows (x64 and x86)
1.191     brouard  6837:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6838: #elif __unix__ // all unices, not all compilers
                   6839:     // Unix
1.191     brouard  6840:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6841: #elif __linux__
                   6842:     // linux
1.191     brouard  6843:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6844: #elif __APPLE__
1.174     brouard  6845:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6846:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6847: #endif
                   6848: 
                   6849: /*  __MINGW32__          */
                   6850: /*  __CYGWIN__  */
                   6851: /* __MINGW64__  */
                   6852: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6853: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6854: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6855: /* _WIN64  // Defined for applications for Win64. */
                   6856: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6857: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6858: 
1.167     brouard  6859: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6860:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6861: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6862:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6863: #else
1.191     brouard  6864:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6865: #endif
                   6866: 
1.169     brouard  6867: #if defined(__GNUC__)
                   6868: # if defined(__GNUC_PATCHLEVEL__)
                   6869: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6870:                             + __GNUC_MINOR__ * 100 \
                   6871:                             + __GNUC_PATCHLEVEL__)
                   6872: # else
                   6873: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6874:                             + __GNUC_MINOR__ * 100)
                   6875: # endif
1.174     brouard  6876:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6877:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6878: 
                   6879:    if (uname(&sysInfo) != -1) {
                   6880:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6881:         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  6882:    }
                   6883:    else
                   6884:       perror("uname() error");
1.179     brouard  6885:    //#ifndef __INTEL_COMPILER 
                   6886: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6887:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6888:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6889: #endif
1.169     brouard  6890: #endif
1.172     brouard  6891: 
                   6892:    //   void main()
                   6893:    //   {
1.169     brouard  6894: #if defined(_MSC_VER)
1.174     brouard  6895:    if (IsWow64()){
1.191     brouard  6896:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6897:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6898:    }
                   6899:    else{
1.191     brouard  6900:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6901:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6902:    }
1.172     brouard  6903:    //     printf("\nPress Enter to continue...");
                   6904:    //     getchar();
                   6905:    //   }
                   6906: 
1.169     brouard  6907: #endif
                   6908:    
1.167     brouard  6909: 
                   6910:  }
1.136     brouard  6911: 
1.209     brouard  6912:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6913:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6914:   int i, j, k, i1 ;
1.202     brouard  6915:   /* double ftolpl = 1.e-10; */
1.180     brouard  6916:   double age, agebase, agelim;
1.203     brouard  6917:   double tot;
1.180     brouard  6918: 
1.202     brouard  6919:   strcpy(filerespl,"PL_");
                   6920:   strcat(filerespl,fileresu);
                   6921:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6922:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6923:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6924:   }
                   6925:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6926:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6927:   pstamp(ficrespl);
1.203     brouard  6928:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6929:   fprintf(ficrespl,"#Age ");
                   6930:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6931:   fprintf(ficrespl,"\n");
1.180     brouard  6932:   
                   6933:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6934: 
                   6935:     agebase=ageminpar;
                   6936:     agelim=agemaxpar;
                   6937: 
                   6938:     i1=pow(2,cptcoveff);
                   6939:     if (cptcovn < 1){i1=1;}
                   6940: 
                   6941:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6942:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6943:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6944:        k=k+1;
                   6945:        /* to clean */
1.198     brouard  6946:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6947:        fprintf(ficrespl,"#******");
                   6948:        printf("#******");
                   6949:        fprintf(ficlog,"#******");
1.180     brouard  6950:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6951:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6952:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6953:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6954:        }
                   6955:        fprintf(ficrespl,"******\n");
                   6956:        printf("******\n");
                   6957:        fprintf(ficlog,"******\n");
                   6958: 
                   6959:        fprintf(ficrespl,"#Age ");
                   6960:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6961:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6962:        }
1.203     brouard  6963:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6964:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6965:        
                   6966:        for (age=agebase; age<=agelim; age++){
                   6967:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  6968:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  6969:          fprintf(ficrespl,"%.0f ",age );
                   6970:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6971:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  6972:          tot=0.;
                   6973:          for(i=1; i<=nlstate;i++){
                   6974:            tot +=  prlim[i][i];
1.180     brouard  6975:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  6976:          }
1.209     brouard  6977:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  6978:        } /* Age */
                   6979:        /* was end of cptcod */
                   6980:     } /* cptcov */
1.184     brouard  6981:        return 0;
1.180     brouard  6982: }
                   6983: 
                   6984: int hPijx(double *p, int bage, int fage){
                   6985:     /*------------- h Pij x at various ages ------------*/
                   6986: 
                   6987:   int stepsize;
                   6988:   int agelim;
                   6989:   int hstepm;
                   6990:   int nhstepm;
                   6991:   int h, i, i1, j, k;
                   6992: 
                   6993:   double agedeb;
                   6994:   double ***p3mat;
                   6995: 
1.201     brouard  6996:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6997:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6998:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6999:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7000:     }
                   7001:     printf("Computing pij: result on file '%s' \n", filerespij);
                   7002:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   7003:   
                   7004:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7005:     /*if (stepm<=24) stepsize=2;*/
                   7006: 
                   7007:     agelim=AGESUP;
                   7008:     hstepm=stepsize*YEARM; /* Every year of age */
                   7009:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   7010: 
                   7011:     /* hstepm=1;   aff par mois*/
                   7012:     pstamp(ficrespij);
                   7013:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   7014:     i1= pow(2,cptcoveff);
1.183     brouard  7015:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   7016:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   7017:    /*          k=k+1;  */
                   7018:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7019:       fprintf(ficrespij,"\n#****** ");
                   7020:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  7021:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  7022:       fprintf(ficrespij,"******\n");
                   7023:       
                   7024:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   7025:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7026:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7027:        
                   7028:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  7029:        
1.183     brouard  7030:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7031:        oldm=oldms;savm=savms;
                   7032:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7033:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   7034:        for(i=1; i<=nlstate;i++)
                   7035:          for(j=1; j<=nlstate+ndeath;j++)
                   7036:            fprintf(ficrespij," %1d-%1d",i,j);
                   7037:        fprintf(ficrespij,"\n");
                   7038:        for (h=0; h<=nhstepm; h++){
                   7039:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   7040:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  7041:          for(i=1; i<=nlstate;i++)
                   7042:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  7043:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  7044:          fprintf(ficrespij,"\n");
                   7045:        }
1.183     brouard  7046:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7047:        fprintf(ficrespij,"\n");
                   7048:       }
1.180     brouard  7049:       /*}*/
                   7050:     }
1.184     brouard  7051:        return 0;
1.180     brouard  7052: }
                   7053: 
                   7054: 
1.136     brouard  7055: /***********************************************/
                   7056: /**************** Main Program *****************/
                   7057: /***********************************************/
                   7058: 
                   7059: int main(int argc, char *argv[])
                   7060: {
                   7061: #ifdef GSL
                   7062:   const gsl_multimin_fminimizer_type *T;
                   7063:   size_t iteri = 0, it;
                   7064:   int rval = GSL_CONTINUE;
                   7065:   int status = GSL_SUCCESS;
                   7066:   double ssval;
                   7067: #endif
                   7068:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  7069:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  7070:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  7071:   int jj, ll, li, lj, lk;
1.136     brouard  7072:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  7073:   int num_filled;
1.136     brouard  7074:   int itimes;
                   7075:   int NDIM=2;
                   7076:   int vpopbased=0;
                   7077: 
1.164     brouard  7078:   char ca[32], cb[32];
1.136     brouard  7079:   /*  FILE *fichtm; *//* Html File */
                   7080:   /* FILE *ficgp;*/ /*Gnuplot File */
                   7081:   struct stat info;
1.191     brouard  7082:   double agedeb=0.;
1.194     brouard  7083: 
                   7084:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  7085: 
1.165     brouard  7086:   double fret;
1.191     brouard  7087:   double dum=0.; /* Dummy variable */
1.136     brouard  7088:   double ***p3mat;
                   7089:   double ***mobaverage;
1.164     brouard  7090: 
                   7091:   char line[MAXLINE];
1.197     brouard  7092:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   7093: 
                   7094:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  7095:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  7096:   char *tok, *val; /* pathtot */
1.136     brouard  7097:   int firstobs=1, lastobs=10;
1.195     brouard  7098:   int c,  h , cpt, c2;
1.191     brouard  7099:   int jl=0;
                   7100:   int i1, j1, jk, stepsize=0;
1.194     brouard  7101:   int count=0;
                   7102: 
1.164     brouard  7103:   int *tab; 
1.136     brouard  7104:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   7105:   int mobilav=0,popforecast=0;
1.191     brouard  7106:   int hstepm=0, nhstepm=0;
1.136     brouard  7107:   int agemortsup;
                   7108:   float  sumlpop=0.;
                   7109:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   7110:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   7111: 
1.191     brouard  7112:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  7113:   double ftolpl=FTOL;
                   7114:   double **prlim;
                   7115:   double ***param; /* Matrix of parameters */
                   7116:   double  *p;
                   7117:   double **matcov; /* Matrix of covariance */
1.203     brouard  7118:   double **hess; /* Hessian matrix */
1.136     brouard  7119:   double ***delti3; /* Scale */
                   7120:   double *delti; /* Scale */
                   7121:   double ***eij, ***vareij;
                   7122:   double **varpl; /* Variances of prevalence limits by age */
                   7123:   double *epj, vepp;
1.164     brouard  7124: 
1.136     brouard  7125:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   7126:   double **ximort;
1.145     brouard  7127:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  7128:   int *dcwave;
                   7129: 
1.164     brouard  7130:   char z[1]="c";
1.136     brouard  7131: 
                   7132:   /*char  *strt;*/
                   7133:   char strtend[80];
1.126     brouard  7134: 
1.164     brouard  7135: 
1.126     brouard  7136: /*   setlocale (LC_ALL, ""); */
                   7137: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   7138: /*   textdomain (PACKAGE); */
                   7139: /*   setlocale (LC_CTYPE, ""); */
                   7140: /*   setlocale (LC_MESSAGES, ""); */
                   7141: 
                   7142:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  7143:   rstart_time = time(NULL);  
                   7144:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   7145:   start_time = *localtime(&rstart_time);
1.126     brouard  7146:   curr_time=start_time;
1.157     brouard  7147:   /*tml = *localtime(&start_time.tm_sec);*/
                   7148:   /* strcpy(strstart,asctime(&tml)); */
                   7149:   strcpy(strstart,asctime(&start_time));
1.126     brouard  7150: 
                   7151: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  7152: /*  tp.tm_sec = tp.tm_sec +86400; */
                   7153: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  7154: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   7155: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   7156: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  7157: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  7158: /*   strt=asctime(&tmg); */
                   7159: /*   printf("Time(after) =%s",strstart);  */
                   7160: /*  (void) time (&time_value);
                   7161: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   7162: *  tm = *localtime(&time_value);
                   7163: *  strstart=asctime(&tm);
                   7164: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   7165: */
                   7166: 
                   7167:   nberr=0; /* Number of errors and warnings */
                   7168:   nbwarn=0;
1.184     brouard  7169: #ifdef WIN32
                   7170:   _getcwd(pathcd, size);
                   7171: #else
1.126     brouard  7172:   getcwd(pathcd, size);
1.184     brouard  7173: #endif
1.191     brouard  7174:   syscompilerinfo(0);
1.196     brouard  7175:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  7176:   if(argc <=1){
                   7177:     printf("\nEnter the parameter file name: ");
1.205     brouard  7178:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   7179:       printf("ERROR Empty parameter file name\n");
                   7180:       goto end;
                   7181:     }
1.126     brouard  7182:     i=strlen(pathr);
                   7183:     if(pathr[i-1]=='\n')
                   7184:       pathr[i-1]='\0';
1.156     brouard  7185:     i=strlen(pathr);
1.205     brouard  7186:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  7187:       pathr[i-1]='\0';
1.205     brouard  7188:     }
                   7189:     i=strlen(pathr);
                   7190:     if( i==0 ){
                   7191:       printf("ERROR Empty parameter file name\n");
                   7192:       goto end;
                   7193:     }
                   7194:     for (tok = pathr; tok != NULL; ){
1.126     brouard  7195:       printf("Pathr |%s|\n",pathr);
                   7196:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   7197:       printf("val= |%s| pathr=%s\n",val,pathr);
                   7198:       strcpy (pathtot, val);
                   7199:       if(pathr[0] == '\0') break; /* Dirty */
                   7200:     }
                   7201:   }
                   7202:   else{
                   7203:     strcpy(pathtot,argv[1]);
                   7204:   }
                   7205:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   7206:   /*cygwin_split_path(pathtot,path,optionfile);
                   7207:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   7208:   /* cutv(path,optionfile,pathtot,'\\');*/
                   7209: 
                   7210:   /* Split argv[0], imach program to get pathimach */
                   7211:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   7212:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7213:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7214:  /*   strcpy(pathimach,argv[0]); */
                   7215:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   7216:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   7217:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  7218: #ifdef WIN32
                   7219:   _chdir(path); /* Can be a relative path */
                   7220:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   7221: #else
1.126     brouard  7222:   chdir(path); /* Can be a relative path */
1.184     brouard  7223:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   7224: #endif
                   7225:   printf("Current directory %s!\n",pathcd);
1.126     brouard  7226:   strcpy(command,"mkdir ");
                   7227:   strcat(command,optionfilefiname);
                   7228:   if((outcmd=system(command)) != 0){
1.169     brouard  7229:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  7230:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   7231:     /* fclose(ficlog); */
                   7232: /*     exit(1); */
                   7233:   }
                   7234: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   7235: /*     perror("mkdir"); */
                   7236: /*   } */
                   7237: 
                   7238:   /*-------- arguments in the command line --------*/
                   7239: 
1.186     brouard  7240:   /* Main Log file */
1.126     brouard  7241:   strcat(filelog, optionfilefiname);
                   7242:   strcat(filelog,".log");    /* */
                   7243:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   7244:     printf("Problem with logfile %s\n",filelog);
                   7245:     goto end;
                   7246:   }
                   7247:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  7248:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  7249:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   7250:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   7251:  path=%s \n\
                   7252:  optionfile=%s\n\
                   7253:  optionfilext=%s\n\
1.156     brouard  7254:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  7255: 
1.197     brouard  7256:   syscompilerinfo(1);
1.167     brouard  7257: 
1.126     brouard  7258:   printf("Local time (at start):%s",strstart);
                   7259:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   7260:   fflush(ficlog);
                   7261: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  7262: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  7263: 
                   7264:   /* */
                   7265:   strcpy(fileres,"r");
                   7266:   strcat(fileres, optionfilefiname);
1.201     brouard  7267:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  7268:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  7269:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  7270: 
1.186     brouard  7271:   /* Main ---------arguments file --------*/
1.126     brouard  7272: 
                   7273:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  7274:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   7275:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  7276:     fflush(ficlog);
1.149     brouard  7277:     /* goto end; */
                   7278:     exit(70); 
1.126     brouard  7279:   }
                   7280: 
                   7281: 
                   7282: 
                   7283:   strcpy(filereso,"o");
1.201     brouard  7284:   strcat(filereso,fileresu);
1.126     brouard  7285:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   7286:     printf("Problem with Output resultfile: %s\n", filereso);
                   7287:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   7288:     fflush(ficlog);
                   7289:     goto end;
                   7290:   }
                   7291: 
                   7292:   /* Reads comments: lines beginning with '#' */
                   7293:   numlinepar=0;
1.197     brouard  7294: 
                   7295:     /* First parameter line */
                   7296:   while(fgets(line, MAXLINE, ficpar)) {
                   7297:     /* If line starts with a # it is a comment */
                   7298:     if (line[0] == '#') {
                   7299:       numlinepar++;
                   7300:       fputs(line,stdout);
                   7301:       fputs(line,ficparo);
                   7302:       fputs(line,ficlog);
                   7303:       continue;
                   7304:     }else
                   7305:       break;
                   7306:   }
                   7307:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   7308:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   7309:     if (num_filled != 5) {
                   7310:       printf("Should be 5 parameters\n");
                   7311:     }
1.126     brouard  7312:     numlinepar++;
1.197     brouard  7313:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   7314:   }
                   7315:   /* Second parameter line */
                   7316:   while(fgets(line, MAXLINE, ficpar)) {
                   7317:     /* If line starts with a # it is a comment */
                   7318:     if (line[0] == '#') {
                   7319:       numlinepar++;
                   7320:       fputs(line,stdout);
                   7321:       fputs(line,ficparo);
                   7322:       fputs(line,ficlog);
                   7323:       continue;
                   7324:     }else
                   7325:       break;
                   7326:   }
                   7327:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   7328:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   7329:     if (num_filled != 8) {
1.209     brouard  7330:       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");
                   7331:       printf("but line=%s\n",line);
1.197     brouard  7332:     }
                   7333:     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  7334:   }
1.203     brouard  7335:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  7336:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  7337:   /* Third parameter line */
                   7338:   while(fgets(line, MAXLINE, ficpar)) {
                   7339:     /* If line starts with a # it is a comment */
                   7340:     if (line[0] == '#') {
                   7341:       numlinepar++;
                   7342:       fputs(line,stdout);
                   7343:       fputs(line,ficparo);
                   7344:       fputs(line,ficlog);
                   7345:       continue;
                   7346:     }else
                   7347:       break;
                   7348:   }
1.201     brouard  7349:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7350:     if (num_filled == 0)
                   7351:             model[0]='\0';
                   7352:     else if (num_filled != 1){
1.197     brouard  7353:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7354:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7355:       model[0]='\0';
                   7356:       goto end;
                   7357:     }
                   7358:     else{
                   7359:       if (model[0]=='+'){
                   7360:        for(i=1; i<=strlen(model);i++)
                   7361:          modeltemp[i-1]=model[i];
1.201     brouard  7362:        strcpy(model,modeltemp); 
1.197     brouard  7363:       }
                   7364:     }
1.199     brouard  7365:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7366:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7367:   }
                   7368:   /* 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); */
                   7369:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7370:   /* 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  7371:   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);
                   7372:   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  7373:   fflush(ficlog);
1.190     brouard  7374:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7375:   if(model[0]=='#'){
1.187     brouard  7376:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7377:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7378:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7379:     if(mle != -1){
                   7380:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7381:       exit(1);
                   7382:     }
                   7383:   }
1.126     brouard  7384:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7385:     ungetc(c,ficpar);
                   7386:     fgets(line, MAXLINE, ficpar);
                   7387:     numlinepar++;
1.195     brouard  7388:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7389:       z[0]=line[1];
                   7390:     }
                   7391:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7392:     fputs(line, stdout);
                   7393:     //puts(line);
1.126     brouard  7394:     fputs(line,ficparo);
                   7395:     fputs(line,ficlog);
                   7396:   }
                   7397:   ungetc(c,ficpar);
                   7398: 
                   7399:    
1.145     brouard  7400:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7401:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7402:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7403:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7404:   */
                   7405:   if (strlen(model)>1) 
1.187     brouard  7406:     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  7407:   else
1.187     brouard  7408:     ncovmodel=2; /* Constant and age */
1.133     brouard  7409:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7410:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7411:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7412:     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);
                   7413:     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);
                   7414:     fflush(stdout);
                   7415:     fclose (ficlog);
                   7416:     goto end;
                   7417:   }
1.126     brouard  7418:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7419:   delti=delti3[1][1];
                   7420:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7421:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7422:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7423:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7424:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7425:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7426:     fclose (ficparo);
                   7427:     fclose (ficlog);
                   7428:     goto end;
                   7429:     exit(0);
                   7430:   }
1.186     brouard  7431:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7432:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7433:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7434:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7435:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7436:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7437:     hess=matrix(1,npar,1,npar);
1.126     brouard  7438:   }
                   7439:   else{
1.145     brouard  7440:     /* Read guessed parameters */
1.126     brouard  7441:     /* Reads comments: lines beginning with '#' */
                   7442:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7443:       ungetc(c,ficpar);
                   7444:       fgets(line, MAXLINE, ficpar);
                   7445:       numlinepar++;
1.141     brouard  7446:       fputs(line,stdout);
1.126     brouard  7447:       fputs(line,ficparo);
                   7448:       fputs(line,ficlog);
                   7449:     }
                   7450:     ungetc(c,ficpar);
                   7451:     
                   7452:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7453:     for(i=1; i <=nlstate; i++){
                   7454:       j=0;
                   7455:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7456:        if(jj==i) continue;
                   7457:        j++;
                   7458:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7459:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7460:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7461: It might be a problem of design; if ncovcol and the model are correct\n \
                   7462: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7463:          exit(1);
                   7464:        }
                   7465:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7466:        if(mle==1)
1.193     brouard  7467:          printf("%1d%1d",i,jj);
                   7468:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7469:        for(k=1; k<=ncovmodel;k++){
                   7470:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7471:          if(mle==1){
                   7472:            printf(" %lf",param[i][j][k]);
                   7473:            fprintf(ficlog," %lf",param[i][j][k]);
                   7474:          }
                   7475:          else
                   7476:            fprintf(ficlog," %lf",param[i][j][k]);
                   7477:          fprintf(ficparo," %lf",param[i][j][k]);
                   7478:        }
                   7479:        fscanf(ficpar,"\n");
                   7480:        numlinepar++;
                   7481:        if(mle==1)
                   7482:          printf("\n");
                   7483:        fprintf(ficlog,"\n");
                   7484:        fprintf(ficparo,"\n");
                   7485:       }
                   7486:     }  
                   7487:     fflush(ficlog);
                   7488: 
1.145     brouard  7489:     /* Reads scales values */
1.126     brouard  7490:     p=param[1][1];
                   7491:     
                   7492:     /* Reads comments: lines beginning with '#' */
                   7493:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7494:       ungetc(c,ficpar);
                   7495:       fgets(line, MAXLINE, ficpar);
                   7496:       numlinepar++;
1.141     brouard  7497:       fputs(line,stdout);
1.126     brouard  7498:       fputs(line,ficparo);
                   7499:       fputs(line,ficlog);
                   7500:     }
                   7501:     ungetc(c,ficpar);
                   7502: 
                   7503:     for(i=1; i <=nlstate; i++){
                   7504:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7505:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7506:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7507:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7508:          exit(1);
                   7509:        }
                   7510:        printf("%1d%1d",i,j);
                   7511:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7512:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7513:        for(k=1; k<=ncovmodel;k++){
                   7514:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7515:          printf(" %le",delti3[i][j][k]);
                   7516:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7517:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7518:        }
                   7519:        fscanf(ficpar,"\n");
                   7520:        numlinepar++;
                   7521:        printf("\n");
                   7522:        fprintf(ficparo,"\n");
                   7523:        fprintf(ficlog,"\n");
                   7524:       }
                   7525:     }
                   7526:     fflush(ficlog);
                   7527: 
1.145     brouard  7528:     /* Reads covariance matrix */
1.126     brouard  7529:     delti=delti3[1][1];
                   7530: 
                   7531: 
                   7532:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7533:   
                   7534:     /* Reads comments: lines beginning with '#' */
                   7535:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7536:       ungetc(c,ficpar);
                   7537:       fgets(line, MAXLINE, ficpar);
                   7538:       numlinepar++;
1.141     brouard  7539:       fputs(line,stdout);
1.126     brouard  7540:       fputs(line,ficparo);
                   7541:       fputs(line,ficlog);
                   7542:     }
                   7543:     ungetc(c,ficpar);
                   7544:   
                   7545:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7546:     hess=matrix(1,npar,1,npar);
1.131     brouard  7547:     for(i=1; i <=npar; i++)
                   7548:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7549:       
1.194     brouard  7550:     /* Scans npar lines */
1.126     brouard  7551:     for(i=1; i <=npar; i++){
1.194     brouard  7552:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7553:       if(count != 3){
                   7554:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7555: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7556: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7557:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7558: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7559: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7560:        exit(1);
                   7561:       }else
1.126     brouard  7562:       if(mle==1)
1.194     brouard  7563:        printf("%1d%1d%1d",i1,j1,jk);
                   7564:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7565:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7566:       for(j=1; j <=i; j++){
                   7567:        fscanf(ficpar," %le",&matcov[i][j]);
                   7568:        if(mle==1){
                   7569:          printf(" %.5le",matcov[i][j]);
                   7570:        }
                   7571:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7572:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7573:       }
                   7574:       fscanf(ficpar,"\n");
                   7575:       numlinepar++;
                   7576:       if(mle==1)
                   7577:        printf("\n");
                   7578:       fprintf(ficlog,"\n");
                   7579:       fprintf(ficparo,"\n");
                   7580:     }
1.194     brouard  7581:     /* End of read covariance matrix npar lines */
1.126     brouard  7582:     for(i=1; i <=npar; i++)
                   7583:       for(j=i+1;j<=npar;j++)
                   7584:        matcov[i][j]=matcov[j][i];
                   7585:     
                   7586:     if(mle==1)
                   7587:       printf("\n");
                   7588:     fprintf(ficlog,"\n");
                   7589:     
                   7590:     fflush(ficlog);
                   7591:     
                   7592:     /*-------- Rewriting parameter file ----------*/
                   7593:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7594:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7595:     strcat(rfileres,".");    /* */
                   7596:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7597:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7598:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7599:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7600:     }
                   7601:     fprintf(ficres,"#%s\n",version);
                   7602:   }    /* End of mle != -3 */
                   7603: 
1.186     brouard  7604:   /*  Main data
                   7605:    */
1.126     brouard  7606:   n= lastobs;
                   7607:   num=lvector(1,n);
                   7608:   moisnais=vector(1,n);
                   7609:   annais=vector(1,n);
                   7610:   moisdc=vector(1,n);
                   7611:   andc=vector(1,n);
                   7612:   agedc=vector(1,n);
                   7613:   cod=ivector(1,n);
                   7614:   weight=vector(1,n);
                   7615:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7616:   mint=matrix(1,maxwav,1,n);
                   7617:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7618:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7619:   tab=ivector(1,NCOVMAX);
1.144     brouard  7620:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7621:   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  7622: 
1.136     brouard  7623:   /* Reads data from file datafile */
                   7624:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7625:     goto end;
                   7626: 
                   7627:   /* Calculation of the number of parameters from char model */
1.137     brouard  7628:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7629:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7630:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7631:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7632:        k=1 Tvar[1]=2 (from V2)
                   7633:     */
                   7634:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7635:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7636:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7637:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7638:   */
                   7639:   /* For model-covariate k tells which data-covariate to use but
                   7640:     because this model-covariate is a construction we invent a new column
                   7641:     ncovcol + k1
                   7642:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7643:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7644:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7645:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7646:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7647:   */
1.145     brouard  7648:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7649:   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  7650:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7651:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7652:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7653:                         4 covariates (3 plus signs)
                   7654:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7655:                      */  
1.136     brouard  7656: 
1.186     brouard  7657: /* Main decodemodel */
                   7658: 
1.187     brouard  7659: 
1.136     brouard  7660:   if(decodemodel(model, lastobs) == 1)
                   7661:     goto end;
                   7662: 
1.137     brouard  7663:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7664:     nbwarn++;
                   7665:     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); 
                   7666:     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); 
                   7667:   }
1.136     brouard  7668:     /*  if(mle==1){*/
1.137     brouard  7669:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7670:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7671:   }
                   7672: 
                   7673:     /*-calculation of age at interview from date of interview and age at death -*/
                   7674:   agev=matrix(1,maxwav,1,imx);
                   7675: 
                   7676:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7677:     goto end;
                   7678: 
1.126     brouard  7679: 
1.136     brouard  7680:   agegomp=(int)agemin;
                   7681:   free_vector(moisnais,1,n);
                   7682:   free_vector(annais,1,n);
1.126     brouard  7683:   /* free_matrix(mint,1,maxwav,1,n);
                   7684:      free_matrix(anint,1,maxwav,1,n);*/
                   7685:   free_vector(moisdc,1,n);
                   7686:   free_vector(andc,1,n);
1.145     brouard  7687:   /* */
                   7688:   
1.126     brouard  7689:   wav=ivector(1,imx);
1.214   ! brouard  7690:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
        !          7691:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
        !          7692:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
        !          7693:   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.*/
        !          7694:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
        !          7695:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  7696:    
                   7697:   /* Concatenates waves */
1.214   ! brouard  7698:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
        !          7699:      Death is a valid wave (if date is known).
        !          7700:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
        !          7701:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          7702:      and mw[mi+1][i]. dh depends on stepm.
        !          7703:   */
        !          7704: 
1.126     brouard  7705:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7706:   /* */
                   7707:  
1.126     brouard  7708:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7709: 
                   7710:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7711:   ncodemax[1]=1;
1.145     brouard  7712:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7713:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7714:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211     brouard  7715:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  7716:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  7717:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  7718: 
1.200     brouard  7719:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7720:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7721:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  7722:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   7723:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   7724:    * (currently 0 or 1) in the data.
                   7725:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   7726:    * corresponding modality (h,j).
                   7727:    */
                   7728: 
1.145     brouard  7729:   h=0;
                   7730: 
                   7731: 
                   7732:   /*if (cptcovn > 0) */
1.126     brouard  7733:       
1.145     brouard  7734:  
1.126     brouard  7735:   m=pow(2,cptcoveff);
                   7736:  
1.144     brouard  7737:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  7738:           * For k=4 covariates, h goes from 1 to m=2**k
                   7739:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   7740:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  7741:           *     h\k   1     2     3     4
1.143     brouard  7742:           *______________________________  
                   7743:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7744:           *     2     2     1     1     1
                   7745:           *     3 i=2 1     2     1     1
                   7746:           *     4     2     2     1     1
                   7747:           *     5 i=3 1 i=2 1     2     1
                   7748:           *     6     2     1     2     1
                   7749:           *     7 i=4 1     2     2     1
                   7750:           *     8     2     2     2     1
1.197     brouard  7751:           *     9 i=5 1 i=3 1 i=2 1     2
                   7752:           *    10     2     1     1     2
                   7753:           *    11 i=6 1     2     1     2
                   7754:           *    12     2     2     1     2
                   7755:           *    13 i=7 1 i=4 1     2     2    
                   7756:           *    14     2     1     2     2
                   7757:           *    15 i=8 1     2     2     2
                   7758:           *    16     2     2     2     2
1.143     brouard  7759:           */
1.212     brouard  7760:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  7761:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   7762:      * and the value of each covariate?
                   7763:      * V1=1, V2=1, V3=2, V4=1 ?
                   7764:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   7765:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   7766:      * In order to get the real value in the data, we use nbcode
                   7767:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   7768:      * We are keeping this crazy system in order to be able (in the future?) 
                   7769:      * to have more than 2 values (0 or 1) for a covariate.
                   7770:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   7771:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   7772:      *              bbbbbbbb
                   7773:      *              76543210     
                   7774:      *   h-1        00000101 (6-1=5)
                   7775:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
                   7776:      *           &
                   7777:      *     1        00000001 (1)
                   7778:      *              00000001        = 1 & ((h-1) >> (k-1))
                   7779:      *          +1= 00000010 =2 
                   7780:      *
                   7781:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   7782:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   7783:      *    >>k'            11
                   7784:      *          &   00000001
                   7785:      *            = 00000001
                   7786:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   7787:      * Reverse h=6 and m=16?
                   7788:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   7789:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   7790:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   7791:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   7792:      * V3=decodtabm(14,3,2**4)=2
                   7793:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   7794:      *(h-1) >> (j-1)    0011 =13 >> 2
                   7795:      *          &1 000000001
                   7796:      *           = 000000001
                   7797:      *         +1= 000000010 =2
                   7798:      *                  2211
                   7799:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   7800:      *                  V3=2
                   7801:      */
                   7802: 
1.202     brouard  7803:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7804:   /*   /\* printf("h=%2d ", h); *\/ */
                   7805:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7806:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7807:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7808:   /*    /\* } *\/ */
                   7809:   /*    /\* printf("\n"); *\/ */
                   7810:   /* } */
1.197     brouard  7811:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7812:   /*   for(i=1; i <=pow(2,cptcoveff-k);i++){ /\* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 *\/  */
                   7813:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7814:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7815:   /*     h++; */
                   7816:   /*     if (h>m)  */
                   7817:   /*       h=1; */
                   7818:   /*     codtab[h][k]=j; */
                   7819:   /*     /\* codtab[12][3]=1; *\/ */
                   7820:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7821:   /*     /\* printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]); *\/ */
                   7822:   /*   }  */
                   7823:   /*     } */
                   7824:   /*   } */
                   7825:   /* }  */
1.126     brouard  7826:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7827:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7828:   /* for(i=1; i <=m ;i++){  */
                   7829:   /*    for(k=1; k <=cptcovn; k++){ */
                   7830:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7831:   /*    } */
                   7832:   /*    printf("\n"); */
                   7833:   /* } */
                   7834:   /*   scanf("%d",i);*/
1.145     brouard  7835: 
                   7836:  free_ivector(Ndum,-1,NCOVMAX);
                   7837: 
                   7838: 
1.126     brouard  7839:     
1.186     brouard  7840:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7841:   strcpy(optionfilegnuplot,optionfilefiname);
                   7842:   if(mle==-3)
1.201     brouard  7843:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7844:   strcat(optionfilegnuplot,".gp");
                   7845: 
                   7846:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7847:     printf("Problem with file %s",optionfilegnuplot);
                   7848:   }
                   7849:   else{
1.204     brouard  7850:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7851:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7852:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7853:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7854:   }
                   7855:   /*  fclose(ficgp);*/
1.186     brouard  7856: 
                   7857: 
                   7858:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7859: 
                   7860:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7861:   if(mle==-3)
1.201     brouard  7862:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7863:   strcat(optionfilehtm,".htm");
                   7864:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7865:     printf("Problem with %s \n",optionfilehtm);
                   7866:     exit(0);
1.126     brouard  7867:   }
                   7868: 
                   7869:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7870:   strcat(optionfilehtmcov,"-cov.htm");
                   7871:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7872:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7873:   }
                   7874:   else{
                   7875:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7876: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7877: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7878:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7879:   }
                   7880: 
1.213     brouard  7881:   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  7882: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7883: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7884: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7885: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7886: \n\
                   7887: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7888:  <ul><li><h4>Parameter files</h4>\n\
                   7889:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7890:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7891:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7892:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7893:  - Date and time at start: %s</ul>\n",\
                   7894:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7895:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7896:          fileres,fileres,\
                   7897:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7898:   fflush(fichtm);
                   7899: 
                   7900:   strcpy(pathr,path);
                   7901:   strcat(pathr,optionfilefiname);
1.184     brouard  7902: #ifdef WIN32
                   7903:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7904: #else
1.126     brouard  7905:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7906: #endif
                   7907:          
1.126     brouard  7908:   
                   7909:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7910:      and prints on file fileres'p'. */
1.214   ! brouard  7911:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
        !          7912:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  7913: 
                   7914:   fprintf(fichtm,"\n");
                   7915:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7916: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7917: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7918:          imx,agemin,agemax,jmin,jmax,jmean);
                   7919:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7920:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7921:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7922:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7923:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7924:     
                   7925:    
                   7926:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7927:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7928:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7929: 
                   7930:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7931:   /* For mortality only */
1.126     brouard  7932:   if (mle==-3){
1.136     brouard  7933:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7934:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7935:     cens=ivector(1,n);
                   7936:     ageexmed=vector(1,n);
                   7937:     agecens=vector(1,n);
                   7938:     dcwave=ivector(1,n);
                   7939:  
                   7940:     for (i=1; i<=imx; i++){
                   7941:       dcwave[i]=-1;
                   7942:       for (m=firstpass; m<=lastpass; m++)
                   7943:        if (s[m][i]>nlstate) {
                   7944:          dcwave[i]=m;
                   7945:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7946:          break;
                   7947:        }
                   7948:     }
                   7949: 
                   7950:     for (i=1; i<=imx; i++) {
                   7951:       if (wav[i]>0){
                   7952:        ageexmed[i]=agev[mw[1][i]][i];
                   7953:        j=wav[i];
                   7954:        agecens[i]=1.; 
                   7955: 
                   7956:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7957:          agecens[i]=agev[mw[j][i]][i];
                   7958:          cens[i]= 1;
                   7959:        }else if (ageexmed[i]< 1) 
                   7960:          cens[i]= -1;
                   7961:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7962:          cens[i]=0 ;
                   7963:       }
                   7964:       else cens[i]=-1;
                   7965:     }
                   7966:     
                   7967:     for (i=1;i<=NDIM;i++) {
                   7968:       for (j=1;j<=NDIM;j++)
                   7969:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7970:     }
                   7971:     
1.145     brouard  7972:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7973:     /*printf("%lf %lf", p[1], p[2]);*/
                   7974:     
                   7975:     
1.136     brouard  7976: #ifdef GSL
                   7977:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7978: #else
1.126     brouard  7979:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7980: #endif
1.201     brouard  7981:     strcpy(filerespow,"POW-MORT_"); 
                   7982:     strcat(filerespow,fileresu);
1.126     brouard  7983:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7984:       printf("Problem with resultfile: %s\n", filerespow);
                   7985:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7986:     }
1.136     brouard  7987: #ifdef GSL
                   7988:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7989: #else
1.126     brouard  7990:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7991: #endif
1.126     brouard  7992:     /*  for (i=1;i<=nlstate;i++)
                   7993:        for(j=1;j<=nlstate+ndeath;j++)
                   7994:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7995:     */
                   7996:     fprintf(ficrespow,"\n");
1.136     brouard  7997: #ifdef GSL
                   7998:     /* gsl starts here */ 
                   7999:     T = gsl_multimin_fminimizer_nmsimplex;
                   8000:     gsl_multimin_fminimizer *sfm = NULL;
                   8001:     gsl_vector *ss, *x;
                   8002:     gsl_multimin_function minex_func;
                   8003: 
                   8004:     /* Initial vertex size vector */
                   8005:     ss = gsl_vector_alloc (NDIM);
                   8006:     
                   8007:     if (ss == NULL){
                   8008:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   8009:     }
                   8010:     /* Set all step sizes to 1 */
                   8011:     gsl_vector_set_all (ss, 0.001);
                   8012: 
                   8013:     /* Starting point */
1.126     brouard  8014:     
1.136     brouard  8015:     x = gsl_vector_alloc (NDIM);
                   8016:     
                   8017:     if (x == NULL){
                   8018:       gsl_vector_free(ss);
                   8019:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   8020:     }
                   8021:   
                   8022:     /* Initialize method and iterate */
                   8023:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  8024:     /*     gsl_vector_set(x, 0, 0.0268); */
                   8025:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  8026:     gsl_vector_set(x, 0, p[1]);
                   8027:     gsl_vector_set(x, 1, p[2]);
                   8028: 
                   8029:     minex_func.f = &gompertz_f;
                   8030:     minex_func.n = NDIM;
                   8031:     minex_func.params = (void *)&p; /* ??? */
                   8032:     
                   8033:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   8034:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   8035:     
                   8036:     printf("Iterations beginning .....\n\n");
                   8037:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   8038: 
                   8039:     iteri=0;
                   8040:     while (rval == GSL_CONTINUE){
                   8041:       iteri++;
                   8042:       status = gsl_multimin_fminimizer_iterate(sfm);
                   8043:       
                   8044:       if (status) printf("error: %s\n", gsl_strerror (status));
                   8045:       fflush(0);
                   8046:       
                   8047:       if (status) 
                   8048:         break;
                   8049:       
                   8050:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   8051:       ssval = gsl_multimin_fminimizer_size (sfm);
                   8052:       
                   8053:       if (rval == GSL_SUCCESS)
                   8054:         printf ("converged to a local maximum at\n");
                   8055:       
                   8056:       printf("%5d ", iteri);
                   8057:       for (it = 0; it < NDIM; it++){
                   8058:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   8059:       }
                   8060:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   8061:     }
                   8062:     
                   8063:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   8064:     
                   8065:     gsl_vector_free(x); /* initial values */
                   8066:     gsl_vector_free(ss); /* inital step size */
                   8067:     for (it=0; it<NDIM; it++){
                   8068:       p[it+1]=gsl_vector_get(sfm->x,it);
                   8069:       fprintf(ficrespow," %.12lf", p[it]);
                   8070:     }
                   8071:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   8072: #endif
                   8073: #ifdef POWELL
                   8074:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   8075: #endif  
1.126     brouard  8076:     fclose(ficrespow);
                   8077:     
1.203     brouard  8078:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  8079: 
                   8080:     for(i=1; i <=NDIM; i++)
                   8081:       for(j=i+1;j<=NDIM;j++)
                   8082:        matcov[i][j]=matcov[j][i];
                   8083:     
                   8084:     printf("\nCovariance matrix\n ");
1.203     brouard  8085:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  8086:     for(i=1; i <=NDIM; i++) {
                   8087:       for(j=1;j<=NDIM;j++){ 
                   8088:        printf("%f ",matcov[i][j]);
1.203     brouard  8089:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  8090:       }
1.203     brouard  8091:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  8092:     }
                   8093:     
                   8094:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  8095:     for (i=1;i<=NDIM;i++) {
1.126     brouard  8096:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  8097:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   8098:     }
1.126     brouard  8099:     lsurv=vector(1,AGESUP);
                   8100:     lpop=vector(1,AGESUP);
                   8101:     tpop=vector(1,AGESUP);
                   8102:     lsurv[agegomp]=100000;
                   8103:     
                   8104:     for (k=agegomp;k<=AGESUP;k++) {
                   8105:       agemortsup=k;
                   8106:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   8107:     }
                   8108:     
                   8109:     for (k=agegomp;k<agemortsup;k++)
                   8110:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   8111:     
                   8112:     for (k=agegomp;k<agemortsup;k++){
                   8113:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   8114:       sumlpop=sumlpop+lpop[k];
                   8115:     }
                   8116:     
                   8117:     tpop[agegomp]=sumlpop;
                   8118:     for (k=agegomp;k<(agemortsup-3);k++){
                   8119:       /*  tpop[k+1]=2;*/
                   8120:       tpop[k+1]=tpop[k]-lpop[k];
                   8121:     }
                   8122:     
                   8123:     
                   8124:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   8125:     for (k=agegomp;k<(agemortsup-2);k++) 
                   8126:       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]);
                   8127:     
                   8128:     
                   8129:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8130:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   8131:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8132: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8133: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8134:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8135: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8136: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8137:     }else
1.201     brouard  8138:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   8139:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  8140:                     stepm, weightopt,\
                   8141:                     model,imx,p,matcov,agemortsup);
                   8142:     
                   8143:     free_vector(lsurv,1,AGESUP);
                   8144:     free_vector(lpop,1,AGESUP);
                   8145:     free_vector(tpop,1,AGESUP);
1.136     brouard  8146: #ifdef GSL
                   8147:     free_ivector(cens,1,n);
                   8148:     free_vector(agecens,1,n);
                   8149:     free_ivector(dcwave,1,n);
                   8150:     free_matrix(ximort,1,NDIM,1,NDIM);
                   8151: #endif
1.186     brouard  8152:   } /* Endof if mle==-3 mortality only */
1.205     brouard  8153:   /* Standard  */
                   8154:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   8155:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8156:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  8157:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  8158:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8159:     for (k=1; k<=npar;k++)
                   8160:       printf(" %d %8.5f",k,p[k]);
                   8161:     printf("\n");
1.205     brouard  8162:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   8163:       /* mlikeli uses func not funcone */
                   8164:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   8165:     }
                   8166:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   8167:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8168:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   8169:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8170:     }
                   8171:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  8172:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8173:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8174:     for (k=1; k<=npar;k++)
                   8175:       printf(" %d %8.5f",k,p[k]);
                   8176:     printf("\n");
                   8177:     
                   8178:     /*--------- results files --------------*/
1.192     brouard  8179:     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  8180:     
                   8181:     
                   8182:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8183:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8184:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8185:     for(i=1,jk=1; i <=nlstate; i++){
                   8186:       for(k=1; k <=(nlstate+ndeath); k++){
                   8187:        if (k != i) {
                   8188:          printf("%d%d ",i,k);
                   8189:          fprintf(ficlog,"%d%d ",i,k);
                   8190:          fprintf(ficres,"%1d%1d ",i,k);
                   8191:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  8192:            printf("%12.7f ",p[jk]);
                   8193:            fprintf(ficlog,"%12.7f ",p[jk]);
                   8194:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  8195:            jk++; 
                   8196:          }
                   8197:          printf("\n");
                   8198:          fprintf(ficlog,"\n");
                   8199:          fprintf(ficres,"\n");
                   8200:        }
                   8201:       }
                   8202:     }
1.203     brouard  8203:     if(mle != 0){
                   8204:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  8205:       ftolhess=ftol; /* Usually correct */
1.203     brouard  8206:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   8207:       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");
                   8208:       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");
                   8209:       for(i=1,jk=1; i <=nlstate; i++){
                   8210:        for(k=1; k <=(nlstate+ndeath); k++){
                   8211:          if (k != i) {
                   8212:            printf("%d%d ",i,k);
                   8213:            fprintf(ficlog,"%d%d ",i,k);
                   8214:            for(j=1; j <=ncovmodel; j++){
                   8215:              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]));
                   8216:              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]));
                   8217:              jk++; 
                   8218:            }
                   8219:            printf("\n");
                   8220:            fprintf(ficlog,"\n");
1.193     brouard  8221:          }
                   8222:        }
                   8223:       }
1.203     brouard  8224:     } /* end of hesscov and Wald tests */
1.193     brouard  8225: 
1.203     brouard  8226:     /*  */
1.126     brouard  8227:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   8228:     printf("# Scales (for hessian or gradient estimation)\n");
                   8229:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   8230:     for(i=1,jk=1; i <=nlstate; i++){
                   8231:       for(j=1; j <=nlstate+ndeath; j++){
                   8232:        if (j!=i) {
                   8233:          fprintf(ficres,"%1d%1d",i,j);
                   8234:          printf("%1d%1d",i,j);
                   8235:          fprintf(ficlog,"%1d%1d",i,j);
                   8236:          for(k=1; k<=ncovmodel;k++){
                   8237:            printf(" %.5e",delti[jk]);
                   8238:            fprintf(ficlog," %.5e",delti[jk]);
                   8239:            fprintf(ficres," %.5e",delti[jk]);
                   8240:            jk++;
                   8241:          }
                   8242:          printf("\n");
                   8243:          fprintf(ficlog,"\n");
                   8244:          fprintf(ficres,"\n");
                   8245:        }
                   8246:       }
                   8247:     }
                   8248:     
                   8249:     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  8250:     if(mle >= 1) /* To big for the screen */
1.126     brouard  8251:       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");
                   8252:     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");
                   8253:     /* # 121 Var(a12)\n\ */
                   8254:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8255:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8256:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8257:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8258:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8259:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8260:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8261:     
                   8262:     
                   8263:     /* Just to have a covariance matrix which will be more understandable
                   8264:        even is we still don't want to manage dictionary of variables
                   8265:     */
                   8266:     for(itimes=1;itimes<=2;itimes++){
                   8267:       jj=0;
                   8268:       for(i=1; i <=nlstate; i++){
                   8269:        for(j=1; j <=nlstate+ndeath; j++){
                   8270:          if(j==i) continue;
                   8271:          for(k=1; k<=ncovmodel;k++){
                   8272:            jj++;
                   8273:            ca[0]= k+'a'-1;ca[1]='\0';
                   8274:            if(itimes==1){
                   8275:              if(mle>=1)
                   8276:                printf("#%1d%1d%d",i,j,k);
                   8277:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   8278:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   8279:            }else{
                   8280:              if(mle>=1)
                   8281:                printf("%1d%1d%d",i,j,k);
                   8282:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   8283:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   8284:            }
                   8285:            ll=0;
                   8286:            for(li=1;li <=nlstate; li++){
                   8287:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   8288:                if(lj==li) continue;
                   8289:                for(lk=1;lk<=ncovmodel;lk++){
                   8290:                  ll++;
                   8291:                  if(ll<=jj){
                   8292:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   8293:                    if(ll<jj){
                   8294:                      if(itimes==1){
                   8295:                        if(mle>=1)
                   8296:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8297:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8298:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8299:                      }else{
                   8300:                        if(mle>=1)
                   8301:                          printf(" %.5e",matcov[jj][ll]); 
                   8302:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   8303:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   8304:                      }
                   8305:                    }else{
                   8306:                      if(itimes==1){
                   8307:                        if(mle>=1)
                   8308:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   8309:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   8310:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   8311:                      }else{
                   8312:                        if(mle>=1)
1.203     brouard  8313:                          printf(" %.7e",matcov[jj][ll]); 
                   8314:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   8315:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  8316:                      }
                   8317:                    }
                   8318:                  }
                   8319:                } /* end lk */
                   8320:              } /* end lj */
                   8321:            } /* end li */
                   8322:            if(mle>=1)
                   8323:              printf("\n");
                   8324:            fprintf(ficlog,"\n");
                   8325:            fprintf(ficres,"\n");
                   8326:            numlinepar++;
                   8327:          } /* end k*/
                   8328:        } /*end j */
                   8329:       } /* end i */
                   8330:     } /* end itimes */
                   8331:     
                   8332:     fflush(ficlog);
                   8333:     fflush(ficres);
1.209     brouard  8334:       while(fgets(line, MAXLINE, ficpar)) {
                   8335:     /* If line starts with a # it is a comment */
                   8336:     if (line[0] == '#') {
                   8337:       numlinepar++;
1.141     brouard  8338:       fputs(line,stdout);
1.126     brouard  8339:       fputs(line,ficparo);
1.209     brouard  8340:       fputs(line,ficlog);
                   8341:       continue;
                   8342:     }else
                   8343:       break;
                   8344:   }
                   8345: 
                   8346:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   8347:     /*   ungetc(c,ficpar); */
                   8348:     /*   fgets(line, MAXLINE, ficpar); */
                   8349:     /*   fputs(line,stdout); */
                   8350:     /*   fputs(line,ficparo); */
                   8351:     /* } */
                   8352:     /* ungetc(c,ficpar); */
1.126     brouard  8353:     
                   8354:     estepm=0;
1.209     brouard  8355:     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){
                   8356: 
                   8357:     if (num_filled != 6) {
                   8358:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   8359:       printf("but line=%s\n",line);
                   8360:       goto end;
                   8361:     }
                   8362:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   8363:   }
                   8364:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   8365:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   8366: 
                   8367:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  8368:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   8369:     if (fage <= 2) {
                   8370:       bage = ageminpar;
                   8371:       fage = agemaxpar;
                   8372:     }
                   8373:     
                   8374:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  8375:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   8376:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  8377: 
                   8378:     /* Other stuffs, more or less useful */    
1.126     brouard  8379:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8380:       ungetc(c,ficpar);
                   8381:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8382:       fputs(line,stdout);
1.126     brouard  8383:       fputs(line,ficparo);
                   8384:     }
                   8385:     ungetc(c,ficpar);
                   8386:     
                   8387:     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);
                   8388:     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);
                   8389:     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);
                   8390:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   8391:     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);
                   8392:     
                   8393:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8394:       ungetc(c,ficpar);
                   8395:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8396:       fputs(line,stdout);
1.126     brouard  8397:       fputs(line,ficparo);
                   8398:     }
                   8399:     ungetc(c,ficpar);
                   8400:     
                   8401:     
                   8402:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8403:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8404:     
                   8405:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8406:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8407:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8408:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8409:     
                   8410:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8411:       ungetc(c,ficpar);
                   8412:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8413:       fputs(line,stdout);
1.126     brouard  8414:       fputs(line,ficparo);
                   8415:     }
                   8416:     ungetc(c,ficpar);
                   8417:     
                   8418:     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);
                   8419:     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);
                   8420:     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);
                   8421:     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);
                   8422:     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);
                   8423:     /* day and month of proj2 are not used but only year anproj2.*/
                   8424:     
                   8425:     
                   8426:     
1.145     brouard  8427:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8428:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8429:     
                   8430:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8431:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8432:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8433: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8434: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8435:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8436: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8437: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8438:     }else
1.211     brouard  8439:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126     brouard  8440:     
1.201     brouard  8441:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211     brouard  8442:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.213     brouard  8443:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126     brouard  8444:       
                   8445:    /*------------ free_vector  -------------*/
                   8446:    /*  chdir(path); */
                   8447:  
                   8448:     free_ivector(wav,1,imx);
1.214   ! brouard  8449:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
        !          8450:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
        !          8451:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.126     brouard  8452:     free_lvector(num,1,n);
                   8453:     free_vector(agedc,1,n);
                   8454:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8455:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8456:     fclose(ficparo);
                   8457:     fclose(ficres);
                   8458: 
                   8459: 
1.186     brouard  8460:     /* Other results (useful)*/
                   8461: 
                   8462: 
1.126     brouard  8463:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8464:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8465:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  8466:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8467:     fclose(ficrespl);
                   8468: 
1.145     brouard  8469: #ifdef FREEEXIT2
                   8470: #include "freeexit2.h"
                   8471: #endif
                   8472: 
1.126     brouard  8473:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8474:     /*#include "hpijx.h"*/
                   8475:     hPijx(p, bage, fage);
1.145     brouard  8476:     fclose(ficrespij);
1.126     brouard  8477: 
1.145     brouard  8478:   /*-------------- Variance of one-step probabilities---*/
                   8479:     k=1;
1.126     brouard  8480:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8481: 
                   8482: 
                   8483:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8484:     for(i=1;i<=AGESUP;i++)
                   8485:       for(j=1;j<=NCOVMAX;j++)
                   8486:        for(k=1;k<=NCOVMAX;k++)
                   8487:          probs[i][j][k]=0.;
                   8488: 
                   8489:     /*---------- Forecasting ------------------*/
                   8490:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8491:     if(prevfcast==1){
                   8492:       /*    if(stepm ==1){*/
1.201     brouard  8493:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8494:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8495:       /*      }  */
                   8496:       /*      else{ */
                   8497:       /*        erreur=108; */
                   8498:       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   8499:       /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   8500:       /*      } */
                   8501:     }
1.186     brouard  8502:  
                   8503:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8504: 
1.127     brouard  8505:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8506: 
                   8507:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8508:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
                   8509:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8510:     */
1.126     brouard  8511: 
1.127     brouard  8512:     if (mobilav!=0) {
                   8513:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8514:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8515:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8516:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8517:       }
1.126     brouard  8518:     }
                   8519: 
                   8520: 
1.127     brouard  8521:     /*---------- Health expectancies, no variances ------------*/
                   8522: 
1.201     brouard  8523:     strcpy(filerese,"E_");
                   8524:     strcat(filerese,fileresu);
1.126     brouard  8525:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8526:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8527:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8528:     }
1.208     brouard  8529:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8530:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8531:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8532:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8533:           
                   8534:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8535:        fprintf(ficreseij,"\n#****** ");
                   8536:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8537:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8538:        }
                   8539:        fprintf(ficreseij,"******\n");
                   8540: 
                   8541:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8542:        oldm=oldms;savm=savms;
                   8543:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8544:       
                   8545:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8546:       /*}*/
1.127     brouard  8547:     }
                   8548:     fclose(ficreseij);
1.208     brouard  8549:     printf("done evsij\n");fflush(stdout);
                   8550:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8551: 
                   8552:     /*---------- Health expectancies and variances ------------*/
                   8553: 
                   8554: 
1.201     brouard  8555:     strcpy(filerest,"T_");
                   8556:     strcat(filerest,fileresu);
1.127     brouard  8557:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8558:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8559:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8560:     }
1.208     brouard  8561:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8562:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8563: 
1.126     brouard  8564: 
1.201     brouard  8565:     strcpy(fileresstde,"STDE_");
                   8566:     strcat(fileresstde,fileresu);
1.126     brouard  8567:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8568:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8569:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8570:     }
1.208     brouard  8571:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8572:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8573: 
1.201     brouard  8574:     strcpy(filerescve,"CVE_");
                   8575:     strcat(filerescve,fileresu);
1.126     brouard  8576:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8577:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8578:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8579:     }
1.208     brouard  8580:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8581:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8582: 
1.201     brouard  8583:     strcpy(fileresv,"V_");
                   8584:     strcat(fileresv,fileresu);
1.126     brouard  8585:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8586:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8587:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8588:     }
1.208     brouard  8589:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8590:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8591: 
1.145     brouard  8592:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8593:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8594:           
                   8595:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8596:       fprintf(ficrest,"\n#****** ");
                   8597:       for(j=1;j<=cptcoveff;j++) 
                   8598:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8599:       fprintf(ficrest,"******\n");
                   8600:       
                   8601:       fprintf(ficresstdeij,"\n#****** ");
                   8602:       fprintf(ficrescveij,"\n#****** ");
                   8603:       for(j=1;j<=cptcoveff;j++) {
                   8604:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8605:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8606:       }
                   8607:       fprintf(ficresstdeij,"******\n");
                   8608:       fprintf(ficrescveij,"******\n");
                   8609:       
                   8610:       fprintf(ficresvij,"\n#****** ");
                   8611:       for(j=1;j<=cptcoveff;j++) 
                   8612:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8613:       fprintf(ficresvij,"******\n");
                   8614:       
                   8615:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8616:       oldm=oldms;savm=savms;
                   8617:       printf(" cvevsij %d, ",k);
                   8618:       fprintf(ficlog, " cvevsij %d, ",k);
                   8619:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8620:       printf(" end cvevsij \n ");
                   8621:       fprintf(ficlog, " end cvevsij \n ");
                   8622:       
                   8623:       /*
                   8624:        */
                   8625:       /* goto endfree; */
                   8626:       
                   8627:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8628:       pstamp(ficrest);
                   8629:       
                   8630:       
                   8631:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8632:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8633:        cptcod= 0; /* To be deleted */
                   8634:        printf("varevsij %d \n",vpopbased);
                   8635:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  8636:        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 */
1.208     brouard  8637:        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 ");
                   8638:        if(vpopbased==1)
                   8639:          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);
                   8640:        else
                   8641:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8642:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8643:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8644:        fprintf(ficrest,"\n");
                   8645:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8646:        epj=vector(1,nlstate+1);
                   8647:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8648:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8649:        for(age=bage; age <=fage ;age++){
1.209     brouard  8650:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8651:          if (vpopbased==1) {
                   8652:            if(mobilav ==0){
                   8653:              for(i=1; i<=nlstate;i++)
                   8654:                prlim[i][i]=probs[(int)age][i][k];
                   8655:            }else{ /* mobilav */ 
                   8656:              for(i=1; i<=nlstate;i++)
                   8657:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8658:            }
1.208     brouard  8659:          }
                   8660:          
                   8661:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8662:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8663:          /* printf(" age %4.0f ",age); */
                   8664:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8665:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8666:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8667:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8668:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8669:            }
1.208     brouard  8670:            epj[nlstate+1] +=epj[j];
                   8671:          }
                   8672:          /* printf(" age %4.0f \n",age); */
                   8673:          
                   8674:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8675:            for(j=1;j <=nlstate;j++)
                   8676:              vepp += vareij[i][j][(int)age];
                   8677:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8678:          for(j=1;j <=nlstate;j++){
                   8679:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8680:          }
1.208     brouard  8681:          fprintf(ficrest,"\n");
1.126     brouard  8682:        }
1.208     brouard  8683:       } /* End vpopbased */
                   8684:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8685:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8686:       free_vector(epj,1,nlstate+1);
                   8687:       printf("done \n");fflush(stdout);
                   8688:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8689:       
1.145     brouard  8690:       /*}*/
1.208     brouard  8691:     } /* End k */
1.126     brouard  8692:     free_vector(weight,1,n);
1.145     brouard  8693:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8694:     free_imatrix(s,1,maxwav+1,1,n);
                   8695:     free_matrix(anint,1,maxwav,1,n); 
                   8696:     free_matrix(mint,1,maxwav,1,n);
                   8697:     free_ivector(cod,1,n);
                   8698:     free_ivector(tab,1,NCOVMAX);
                   8699:     fclose(ficresstdeij);
                   8700:     fclose(ficrescveij);
                   8701:     fclose(ficresvij);
                   8702:     fclose(ficrest);
1.208     brouard  8703:     printf("done Health expectancies\n");fflush(stdout);
                   8704:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8705:     fclose(ficpar);
                   8706:   
                   8707:     /*------- Variance of period (stable) prevalence------*/   
                   8708: 
1.201     brouard  8709:     strcpy(fileresvpl,"VPL_");
                   8710:     strcat(fileresvpl,fileresu);
1.126     brouard  8711:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8712:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8713:       exit(0);
                   8714:     }
1.208     brouard  8715:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8716:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8717: 
1.145     brouard  8718:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8719:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8720:           
                   8721:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8722:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8723:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8724:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8725:        fprintf(ficresvpl,"******\n");
                   8726:       
                   8727:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8728:        oldm=oldms;savm=savms;
1.209     brouard  8729:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8730:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8731:       /*}*/
1.126     brouard  8732:     }
                   8733: 
                   8734:     fclose(ficresvpl);
1.208     brouard  8735:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8736:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8737: 
                   8738:     /*---------- End : free ----------------*/
                   8739:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8740:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8741:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8742:  /* endfree:*/
1.141     brouard  8743:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8744:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8745:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8746:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8747:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8748:     free_matrix(covar,0,NCOVMAX,1,n);
                   8749:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8750:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8751:     /*free_vector(delti,1,npar);*/
                   8752:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8753:     free_matrix(agev,1,maxwav,1,imx);
                   8754:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8755: 
1.145     brouard  8756:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8757:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8758:     free_ivector(Tvar,1,NCOVMAX);
                   8759:     free_ivector(Tprod,1,NCOVMAX);
                   8760:     free_ivector(Tvaraff,1,NCOVMAX);
                   8761:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8762: 
                   8763:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8764:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8765:   fflush(fichtm);
                   8766:   fflush(ficgp);
                   8767:   
                   8768: 
                   8769:   if((nberr >0) || (nbwarn>0)){
                   8770:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8771:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8772:   }else{
                   8773:     printf("End of Imach\n");
                   8774:     fprintf(ficlog,"End of Imach\n");
                   8775:   }
                   8776:   printf("See log file on %s\n",filelog);
                   8777:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8778:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8779:   rend_time = time(NULL);  
                   8780:   end_time = *localtime(&rend_time);
                   8781:   /* tml = *localtime(&end_time.tm_sec); */
                   8782:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8783:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8784:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8785:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8786: 
1.157     brouard  8787:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8788:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8789:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8790:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8791: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8792:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8793:   fclose(fichtm);
                   8794:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8795:   fclose(fichtmcov);
                   8796:   fclose(ficgp);
                   8797:   fclose(ficlog);
                   8798:   /*------ End -----------*/
                   8799: 
                   8800: 
                   8801:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8802: #ifdef WIN32
                   8803:    if (_chdir(pathcd) != 0)
                   8804:           printf("Can't move to directory %s!\n",path);
                   8805:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8806: #else
1.126     brouard  8807:    if(chdir(pathcd) != 0)
1.184     brouard  8808:           printf("Can't move to directory %s!\n", path);
                   8809:    if (getcwd(pathcd, MAXLINE) > 0)
                   8810: #endif 
1.126     brouard  8811:     printf("Current directory %s!\n",pathcd);
                   8812:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8813:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8814: #ifdef _WIN32
1.126     brouard  8815:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8816: #endif
                   8817:   if(!stat(plotcmd,&info)){
1.158     brouard  8818:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8819:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8820:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8821:     }else
                   8822:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8823: #ifdef __unix
1.126     brouard  8824:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8825:     if(!stat(plotcmd,&info)){
1.158     brouard  8826:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8827:     }else
                   8828:       strcpy(pplotcmd,plotcmd);
                   8829: #endif
                   8830:   }else
                   8831:     strcpy(pplotcmd,plotcmd);
                   8832:   
                   8833:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8834:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8835: 
                   8836:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8837:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8838:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8839:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8840:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8841:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8842:   }
1.158     brouard  8843:   printf(" Successful, please wait...");
1.126     brouard  8844:   while (z[0] != 'q') {
                   8845:     /* chdir(path); */
1.154     brouard  8846:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8847:     scanf("%s",z);
                   8848: /*     if (z[0] == 'c') system("./imach"); */
                   8849:     if (z[0] == 'e') {
1.158     brouard  8850: #ifdef __APPLE__
1.152     brouard  8851:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8852: #elif __linux
                   8853:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8854: #else
1.152     brouard  8855:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8856: #endif
                   8857:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8858:       system(pplotcmd);
1.126     brouard  8859:     }
                   8860:     else if (z[0] == 'g') system(plotcmd);
                   8861:     else if (z[0] == 'q') exit(0);
                   8862:   }
                   8863:   end:
                   8864:   while (z[0] != 'q') {
1.195     brouard  8865:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8866:     scanf("%s",z);
                   8867:   }
                   8868: }

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