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

1.222   ! brouard     1: /* $Id: imach.c,v 1.221 2016/02/15 23:35:36 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.222   ! brouard     4:   Revision 1.221  2016/02/15 23:35:36  brouard
        !             5:   Summary: minor bug
        !             6: 
1.220     brouard     7:   Revision 1.219  2016/02/15 00:48:12  brouard
                      8:   *** empty log message ***
                      9: 
1.219     brouard    10:   Revision 1.218  2016/02/12 11:29:23  brouard
                     11:   Summary: 0.99 Back projections
                     12: 
1.218     brouard    13:   Revision 1.217  2015/12/23 17:18:31  brouard
                     14:   Summary: Experimental backcast
                     15: 
1.217     brouard    16:   Revision 1.216  2015/12/18 17:32:11  brouard
                     17:   Summary: 0.98r4 Warning and status=-2
                     18: 
                     19:   Version 0.98r4 is now:
                     20:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     21:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     22:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     23: 
1.216     brouard    24:   Revision 1.215  2015/12/16 08:52:24  brouard
                     25:   Summary: 0.98r4 working
                     26: 
1.215     brouard    27:   Revision 1.214  2015/12/16 06:57:54  brouard
                     28:   Summary: temporary not working
                     29: 
1.214     brouard    30:   Revision 1.213  2015/12/11 18:22:17  brouard
                     31:   Summary: 0.98r4
                     32: 
1.213     brouard    33:   Revision 1.212  2015/11/21 12:47:24  brouard
                     34:   Summary: minor typo
                     35: 
1.212     brouard    36:   Revision 1.211  2015/11/21 12:41:11  brouard
                     37:   Summary: 0.98r3 with some graph of projected cross-sectional
                     38: 
                     39:   Author: Nicolas Brouard
                     40: 
1.211     brouard    41:   Revision 1.210  2015/11/18 17:41:20  brouard
                     42:   Summary: Start working on projected prevalences
                     43: 
1.210     brouard    44:   Revision 1.209  2015/11/17 22:12:03  brouard
                     45:   Summary: Adding ftolpl parameter
                     46:   Author: N Brouard
                     47: 
                     48:   We had difficulties to get smoothed confidence intervals. It was due
                     49:   to the period prevalence which wasn't computed accurately. The inner
                     50:   parameter ftolpl is now an outer parameter of the .imach parameter
                     51:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     52:   computation are long.
                     53: 
1.209     brouard    54:   Revision 1.208  2015/11/17 14:31:57  brouard
                     55:   Summary: temporary
                     56: 
1.208     brouard    57:   Revision 1.207  2015/10/27 17:36:57  brouard
                     58:   *** empty log message ***
                     59: 
1.207     brouard    60:   Revision 1.206  2015/10/24 07:14:11  brouard
                     61:   *** empty log message ***
                     62: 
1.206     brouard    63:   Revision 1.205  2015/10/23 15:50:53  brouard
                     64:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     65: 
1.205     brouard    66:   Revision 1.204  2015/10/01 16:20:26  brouard
                     67:   Summary: Some new graphs of contribution to likelihood
                     68: 
1.204     brouard    69:   Revision 1.203  2015/09/30 17:45:14  brouard
                     70:   Summary: looking at better estimation of the hessian
                     71: 
                     72:   Also a better criteria for convergence to the period prevalence And
                     73:   therefore adding the number of years needed to converge. (The
                     74:   prevalence in any alive state shold sum to one
                     75: 
1.203     brouard    76:   Revision 1.202  2015/09/22 19:45:16  brouard
                     77:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     78: 
1.202     brouard    79:   Revision 1.201  2015/09/15 17:34:58  brouard
                     80:   Summary: 0.98r0
                     81: 
                     82:   - Some new graphs like suvival functions
                     83:   - Some bugs fixed like model=1+age+V2.
                     84: 
1.201     brouard    85:   Revision 1.200  2015/09/09 16:53:55  brouard
                     86:   Summary: Big bug thanks to Flavia
                     87: 
                     88:   Even model=1+age+V2. did not work anymore
                     89: 
1.200     brouard    90:   Revision 1.199  2015/09/07 14:09:23  brouard
                     91:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     92: 
1.199     brouard    93:   Revision 1.198  2015/09/03 07:14:39  brouard
                     94:   Summary: 0.98q5 Flavia
                     95: 
1.198     brouard    96:   Revision 1.197  2015/09/01 18:24:39  brouard
                     97:   *** empty log message ***
                     98: 
1.197     brouard    99:   Revision 1.196  2015/08/18 23:17:52  brouard
                    100:   Summary: 0.98q5
                    101: 
1.196     brouard   102:   Revision 1.195  2015/08/18 16:28:39  brouard
                    103:   Summary: Adding a hack for testing purpose
                    104: 
                    105:   After reading the title, ftol and model lines, if the comment line has
                    106:   a q, starting with #q, the answer at the end of the run is quit. It
                    107:   permits to run test files in batch with ctest. The former workaround was
                    108:   $ echo q | imach foo.imach
                    109: 
1.195     brouard   110:   Revision 1.194  2015/08/18 13:32:00  brouard
                    111:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    112: 
1.194     brouard   113:   Revision 1.193  2015/08/04 07:17:42  brouard
                    114:   Summary: 0.98q4
                    115: 
1.193     brouard   116:   Revision 1.192  2015/07/16 16:49:02  brouard
                    117:   Summary: Fixing some outputs
                    118: 
1.192     brouard   119:   Revision 1.191  2015/07/14 10:00:33  brouard
                    120:   Summary: Some fixes
                    121: 
1.191     brouard   122:   Revision 1.190  2015/05/05 08:51:13  brouard
                    123:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    124: 
                    125:   Fix 1+age+.
                    126: 
1.190     brouard   127:   Revision 1.189  2015/04/30 14:45:16  brouard
                    128:   Summary: 0.98q2
                    129: 
1.189     brouard   130:   Revision 1.188  2015/04/30 08:27:53  brouard
                    131:   *** empty log message ***
                    132: 
1.188     brouard   133:   Revision 1.187  2015/04/29 09:11:15  brouard
                    134:   *** empty log message ***
                    135: 
1.187     brouard   136:   Revision 1.186  2015/04/23 12:01:52  brouard
                    137:   Summary: V1*age is working now, version 0.98q1
                    138: 
                    139:   Some codes had been disabled in order to simplify and Vn*age was
                    140:   working in the optimization phase, ie, giving correct MLE parameters,
                    141:   but, as usual, outputs were not correct and program core dumped.
                    142: 
1.186     brouard   143:   Revision 1.185  2015/03/11 13:26:42  brouard
                    144:   Summary: Inclusion of compile and links command line for Intel Compiler
                    145: 
1.185     brouard   146:   Revision 1.184  2015/03/11 11:52:39  brouard
                    147:   Summary: Back from Windows 8. Intel Compiler
                    148: 
1.184     brouard   149:   Revision 1.183  2015/03/10 20:34:32  brouard
                    150:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    151: 
                    152:   We use directest instead of original Powell test; probably no
                    153:   incidence on the results, but better justifications;
                    154:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    155:   wrong results.
                    156: 
1.183     brouard   157:   Revision 1.182  2015/02/12 08:19:57  brouard
                    158:   Summary: Trying to keep directest which seems simpler and more general
                    159:   Author: Nicolas Brouard
                    160: 
1.182     brouard   161:   Revision 1.181  2015/02/11 23:22:24  brouard
                    162:   Summary: Comments on Powell added
                    163: 
                    164:   Author:
                    165: 
1.181     brouard   166:   Revision 1.180  2015/02/11 17:33:45  brouard
                    167:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    168: 
1.180     brouard   169:   Revision 1.179  2015/01/04 09:57:06  brouard
                    170:   Summary: back to OS/X
                    171: 
1.179     brouard   172:   Revision 1.178  2015/01/04 09:35:48  brouard
                    173:   *** empty log message ***
                    174: 
1.178     brouard   175:   Revision 1.177  2015/01/03 18:40:56  brouard
                    176:   Summary: Still testing ilc32 on OSX
                    177: 
1.177     brouard   178:   Revision 1.176  2015/01/03 16:45:04  brouard
                    179:   *** empty log message ***
                    180: 
1.176     brouard   181:   Revision 1.175  2015/01/03 16:33:42  brouard
                    182:   *** empty log message ***
                    183: 
1.175     brouard   184:   Revision 1.174  2015/01/03 16:15:49  brouard
                    185:   Summary: Still in cross-compilation
                    186: 
1.174     brouard   187:   Revision 1.173  2015/01/03 12:06:26  brouard
                    188:   Summary: trying to detect cross-compilation
                    189: 
1.173     brouard   190:   Revision 1.172  2014/12/27 12:07:47  brouard
                    191:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    192: 
1.172     brouard   193:   Revision 1.171  2014/12/23 13:26:59  brouard
                    194:   Summary: Back from Visual C
                    195: 
                    196:   Still problem with utsname.h on Windows
                    197: 
1.171     brouard   198:   Revision 1.170  2014/12/23 11:17:12  brouard
                    199:   Summary: Cleaning some \%% back to %%
                    200: 
                    201:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    202: 
1.170     brouard   203:   Revision 1.169  2014/12/22 23:08:31  brouard
                    204:   Summary: 0.98p
                    205: 
                    206:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    207: 
1.169     brouard   208:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   209:   Summary: update
1.169     brouard   210: 
1.168     brouard   211:   Revision 1.167  2014/12/22 13:50:56  brouard
                    212:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    213: 
                    214:   Testing on Linux 64
                    215: 
1.167     brouard   216:   Revision 1.166  2014/12/22 11:40:47  brouard
                    217:   *** empty log message ***
                    218: 
1.166     brouard   219:   Revision 1.165  2014/12/16 11:20:36  brouard
                    220:   Summary: After compiling on Visual C
                    221: 
                    222:   * imach.c (Module): Merging 1.61 to 1.162
                    223: 
1.165     brouard   224:   Revision 1.164  2014/12/16 10:52:11  brouard
                    225:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    226: 
                    227:   * imach.c (Module): Merging 1.61 to 1.162
                    228: 
1.164     brouard   229:   Revision 1.163  2014/12/16 10:30:11  brouard
                    230:   * imach.c (Module): Merging 1.61 to 1.162
                    231: 
1.163     brouard   232:   Revision 1.162  2014/09/25 11:43:39  brouard
                    233:   Summary: temporary backup 0.99!
                    234: 
1.162     brouard   235:   Revision 1.1  2014/09/16 11:06:58  brouard
                    236:   Summary: With some code (wrong) for nlopt
                    237: 
                    238:   Author:
                    239: 
                    240:   Revision 1.161  2014/09/15 20:41:41  brouard
                    241:   Summary: Problem with macro SQR on Intel compiler
                    242: 
1.161     brouard   243:   Revision 1.160  2014/09/02 09:24:05  brouard
                    244:   *** empty log message ***
                    245: 
1.160     brouard   246:   Revision 1.159  2014/09/01 10:34:10  brouard
                    247:   Summary: WIN32
                    248:   Author: Brouard
                    249: 
1.159     brouard   250:   Revision 1.158  2014/08/27 17:11:51  brouard
                    251:   *** empty log message ***
                    252: 
1.158     brouard   253:   Revision 1.157  2014/08/27 16:26:55  brouard
                    254:   Summary: Preparing windows Visual studio version
                    255:   Author: Brouard
                    256: 
                    257:   In order to compile on Visual studio, time.h is now correct and time_t
                    258:   and tm struct should be used. difftime should be used but sometimes I
                    259:   just make the differences in raw time format (time(&now).
                    260:   Trying to suppress #ifdef LINUX
                    261:   Add xdg-open for __linux in order to open default browser.
                    262: 
1.157     brouard   263:   Revision 1.156  2014/08/25 20:10:10  brouard
                    264:   *** empty log message ***
                    265: 
1.156     brouard   266:   Revision 1.155  2014/08/25 18:32:34  brouard
                    267:   Summary: New compile, minor changes
                    268:   Author: Brouard
                    269: 
1.155     brouard   270:   Revision 1.154  2014/06/20 17:32:08  brouard
                    271:   Summary: Outputs now all graphs of convergence to period prevalence
                    272: 
1.154     brouard   273:   Revision 1.153  2014/06/20 16:45:46  brouard
                    274:   Summary: If 3 live state, convergence to period prevalence on same graph
                    275:   Author: Brouard
                    276: 
1.153     brouard   277:   Revision 1.152  2014/06/18 17:54:09  brouard
                    278:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    279: 
1.152     brouard   280:   Revision 1.151  2014/06/18 16:43:30  brouard
                    281:   *** empty log message ***
                    282: 
1.151     brouard   283:   Revision 1.150  2014/06/18 16:42:35  brouard
                    284:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    285:   Author: brouard
                    286: 
1.150     brouard   287:   Revision 1.149  2014/06/18 15:51:14  brouard
                    288:   Summary: Some fixes in parameter files errors
                    289:   Author: Nicolas Brouard
                    290: 
1.149     brouard   291:   Revision 1.148  2014/06/17 17:38:48  brouard
                    292:   Summary: Nothing new
                    293:   Author: Brouard
                    294: 
                    295:   Just a new packaging for OS/X version 0.98nS
                    296: 
1.148     brouard   297:   Revision 1.147  2014/06/16 10:33:11  brouard
                    298:   *** empty log message ***
                    299: 
1.147     brouard   300:   Revision 1.146  2014/06/16 10:20:28  brouard
                    301:   Summary: Merge
                    302:   Author: Brouard
                    303: 
                    304:   Merge, before building revised version.
                    305: 
1.146     brouard   306:   Revision 1.145  2014/06/10 21:23:15  brouard
                    307:   Summary: Debugging with valgrind
                    308:   Author: Nicolas Brouard
                    309: 
                    310:   Lot of changes in order to output the results with some covariates
                    311:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    312:   improve the code.
                    313:   No more memory valgrind error but a lot has to be done in order to
                    314:   continue the work of splitting the code into subroutines.
                    315:   Also, decodemodel has been improved. Tricode is still not
                    316:   optimal. nbcode should be improved. Documentation has been added in
                    317:   the source code.
                    318: 
1.144     brouard   319:   Revision 1.143  2014/01/26 09:45:38  brouard
                    320:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    321: 
                    322:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    323:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    324: 
1.143     brouard   325:   Revision 1.142  2014/01/26 03:57:36  brouard
                    326:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    327: 
                    328:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    329: 
1.142     brouard   330:   Revision 1.141  2014/01/26 02:42:01  brouard
                    331:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    332: 
1.141     brouard   333:   Revision 1.140  2011/09/02 10:37:54  brouard
                    334:   Summary: times.h is ok with mingw32 now.
                    335: 
1.140     brouard   336:   Revision 1.139  2010/06/14 07:50:17  brouard
                    337:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    338:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    339: 
1.139     brouard   340:   Revision 1.138  2010/04/30 18:19:40  brouard
                    341:   *** empty log message ***
                    342: 
1.138     brouard   343:   Revision 1.137  2010/04/29 18:11:38  brouard
                    344:   (Module): Checking covariates for more complex models
                    345:   than V1+V2. A lot of change to be done. Unstable.
                    346: 
1.137     brouard   347:   Revision 1.136  2010/04/26 20:30:53  brouard
                    348:   (Module): merging some libgsl code. Fixing computation
                    349:   of likelione (using inter/intrapolation if mle = 0) in order to
                    350:   get same likelihood as if mle=1.
                    351:   Some cleaning of code and comments added.
                    352: 
1.136     brouard   353:   Revision 1.135  2009/10/29 15:33:14  brouard
                    354:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    355: 
1.135     brouard   356:   Revision 1.134  2009/10/29 13:18:53  brouard
                    357:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    358: 
1.134     brouard   359:   Revision 1.133  2009/07/06 10:21:25  brouard
                    360:   just nforces
                    361: 
1.133     brouard   362:   Revision 1.132  2009/07/06 08:22:05  brouard
                    363:   Many tings
                    364: 
1.132     brouard   365:   Revision 1.131  2009/06/20 16:22:47  brouard
                    366:   Some dimensions resccaled
                    367: 
1.131     brouard   368:   Revision 1.130  2009/05/26 06:44:34  brouard
                    369:   (Module): Max Covariate is now set to 20 instead of 8. A
                    370:   lot of cleaning with variables initialized to 0. Trying to make
                    371:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    372: 
1.130     brouard   373:   Revision 1.129  2007/08/31 13:49:27  lievre
                    374:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    375: 
1.129     lievre    376:   Revision 1.128  2006/06/30 13:02:05  brouard
                    377:   (Module): Clarifications on computing e.j
                    378: 
1.128     brouard   379:   Revision 1.127  2006/04/28 18:11:50  brouard
                    380:   (Module): Yes the sum of survivors was wrong since
                    381:   imach-114 because nhstepm was no more computed in the age
                    382:   loop. Now we define nhstepma in the age loop.
                    383:   (Module): In order to speed up (in case of numerous covariates) we
                    384:   compute health expectancies (without variances) in a first step
                    385:   and then all the health expectancies with variances or standard
                    386:   deviation (needs data from the Hessian matrices) which slows the
                    387:   computation.
                    388:   In the future we should be able to stop the program is only health
                    389:   expectancies and graph are needed without standard deviations.
                    390: 
1.127     brouard   391:   Revision 1.126  2006/04/28 17:23:28  brouard
                    392:   (Module): Yes the sum of survivors was wrong since
                    393:   imach-114 because nhstepm was no more computed in the age
                    394:   loop. Now we define nhstepma in the age loop.
                    395:   Version 0.98h
                    396: 
1.126     brouard   397:   Revision 1.125  2006/04/04 15:20:31  lievre
                    398:   Errors in calculation of health expectancies. Age was not initialized.
                    399:   Forecasting file added.
                    400: 
                    401:   Revision 1.124  2006/03/22 17:13:53  lievre
                    402:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    403:   The log-likelihood is printed in the log file
                    404: 
                    405:   Revision 1.123  2006/03/20 10:52:43  brouard
                    406:   * imach.c (Module): <title> changed, corresponds to .htm file
                    407:   name. <head> headers where missing.
                    408: 
                    409:   * imach.c (Module): Weights can have a decimal point as for
                    410:   English (a comma might work with a correct LC_NUMERIC environment,
                    411:   otherwise the weight is truncated).
                    412:   Modification of warning when the covariates values are not 0 or
                    413:   1.
                    414:   Version 0.98g
                    415: 
                    416:   Revision 1.122  2006/03/20 09:45:41  brouard
                    417:   (Module): Weights can have a decimal point as for
                    418:   English (a comma might work with a correct LC_NUMERIC environment,
                    419:   otherwise the weight is truncated).
                    420:   Modification of warning when the covariates values are not 0 or
                    421:   1.
                    422:   Version 0.98g
                    423: 
                    424:   Revision 1.121  2006/03/16 17:45:01  lievre
                    425:   * imach.c (Module): Comments concerning covariates added
                    426: 
                    427:   * imach.c (Module): refinements in the computation of lli if
                    428:   status=-2 in order to have more reliable computation if stepm is
                    429:   not 1 month. Version 0.98f
                    430: 
                    431:   Revision 1.120  2006/03/16 15:10:38  lievre
                    432:   (Module): refinements in the computation of lli if
                    433:   status=-2 in order to have more reliable computation if stepm is
                    434:   not 1 month. Version 0.98f
                    435: 
                    436:   Revision 1.119  2006/03/15 17:42:26  brouard
                    437:   (Module): Bug if status = -2, the loglikelihood was
                    438:   computed as likelihood omitting the logarithm. Version O.98e
                    439: 
                    440:   Revision 1.118  2006/03/14 18:20:07  brouard
                    441:   (Module): varevsij Comments added explaining the second
                    442:   table of variances if popbased=1 .
                    443:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    444:   (Module): Function pstamp added
                    445:   (Module): Version 0.98d
                    446: 
                    447:   Revision 1.117  2006/03/14 17:16:22  brouard
                    448:   (Module): varevsij Comments added explaining the second
                    449:   table of variances if popbased=1 .
                    450:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    451:   (Module): Function pstamp added
                    452:   (Module): Version 0.98d
                    453: 
                    454:   Revision 1.116  2006/03/06 10:29:27  brouard
                    455:   (Module): Variance-covariance wrong links and
                    456:   varian-covariance of ej. is needed (Saito).
                    457: 
                    458:   Revision 1.115  2006/02/27 12:17:45  brouard
                    459:   (Module): One freematrix added in mlikeli! 0.98c
                    460: 
                    461:   Revision 1.114  2006/02/26 12:57:58  brouard
                    462:   (Module): Some improvements in processing parameter
                    463:   filename with strsep.
                    464: 
                    465:   Revision 1.113  2006/02/24 14:20:24  brouard
                    466:   (Module): Memory leaks checks with valgrind and:
                    467:   datafile was not closed, some imatrix were not freed and on matrix
                    468:   allocation too.
                    469: 
                    470:   Revision 1.112  2006/01/30 09:55:26  brouard
                    471:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    472: 
                    473:   Revision 1.111  2006/01/25 20:38:18  brouard
                    474:   (Module): Lots of cleaning and bugs added (Gompertz)
                    475:   (Module): Comments can be added in data file. Missing date values
                    476:   can be a simple dot '.'.
                    477: 
                    478:   Revision 1.110  2006/01/25 00:51:50  brouard
                    479:   (Module): Lots of cleaning and bugs added (Gompertz)
                    480: 
                    481:   Revision 1.109  2006/01/24 19:37:15  brouard
                    482:   (Module): Comments (lines starting with a #) are allowed in data.
                    483: 
                    484:   Revision 1.108  2006/01/19 18:05:42  lievre
                    485:   Gnuplot problem appeared...
                    486:   To be fixed
                    487: 
                    488:   Revision 1.107  2006/01/19 16:20:37  brouard
                    489:   Test existence of gnuplot in imach path
                    490: 
                    491:   Revision 1.106  2006/01/19 13:24:36  brouard
                    492:   Some cleaning and links added in html output
                    493: 
                    494:   Revision 1.105  2006/01/05 20:23:19  lievre
                    495:   *** empty log message ***
                    496: 
                    497:   Revision 1.104  2005/09/30 16:11:43  lievre
                    498:   (Module): sump fixed, loop imx fixed, and simplifications.
                    499:   (Module): If the status is missing at the last wave but we know
                    500:   that the person is alive, then we can code his/her status as -2
                    501:   (instead of missing=-1 in earlier versions) and his/her
                    502:   contributions to the likelihood is 1 - Prob of dying from last
                    503:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    504:   the healthy state at last known wave). Version is 0.98
                    505: 
                    506:   Revision 1.103  2005/09/30 15:54:49  lievre
                    507:   (Module): sump fixed, loop imx fixed, and simplifications.
                    508: 
                    509:   Revision 1.102  2004/09/15 17:31:30  brouard
                    510:   Add the possibility to read data file including tab characters.
                    511: 
                    512:   Revision 1.101  2004/09/15 10:38:38  brouard
                    513:   Fix on curr_time
                    514: 
                    515:   Revision 1.100  2004/07/12 18:29:06  brouard
                    516:   Add version for Mac OS X. Just define UNIX in Makefile
                    517: 
                    518:   Revision 1.99  2004/06/05 08:57:40  brouard
                    519:   *** empty log message ***
                    520: 
                    521:   Revision 1.98  2004/05/16 15:05:56  brouard
                    522:   New version 0.97 . First attempt to estimate force of mortality
                    523:   directly from the data i.e. without the need of knowing the health
                    524:   state at each age, but using a Gompertz model: log u =a + b*age .
                    525:   This is the basic analysis of mortality and should be done before any
                    526:   other analysis, in order to test if the mortality estimated from the
                    527:   cross-longitudinal survey is different from the mortality estimated
                    528:   from other sources like vital statistic data.
                    529: 
                    530:   The same imach parameter file can be used but the option for mle should be -3.
                    531: 
1.133     brouard   532:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   533:   former routines in order to include the new code within the former code.
                    534: 
                    535:   The output is very simple: only an estimate of the intercept and of
                    536:   the slope with 95% confident intervals.
                    537: 
                    538:   Current limitations:
                    539:   A) Even if you enter covariates, i.e. with the
                    540:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    541:   B) There is no computation of Life Expectancy nor Life Table.
                    542: 
                    543:   Revision 1.97  2004/02/20 13:25:42  lievre
                    544:   Version 0.96d. Population forecasting command line is (temporarily)
                    545:   suppressed.
                    546: 
                    547:   Revision 1.96  2003/07/15 15:38:55  brouard
                    548:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    549:   rewritten within the same printf. Workaround: many printfs.
                    550: 
                    551:   Revision 1.95  2003/07/08 07:54:34  brouard
                    552:   * imach.c (Repository):
                    553:   (Repository): Using imachwizard code to output a more meaningful covariance
                    554:   matrix (cov(a12,c31) instead of numbers.
                    555: 
                    556:   Revision 1.94  2003/06/27 13:00:02  brouard
                    557:   Just cleaning
                    558: 
                    559:   Revision 1.93  2003/06/25 16:33:55  brouard
                    560:   (Module): On windows (cygwin) function asctime_r doesn't
                    561:   exist so I changed back to asctime which exists.
                    562:   (Module): Version 0.96b
                    563: 
                    564:   Revision 1.92  2003/06/25 16:30:45  brouard
                    565:   (Module): On windows (cygwin) function asctime_r doesn't
                    566:   exist so I changed back to asctime which exists.
                    567: 
                    568:   Revision 1.91  2003/06/25 15:30:29  brouard
                    569:   * imach.c (Repository): Duplicated warning errors corrected.
                    570:   (Repository): Elapsed time after each iteration is now output. It
                    571:   helps to forecast when convergence will be reached. Elapsed time
                    572:   is stamped in powell.  We created a new html file for the graphs
                    573:   concerning matrix of covariance. It has extension -cov.htm.
                    574: 
                    575:   Revision 1.90  2003/06/24 12:34:15  brouard
                    576:   (Module): Some bugs corrected for windows. Also, when
                    577:   mle=-1 a template is output in file "or"mypar.txt with the design
                    578:   of the covariance matrix to be input.
                    579: 
                    580:   Revision 1.89  2003/06/24 12:30:52  brouard
                    581:   (Module): Some bugs corrected for windows. Also, when
                    582:   mle=-1 a template is output in file "or"mypar.txt with the design
                    583:   of the covariance matrix to be input.
                    584: 
                    585:   Revision 1.88  2003/06/23 17:54:56  brouard
                    586:   * 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.
                    587: 
                    588:   Revision 1.87  2003/06/18 12:26:01  brouard
                    589:   Version 0.96
                    590: 
                    591:   Revision 1.86  2003/06/17 20:04:08  brouard
                    592:   (Module): Change position of html and gnuplot routines and added
                    593:   routine fileappend.
                    594: 
                    595:   Revision 1.85  2003/06/17 13:12:43  brouard
                    596:   * imach.c (Repository): Check when date of death was earlier that
                    597:   current date of interview. It may happen when the death was just
                    598:   prior to the death. In this case, dh was negative and likelihood
                    599:   was wrong (infinity). We still send an "Error" but patch by
                    600:   assuming that the date of death was just one stepm after the
                    601:   interview.
                    602:   (Repository): Because some people have very long ID (first column)
                    603:   we changed int to long in num[] and we added a new lvector for
                    604:   memory allocation. But we also truncated to 8 characters (left
                    605:   truncation)
                    606:   (Repository): No more line truncation errors.
                    607: 
                    608:   Revision 1.84  2003/06/13 21:44:43  brouard
                    609:   * imach.c (Repository): Replace "freqsummary" at a correct
                    610:   place. It differs from routine "prevalence" which may be called
                    611:   many times. Probs is memory consuming and must be used with
                    612:   parcimony.
                    613:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    614: 
                    615:   Revision 1.83  2003/06/10 13:39:11  lievre
                    616:   *** empty log message ***
                    617: 
                    618:   Revision 1.82  2003/06/05 15:57:20  brouard
                    619:   Add log in  imach.c and  fullversion number is now printed.
                    620: 
                    621: */
                    622: /*
                    623:    Interpolated Markov Chain
                    624: 
                    625:   Short summary of the programme:
                    626:   
                    627:   This program computes Healthy Life Expectancies from
                    628:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    629:   first survey ("cross") where individuals from different ages are
                    630:   interviewed on their health status or degree of disability (in the
                    631:   case of a health survey which is our main interest) -2- at least a
                    632:   second wave of interviews ("longitudinal") which measure each change
                    633:   (if any) in individual health status.  Health expectancies are
                    634:   computed from the time spent in each health state according to a
                    635:   model. More health states you consider, more time is necessary to reach the
                    636:   Maximum Likelihood of the parameters involved in the model.  The
                    637:   simplest model is the multinomial logistic model where pij is the
                    638:   probability to be observed in state j at the second wave
                    639:   conditional to be observed in state i at the first wave. Therefore
                    640:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    641:   'age' is age and 'sex' is a covariate. If you want to have a more
                    642:   complex model than "constant and age", you should modify the program
                    643:   where the markup *Covariates have to be included here again* invites
                    644:   you to do it.  More covariates you add, slower the
                    645:   convergence.
                    646: 
                    647:   The advantage of this computer programme, compared to a simple
                    648:   multinomial logistic model, is clear when the delay between waves is not
                    649:   identical for each individual. Also, if a individual missed an
                    650:   intermediate interview, the information is lost, but taken into
                    651:   account using an interpolation or extrapolation.  
                    652: 
                    653:   hPijx is the probability to be observed in state i at age x+h
                    654:   conditional to the observed state i at age x. The delay 'h' can be
                    655:   split into an exact number (nh*stepm) of unobserved intermediate
                    656:   states. This elementary transition (by month, quarter,
                    657:   semester or year) is modelled as a multinomial logistic.  The hPx
                    658:   matrix is simply the matrix product of nh*stepm elementary matrices
                    659:   and the contribution of each individual to the likelihood is simply
                    660:   hPijx.
                    661: 
                    662:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   663:   of the life expectancies. It also computes the period (stable) prevalence.
                    664: 
                    665: Back prevalence and projections:
                    666:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj)
                    667:     Computes the back prevalence limit  for any combination    of covariate values k
                    668:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    669:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    670:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    671:    Computes for any combination of covariates k and any age between bage and fage 
                    672:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    673:                        oldm=oldms;savm=savms;
                    674:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    675:      Computes the transition matrix starting at age 'age' over
                    676:      'nhstepm*hstepm*stepm' months (i.e. until
                    677:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    678:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    679:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    680:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    681: 
1.133     brouard   682:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    683:            Institut national d'études démographiques, Paris.
1.126     brouard   684:   This software have been partly granted by Euro-REVES, a concerted action
                    685:   from the European Union.
                    686:   It is copyrighted identically to a GNU software product, ie programme and
                    687:   software can be distributed freely for non commercial use. Latest version
                    688:   can be accessed at http://euroreves.ined.fr/imach .
                    689: 
                    690:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    691:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    692:   
                    693:   **********************************************************************/
                    694: /*
                    695:   main
                    696:   read parameterfile
                    697:   read datafile
                    698:   concatwav
                    699:   freqsummary
                    700:   if (mle >= 1)
                    701:     mlikeli
                    702:   print results files
                    703:   if mle==1 
                    704:      computes hessian
                    705:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    706:       begin-prev-date,...
                    707:   open gnuplot file
                    708:   open html file
1.145     brouard   709:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    710:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    711:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    712:     freexexit2 possible for memory heap.
                    713: 
                    714:   h Pij x                         | pij_nom  ficrestpij
                    715:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    716:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    717:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    718: 
                    719:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    720:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    721:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    722:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    723:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    724: 
1.126     brouard   725:   forecasting if prevfcast==1 prevforecast call prevalence()
                    726:   health expectancies
                    727:   Variance-covariance of DFLE
                    728:   prevalence()
                    729:    movingaverage()
                    730:   varevsij() 
                    731:   if popbased==1 varevsij(,popbased)
                    732:   total life expectancies
                    733:   Variance of period (stable) prevalence
                    734:  end
                    735: */
                    736: 
1.187     brouard   737: /* #define DEBUG */
                    738: /* #define DEBUGBRENT */
1.203     brouard   739: /* #define DEBUGLINMIN */
                    740: /* #define DEBUGHESS */
                    741: #define DEBUGHESSIJ
1.220     brouard   742: #define LINMINORIGINAL  /* Don't use loop on scale in linmin (accepting nan)*/
1.165     brouard   743: #define POWELL /* Instead of NLOPT */
1.192     brouard   744: #define POWELLF1F3 /* Skip test */
1.186     brouard   745: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    746: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   747: 
                    748: #include <math.h>
                    749: #include <stdio.h>
                    750: #include <stdlib.h>
                    751: #include <string.h>
1.159     brouard   752: 
                    753: #ifdef _WIN32
                    754: #include <io.h>
1.172     brouard   755: #include <windows.h>
                    756: #include <tchar.h>
1.159     brouard   757: #else
1.126     brouard   758: #include <unistd.h>
1.159     brouard   759: #endif
1.126     brouard   760: 
                    761: #include <limits.h>
                    762: #include <sys/types.h>
1.171     brouard   763: 
                    764: #if defined(__GNUC__)
                    765: #include <sys/utsname.h> /* Doesn't work on Windows */
                    766: #endif
                    767: 
1.126     brouard   768: #include <sys/stat.h>
                    769: #include <errno.h>
1.159     brouard   770: /* extern int errno; */
1.126     brouard   771: 
1.157     brouard   772: /* #ifdef LINUX */
                    773: /* #include <time.h> */
                    774: /* #include "timeval.h" */
                    775: /* #else */
                    776: /* #include <sys/time.h> */
                    777: /* #endif */
                    778: 
1.126     brouard   779: #include <time.h>
                    780: 
1.136     brouard   781: #ifdef GSL
                    782: #include <gsl/gsl_errno.h>
                    783: #include <gsl/gsl_multimin.h>
                    784: #endif
                    785: 
1.167     brouard   786: 
1.162     brouard   787: #ifdef NLOPT
                    788: #include <nlopt.h>
                    789: typedef struct {
                    790:   double (* function)(double [] );
                    791: } myfunc_data ;
                    792: #endif
                    793: 
1.126     brouard   794: /* #include <libintl.h> */
                    795: /* #define _(String) gettext (String) */
                    796: 
1.141     brouard   797: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   798: 
                    799: #define GNUPLOTPROGRAM "gnuplot"
                    800: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    801: #define FILENAMELENGTH 132
                    802: 
                    803: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    804: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    805: 
1.144     brouard   806: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    807: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   808: 
                    809: #define NINTERVMAX 8
1.144     brouard   810: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    811: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    812: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   813: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   814: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    815: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   816: #define MAXN 20000
1.144     brouard   817: #define YEARM 12. /**< Number of months per year */
1.218     brouard   818: /* #define AGESUP 130 */
                    819: #define AGESUP 150
                    820: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   821: #define AGEBASE 40
1.194     brouard   822: #define AGEOVERFLOW 1.e20
1.164     brouard   823: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   824: #ifdef _WIN32
                    825: #define DIRSEPARATOR '\\'
                    826: #define CHARSEPARATOR "\\"
                    827: #define ODIRSEPARATOR '/'
                    828: #else
1.126     brouard   829: #define DIRSEPARATOR '/'
                    830: #define CHARSEPARATOR "/"
                    831: #define ODIRSEPARATOR '\\'
                    832: #endif
                    833: 
1.222   ! brouard   834: /* $Id: imach.c,v 1.221 2016/02/15 23:35:36 brouard Exp $ */
1.126     brouard   835: /* $State: Exp $ */
1.196     brouard   836: #include "version.h"
                    837: char version[]=__IMACH_VERSION__;
1.204     brouard   838: 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.222   ! brouard   839: char fullversion[]="$Revision: 1.221 $ $Date: 2016/02/15 23:35:36 $"; 
1.126     brouard   840: char strstart[80];
                    841: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   842: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   843: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   844: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    845: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    846: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    847: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    848: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    849: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    850: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    851: int cptcov=0; /* Working variable */
1.218     brouard   852: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   853: int npar=NPARMAX;
                    854: int nlstate=2; /* Number of live states */
                    855: int ndeath=1; /* Number of dead states */
1.130     brouard   856: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   857: int popbased=0;
                    858: 
                    859: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   860: int maxwav=0; /* Maxim number of waves */
                    861: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    862: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    863: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   864:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   865: int mle=1, weightopt=0;
1.126     brouard   866: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    867: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    868: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    869:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   870: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   871: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   872: double **matprod2(); /* test */
1.126     brouard   873: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    874: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   875: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    876: 
1.136     brouard   877: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   878: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   879: FILE *ficlog, *ficrespow;
1.130     brouard   880: int globpr=0; /* Global variable for printing or not */
1.126     brouard   881: double fretone; /* Only one call to likelihood */
1.130     brouard   882: long ipmx=0; /* Number of contributions */
1.126     brouard   883: double sw; /* Sum of weights */
                    884: char filerespow[FILENAMELENGTH];
                    885: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    886: FILE *ficresilk;
                    887: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    888: FILE *ficresprobmorprev;
                    889: FILE *fichtm, *fichtmcov; /* Html File */
                    890: FILE *ficreseij;
                    891: char filerese[FILENAMELENGTH];
                    892: FILE *ficresstdeij;
                    893: char fileresstde[FILENAMELENGTH];
                    894: FILE *ficrescveij;
                    895: char filerescve[FILENAMELENGTH];
                    896: FILE  *ficresvij;
                    897: char fileresv[FILENAMELENGTH];
                    898: FILE  *ficresvpl;
                    899: char fileresvpl[FILENAMELENGTH];
                    900: char title[MAXLINE];
1.217     brouard   901: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   902: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    903: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    904: char command[FILENAMELENGTH];
                    905: int  outcmd=0;
                    906: 
1.217     brouard   907: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   908: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   909: char filelog[FILENAMELENGTH]; /* Log file */
                    910: char filerest[FILENAMELENGTH];
                    911: char fileregp[FILENAMELENGTH];
                    912: char popfile[FILENAMELENGTH];
                    913: 
                    914: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    915: 
1.157     brouard   916: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    917: /* struct timezone tzp; */
                    918: /* extern int gettimeofday(); */
                    919: struct tm tml, *gmtime(), *localtime();
                    920: 
                    921: extern time_t time();
                    922: 
                    923: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    924: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    925: struct tm tm;
                    926: 
1.126     brouard   927: char strcurr[80], strfor[80];
                    928: 
                    929: char *endptr;
                    930: long lval;
                    931: double dval;
                    932: 
                    933: #define NR_END 1
                    934: #define FREE_ARG char*
                    935: #define FTOL 1.0e-10
                    936: 
                    937: #define NRANSI 
                    938: #define ITMAX 200 
                    939: 
                    940: #define TOL 2.0e-4 
                    941: 
                    942: #define CGOLD 0.3819660 
                    943: #define ZEPS 1.0e-10 
                    944: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    945: 
                    946: #define GOLD 1.618034 
                    947: #define GLIMIT 100.0 
                    948: #define TINY 1.0e-20 
                    949: 
                    950: static double maxarg1,maxarg2;
                    951: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    952: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    953:   
                    954: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    955: #define rint(a) floor(a+0.5)
1.166     brouard   956: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   957: #define mytinydouble 1.0e-16
1.166     brouard   958: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    959: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    960: /* static double dsqrarg; */
                    961: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   962: static double sqrarg;
                    963: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    964: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    965: int agegomp= AGEGOMP;
                    966: 
                    967: int imx; 
                    968: int stepm=1;
                    969: /* Stepm, step in month: minimum step interpolation*/
                    970: 
                    971: int estepm;
                    972: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    973: 
                    974: int m,nb;
                    975: long *num;
1.197     brouard   976: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   977: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    978:                   covariate for which somebody answered excluding 
                    979:                   undefined. Usually 2: 0 and 1. */
                    980: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    981:                             covariate for which somebody answered including 
                    982:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   983: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard   984: double **pmmij, ***probs; /* Global pointer */
1.219     brouard   985: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard   986: double *ageexmed,*agecens;
                    987: double dateintmean=0;
                    988: 
                    989: double *weight;
                    990: int **s; /* Status */
1.141     brouard   991: double *agedc;
1.145     brouard   992: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   993:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   994:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   995: double  idx; 
                    996: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   997: int *Tage;
1.145     brouard   998: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   999: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.220     brouard  1000: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1001: double *lsurv, *lpop, *tpop;
                   1002: 
1.143     brouard  1003: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1004: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1005: 
                   1006: /**************** split *************************/
                   1007: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1008: {
                   1009:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1010:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1011:   */ 
                   1012:   char *ss;                            /* pointer */
1.186     brouard  1013:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1014: 
                   1015:   l1 = strlen(path );                  /* length of path */
                   1016:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1017:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1018:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1019:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1020:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1021:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1022:     /* get current working directory */
                   1023:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1024: #ifdef WIN32
                   1025:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1026: #else
                   1027:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1028: #endif
1.126     brouard  1029:       return( GLOCK_ERROR_GETCWD );
                   1030:     }
                   1031:     /* got dirc from getcwd*/
                   1032:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1033:   } else {                             /* strip directory from path */
1.126     brouard  1034:     ss++;                              /* after this, the filename */
                   1035:     l2 = strlen( ss );                 /* length of filename */
                   1036:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1037:     strcpy( name, ss );                /* save file name */
                   1038:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1039:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1040:     printf(" DIRC2 = %s \n",dirc);
                   1041:   }
                   1042:   /* We add a separator at the end of dirc if not exists */
                   1043:   l1 = strlen( dirc );                 /* length of directory */
                   1044:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1045:     dirc[l1] =  DIRSEPARATOR;
                   1046:     dirc[l1+1] = 0; 
                   1047:     printf(" DIRC3 = %s \n",dirc);
                   1048:   }
                   1049:   ss = strrchr( name, '.' );           /* find last / */
                   1050:   if (ss >0){
                   1051:     ss++;
                   1052:     strcpy(ext,ss);                    /* save extension */
                   1053:     l1= strlen( name);
                   1054:     l2= strlen(ss)+1;
                   1055:     strncpy( finame, name, l1-l2);
                   1056:     finame[l1-l2]= 0;
                   1057:   }
                   1058: 
                   1059:   return( 0 );                         /* we're done */
                   1060: }
                   1061: 
                   1062: 
                   1063: /******************************************/
                   1064: 
                   1065: void replace_back_to_slash(char *s, char*t)
                   1066: {
                   1067:   int i;
                   1068:   int lg=0;
                   1069:   i=0;
                   1070:   lg=strlen(t);
                   1071:   for(i=0; i<= lg; i++) {
                   1072:     (s[i] = t[i]);
                   1073:     if (t[i]== '\\') s[i]='/';
                   1074:   }
                   1075: }
                   1076: 
1.132     brouard  1077: char *trimbb(char *out, char *in)
1.137     brouard  1078: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1079:   char *s;
                   1080:   s=out;
                   1081:   while (*in != '\0'){
1.137     brouard  1082:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1083:       in++;
                   1084:     }
                   1085:     *out++ = *in++;
                   1086:   }
                   1087:   *out='\0';
                   1088:   return s;
                   1089: }
                   1090: 
1.187     brouard  1091: /* char *substrchaine(char *out, char *in, char *chain) */
                   1092: /* { */
                   1093: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1094: /*   char *s, *t; */
                   1095: /*   t=in;s=out; */
                   1096: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1097: /*     *out++ = *in++; */
                   1098: /*   } */
                   1099: 
                   1100: /*   /\* *in matches *chain *\/ */
                   1101: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1102: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1103: /*   } */
                   1104: /*   in--; chain--; */
                   1105: /*   while ( (*in != '\0')){ */
                   1106: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1107: /*     *out++ = *in++; */
                   1108: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1109: /*   } */
                   1110: /*   *out='\0'; */
                   1111: /*   out=s; */
                   1112: /*   return out; */
                   1113: /* } */
                   1114: char *substrchaine(char *out, char *in, char *chain)
                   1115: {
                   1116:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1117:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1118: 
                   1119:   char *strloc;
                   1120: 
                   1121:   strcpy (out, in); 
                   1122:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1123:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1124:   if(strloc != NULL){ 
                   1125:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1126:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1127:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1128:   }
                   1129:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1130:   return out;
                   1131: }
                   1132: 
                   1133: 
1.145     brouard  1134: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1135: {
1.187     brouard  1136:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1137:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1138:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1139:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1140:   */
1.160     brouard  1141:   char *s, *t;
1.145     brouard  1142:   t=in;s=in;
                   1143:   while ((*in != occ) && (*in != '\0')){
                   1144:     *alocc++ = *in++;
                   1145:   }
                   1146:   if( *in == occ){
                   1147:     *(alocc)='\0';
                   1148:     s=++in;
                   1149:   }
                   1150:  
                   1151:   if (s == t) {/* occ not found */
                   1152:     *(alocc-(in-s))='\0';
                   1153:     in=s;
                   1154:   }
                   1155:   while ( *in != '\0'){
                   1156:     *blocc++ = *in++;
                   1157:   }
                   1158: 
                   1159:   *blocc='\0';
                   1160:   return t;
                   1161: }
1.137     brouard  1162: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1163: {
1.187     brouard  1164:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1165:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1166:      gives blocc="abcdef2ghi" and alocc="j".
                   1167:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1168:   */
                   1169:   char *s, *t;
                   1170:   t=in;s=in;
                   1171:   while (*in != '\0'){
                   1172:     while( *in == occ){
                   1173:       *blocc++ = *in++;
                   1174:       s=in;
                   1175:     }
                   1176:     *blocc++ = *in++;
                   1177:   }
                   1178:   if (s == t) /* occ not found */
                   1179:     *(blocc-(in-s))='\0';
                   1180:   else
                   1181:     *(blocc-(in-s)-1)='\0';
                   1182:   in=s;
                   1183:   while ( *in != '\0'){
                   1184:     *alocc++ = *in++;
                   1185:   }
                   1186: 
                   1187:   *alocc='\0';
                   1188:   return s;
                   1189: }
                   1190: 
1.126     brouard  1191: int nbocc(char *s, char occ)
                   1192: {
                   1193:   int i,j=0;
                   1194:   int lg=20;
                   1195:   i=0;
                   1196:   lg=strlen(s);
                   1197:   for(i=0; i<= lg; i++) {
                   1198:   if  (s[i] == occ ) j++;
                   1199:   }
                   1200:   return j;
                   1201: }
                   1202: 
1.137     brouard  1203: /* void cutv(char *u,char *v, char*t, char occ) */
                   1204: /* { */
                   1205: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1206: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1207: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1208: /*   int i,lg,j,p=0; */
                   1209: /*   i=0; */
                   1210: /*   lg=strlen(t); */
                   1211: /*   for(j=0; j<=lg-1; j++) { */
                   1212: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1213: /*   } */
1.126     brouard  1214: 
1.137     brouard  1215: /*   for(j=0; j<p; j++) { */
                   1216: /*     (u[j] = t[j]); */
                   1217: /*   } */
                   1218: /*      u[p]='\0'; */
1.126     brouard  1219: 
1.137     brouard  1220: /*    for(j=0; j<= lg; j++) { */
                   1221: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1222: /*   } */
                   1223: /* } */
1.126     brouard  1224: 
1.160     brouard  1225: #ifdef _WIN32
                   1226: char * strsep(char **pp, const char *delim)
                   1227: {
                   1228:   char *p, *q;
                   1229:          
                   1230:   if ((p = *pp) == NULL)
                   1231:     return 0;
                   1232:   if ((q = strpbrk (p, delim)) != NULL)
                   1233:   {
                   1234:     *pp = q + 1;
                   1235:     *q = '\0';
                   1236:   }
                   1237:   else
                   1238:     *pp = 0;
                   1239:   return p;
                   1240: }
                   1241: #endif
                   1242: 
1.126     brouard  1243: /********************** nrerror ********************/
                   1244: 
                   1245: void nrerror(char error_text[])
                   1246: {
                   1247:   fprintf(stderr,"ERREUR ...\n");
                   1248:   fprintf(stderr,"%s\n",error_text);
                   1249:   exit(EXIT_FAILURE);
                   1250: }
                   1251: /*********************** vector *******************/
                   1252: double *vector(int nl, int nh)
                   1253: {
                   1254:   double *v;
                   1255:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1256:   if (!v) nrerror("allocation failure in vector");
                   1257:   return v-nl+NR_END;
                   1258: }
                   1259: 
                   1260: /************************ free vector ******************/
                   1261: void free_vector(double*v, int nl, int nh)
                   1262: {
                   1263:   free((FREE_ARG)(v+nl-NR_END));
                   1264: }
                   1265: 
                   1266: /************************ivector *******************************/
                   1267: int *ivector(long nl,long nh)
                   1268: {
                   1269:   int *v;
                   1270:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1271:   if (!v) nrerror("allocation failure in ivector");
                   1272:   return v-nl+NR_END;
                   1273: }
                   1274: 
                   1275: /******************free ivector **************************/
                   1276: void free_ivector(int *v, long nl, long nh)
                   1277: {
                   1278:   free((FREE_ARG)(v+nl-NR_END));
                   1279: }
                   1280: 
                   1281: /************************lvector *******************************/
                   1282: long *lvector(long nl,long nh)
                   1283: {
                   1284:   long *v;
                   1285:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1286:   if (!v) nrerror("allocation failure in ivector");
                   1287:   return v-nl+NR_END;
                   1288: }
                   1289: 
                   1290: /******************free lvector **************************/
                   1291: void free_lvector(long *v, long nl, long nh)
                   1292: {
                   1293:   free((FREE_ARG)(v+nl-NR_END));
                   1294: }
                   1295: 
                   1296: /******************* imatrix *******************************/
                   1297: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1298:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1299: { 
                   1300:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1301:   int **m; 
                   1302:   
                   1303:   /* allocate pointers to rows */ 
                   1304:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1305:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1306:   m += NR_END; 
                   1307:   m -= nrl; 
                   1308:   
                   1309:   
                   1310:   /* allocate rows and set pointers to them */ 
                   1311:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1312:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1313:   m[nrl] += NR_END; 
                   1314:   m[nrl] -= ncl; 
                   1315:   
                   1316:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1317:   
                   1318:   /* return pointer to array of pointers to rows */ 
                   1319:   return m; 
                   1320: } 
                   1321: 
                   1322: /****************** free_imatrix *************************/
                   1323: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1324:       int **m;
                   1325:       long nch,ncl,nrh,nrl; 
                   1326:      /* free an int matrix allocated by imatrix() */ 
                   1327: { 
                   1328:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1329:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1330: } 
                   1331: 
                   1332: /******************* matrix *******************************/
                   1333: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1334: {
                   1335:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1336:   double **m;
                   1337: 
                   1338:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1339:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1340:   m += NR_END;
                   1341:   m -= nrl;
                   1342: 
                   1343:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1344:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1345:   m[nrl] += NR_END;
                   1346:   m[nrl] -= ncl;
                   1347: 
                   1348:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1349:   return m;
1.145     brouard  1350:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1351: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1352: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1353:    */
                   1354: }
                   1355: 
                   1356: /*************************free matrix ************************/
                   1357: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1358: {
                   1359:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1360:   free((FREE_ARG)(m+nrl-NR_END));
                   1361: }
                   1362: 
                   1363: /******************* ma3x *******************************/
                   1364: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1365: {
                   1366:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1367:   double ***m;
                   1368: 
                   1369:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1370:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1371:   m += NR_END;
                   1372:   m -= nrl;
                   1373: 
                   1374:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1375:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1376:   m[nrl] += NR_END;
                   1377:   m[nrl] -= ncl;
                   1378: 
                   1379:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1380: 
                   1381:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1382:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1383:   m[nrl][ncl] += NR_END;
                   1384:   m[nrl][ncl] -= nll;
                   1385:   for (j=ncl+1; j<=nch; j++) 
                   1386:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1387:   
                   1388:   for (i=nrl+1; i<=nrh; i++) {
                   1389:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1390:     for (j=ncl+1; j<=nch; j++) 
                   1391:       m[i][j]=m[i][j-1]+nlay;
                   1392:   }
                   1393:   return m; 
                   1394:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1395:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1396:   */
                   1397: }
                   1398: 
                   1399: /*************************free ma3x ************************/
                   1400: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1401: {
                   1402:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1403:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1404:   free((FREE_ARG)(m+nrl-NR_END));
                   1405: }
                   1406: 
                   1407: /*************** function subdirf ***********/
                   1408: char *subdirf(char fileres[])
                   1409: {
                   1410:   /* Caution optionfilefiname is hidden */
                   1411:   strcpy(tmpout,optionfilefiname);
                   1412:   strcat(tmpout,"/"); /* Add to the right */
                   1413:   strcat(tmpout,fileres);
                   1414:   return tmpout;
                   1415: }
                   1416: 
                   1417: /*************** function subdirf2 ***********/
                   1418: char *subdirf2(char fileres[], char *preop)
                   1419: {
                   1420:   
                   1421:   /* Caution optionfilefiname is hidden */
                   1422:   strcpy(tmpout,optionfilefiname);
                   1423:   strcat(tmpout,"/");
                   1424:   strcat(tmpout,preop);
                   1425:   strcat(tmpout,fileres);
                   1426:   return tmpout;
                   1427: }
                   1428: 
                   1429: /*************** function subdirf3 ***********/
                   1430: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1431: {
                   1432:   
                   1433:   /* Caution optionfilefiname is hidden */
                   1434:   strcpy(tmpout,optionfilefiname);
                   1435:   strcat(tmpout,"/");
                   1436:   strcat(tmpout,preop);
                   1437:   strcat(tmpout,preop2);
                   1438:   strcat(tmpout,fileres);
                   1439:   return tmpout;
                   1440: }
1.213     brouard  1441:  
                   1442: /*************** function subdirfext ***********/
                   1443: char *subdirfext(char fileres[], char *preop, char *postop)
                   1444: {
                   1445:   
                   1446:   strcpy(tmpout,preop);
                   1447:   strcat(tmpout,fileres);
                   1448:   strcat(tmpout,postop);
                   1449:   return tmpout;
                   1450: }
1.126     brouard  1451: 
1.213     brouard  1452: /*************** function subdirfext3 ***********/
                   1453: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1454: {
                   1455:   
                   1456:   /* Caution optionfilefiname is hidden */
                   1457:   strcpy(tmpout,optionfilefiname);
                   1458:   strcat(tmpout,"/");
                   1459:   strcat(tmpout,preop);
                   1460:   strcat(tmpout,fileres);
                   1461:   strcat(tmpout,postop);
                   1462:   return tmpout;
                   1463: }
                   1464:  
1.162     brouard  1465: char *asc_diff_time(long time_sec, char ascdiff[])
                   1466: {
                   1467:   long sec_left, days, hours, minutes;
                   1468:   days = (time_sec) / (60*60*24);
                   1469:   sec_left = (time_sec) % (60*60*24);
                   1470:   hours = (sec_left) / (60*60) ;
                   1471:   sec_left = (sec_left) %(60*60);
                   1472:   minutes = (sec_left) /60;
                   1473:   sec_left = (sec_left) % (60);
                   1474:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1475:   return ascdiff;
                   1476: }
                   1477: 
1.126     brouard  1478: /***************** f1dim *************************/
                   1479: extern int ncom; 
                   1480: extern double *pcom,*xicom;
                   1481: extern double (*nrfunc)(double []); 
                   1482:  
                   1483: double f1dim(double x) 
                   1484: { 
                   1485:   int j; 
                   1486:   double f;
                   1487:   double *xt; 
                   1488:  
                   1489:   xt=vector(1,ncom); 
                   1490:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1491:   f=(*nrfunc)(xt); 
                   1492:   free_vector(xt,1,ncom); 
                   1493:   return f; 
                   1494: } 
                   1495: 
                   1496: /*****************brent *************************/
                   1497: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1498: {
                   1499:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1500:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1501:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1502:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1503:    * returned function value. 
                   1504:   */
1.126     brouard  1505:   int iter; 
                   1506:   double a,b,d,etemp;
1.159     brouard  1507:   double fu=0,fv,fw,fx;
1.164     brouard  1508:   double ftemp=0.;
1.126     brouard  1509:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1510:   double e=0.0; 
                   1511:  
                   1512:   a=(ax < cx ? ax : cx); 
                   1513:   b=(ax > cx ? ax : cx); 
                   1514:   x=w=v=bx; 
                   1515:   fw=fv=fx=(*f)(x); 
                   1516:   for (iter=1;iter<=ITMAX;iter++) { 
                   1517:     xm=0.5*(a+b); 
                   1518:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1519:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1520:     printf(".");fflush(stdout);
                   1521:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1522: #ifdef DEBUGBRENT
1.126     brouard  1523:     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);
                   1524:     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);
                   1525:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1526: #endif
                   1527:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1528:       *xmin=x; 
                   1529:       return fx; 
                   1530:     } 
                   1531:     ftemp=fu;
                   1532:     if (fabs(e) > tol1) { 
                   1533:       r=(x-w)*(fx-fv); 
                   1534:       q=(x-v)*(fx-fw); 
                   1535:       p=(x-v)*q-(x-w)*r; 
                   1536:       q=2.0*(q-r); 
                   1537:       if (q > 0.0) p = -p; 
                   1538:       q=fabs(q); 
                   1539:       etemp=e; 
                   1540:       e=d; 
                   1541:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1542:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1543:       else { 
                   1544:        d=p/q; 
                   1545:        u=x+d; 
                   1546:        if (u-a < tol2 || b-u < tol2) 
                   1547:          d=SIGN(tol1,xm-x); 
                   1548:       } 
                   1549:     } else { 
                   1550:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1551:     } 
                   1552:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1553:     fu=(*f)(u); 
                   1554:     if (fu <= fx) { 
                   1555:       if (u >= x) a=x; else b=x; 
                   1556:       SHFT(v,w,x,u) 
1.183     brouard  1557:       SHFT(fv,fw,fx,fu) 
                   1558:     } else { 
                   1559:       if (u < x) a=u; else b=u; 
                   1560:       if (fu <= fw || w == x) { 
                   1561:        v=w; 
                   1562:        w=u; 
                   1563:        fv=fw; 
                   1564:        fw=fu; 
                   1565:       } else if (fu <= fv || v == x || v == w) { 
                   1566:        v=u; 
                   1567:        fv=fu; 
                   1568:       } 
                   1569:     } 
1.126     brouard  1570:   } 
                   1571:   nrerror("Too many iterations in brent"); 
                   1572:   *xmin=x; 
                   1573:   return fx; 
                   1574: } 
                   1575: 
                   1576: /****************** mnbrak ***********************/
                   1577: 
                   1578: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1579:            double (*func)(double)) 
1.183     brouard  1580: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1581: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1582: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1583: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1584:    */
1.126     brouard  1585:   double ulim,u,r,q, dum;
                   1586:   double fu; 
1.187     brouard  1587: 
                   1588:   double scale=10.;
                   1589:   int iterscale=0;
                   1590: 
                   1591:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1592:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1593: 
                   1594: 
                   1595:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1596:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1597:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1598:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1599:   /* } */
                   1600: 
1.126     brouard  1601:   if (*fb > *fa) { 
                   1602:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1603:     SHFT(dum,*fb,*fa,dum) 
                   1604:   } 
1.126     brouard  1605:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1606:   *fc=(*func)(*cx); 
1.183     brouard  1607: #ifdef DEBUG
                   1608:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1609:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1610: #endif
                   1611:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1612:     r=(*bx-*ax)*(*fb-*fc); 
                   1613:     q=(*bx-*cx)*(*fb-*fa); 
                   1614:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1615:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1616:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1617:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1618:       fu=(*func)(u); 
1.163     brouard  1619: #ifdef DEBUG
                   1620:       /* f(x)=A(x-u)**2+f(u) */
                   1621:       double A, fparabu; 
                   1622:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1623:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1624:       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);
                   1625:       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  1626:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1627:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1628:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1629:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1630: #endif 
1.184     brouard  1631: #ifdef MNBRAKORIGINAL
1.183     brouard  1632: #else
1.191     brouard  1633: /*       if (fu > *fc) { */
                   1634: /* #ifdef DEBUG */
                   1635: /*       printf("mnbrak4  fu > fc \n"); */
                   1636: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1637: /* #endif */
                   1638: /*     /\* 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 *\\/  *\/ */
                   1639: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1640: /*     dum=u; /\* Shifting c and u *\/ */
                   1641: /*     u = *cx; */
                   1642: /*     *cx = dum; */
                   1643: /*     dum = fu; */
                   1644: /*     fu = *fc; */
                   1645: /*     *fc =dum; */
                   1646: /*       } else { /\* end *\/ */
                   1647: /* #ifdef DEBUG */
                   1648: /*       printf("mnbrak3  fu < fc \n"); */
                   1649: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1650: /* #endif */
                   1651: /*     dum=u; /\* Shifting c and u *\/ */
                   1652: /*     u = *cx; */
                   1653: /*     *cx = dum; */
                   1654: /*     dum = fu; */
                   1655: /*     fu = *fc; */
                   1656: /*     *fc =dum; */
                   1657: /*       } */
1.183     brouard  1658: #ifdef DEBUG
1.191     brouard  1659:       printf("mnbrak34  fu < or >= fc \n");
                   1660:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1661: #endif
1.191     brouard  1662:       dum=u; /* Shifting c and u */
                   1663:       u = *cx;
                   1664:       *cx = dum;
                   1665:       dum = fu;
                   1666:       fu = *fc;
                   1667:       *fc =dum;
1.183     brouard  1668: #endif
1.162     brouard  1669:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1670: #ifdef DEBUG
                   1671:       printf("mnbrak2  u after c but before ulim\n");
                   1672:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1673: #endif
1.126     brouard  1674:       fu=(*func)(u); 
                   1675:       if (fu < *fc) { 
1.183     brouard  1676: #ifdef DEBUG
                   1677:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1678:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1679: #endif
1.126     brouard  1680:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1681:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1682:       } 
1.162     brouard  1683:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1684: #ifdef DEBUG
                   1685:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1686:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1687: #endif
1.126     brouard  1688:       u=ulim; 
                   1689:       fu=(*func)(u); 
1.183     brouard  1690:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1691: #ifdef DEBUG
                   1692:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1693:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1694: #endif
1.126     brouard  1695:       u=(*cx)+GOLD*(*cx-*bx); 
                   1696:       fu=(*func)(u); 
1.183     brouard  1697:     } /* end tests */
1.126     brouard  1698:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1699:     SHFT(*fa,*fb,*fc,fu) 
                   1700: #ifdef DEBUG
                   1701:       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);
                   1702:       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);
                   1703: #endif
                   1704:   } /* 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  1705: } 
                   1706: 
                   1707: /*************** linmin ************************/
1.162     brouard  1708: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1709: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1710: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1711: the value of func at the returned location p . This is actually all accomplished by calling the
                   1712: routines mnbrak and brent .*/
1.126     brouard  1713: int ncom; 
                   1714: double *pcom,*xicom;
                   1715: double (*nrfunc)(double []); 
                   1716:  
                   1717: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1718: { 
                   1719:   double brent(double ax, double bx, double cx, 
                   1720:               double (*f)(double), double tol, double *xmin); 
                   1721:   double f1dim(double x); 
                   1722:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1723:              double *fc, double (*func)(double)); 
                   1724:   int j; 
                   1725:   double xx,xmin,bx,ax; 
                   1726:   double fx,fb,fa;
1.187     brouard  1727: 
1.203     brouard  1728: #ifdef LINMINORIGINAL
                   1729: #else
                   1730:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1731: #endif
                   1732:   
1.126     brouard  1733:   ncom=n; 
                   1734:   pcom=vector(1,n); 
                   1735:   xicom=vector(1,n); 
                   1736:   nrfunc=func; 
                   1737:   for (j=1;j<=n;j++) { 
                   1738:     pcom[j]=p[j]; 
1.202     brouard  1739:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1740:   } 
1.187     brouard  1741: 
1.203     brouard  1742: #ifdef LINMINORIGINAL
                   1743:   xx=1.;
                   1744: #else
                   1745:   axs=0.0;
                   1746:   xxs=1.;
                   1747:   do{
                   1748:     xx= xxs;
                   1749: #endif
1.187     brouard  1750:     ax=0.;
                   1751:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1752:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1753:     /* 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))   */
                   1754:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1755:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1756:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1757:     /* 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  1758: #ifdef LINMINORIGINAL
                   1759: #else
                   1760:     if (fx != fx){
                   1761:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1762:        printf("|");
                   1763:        fprintf(ficlog,"|");
                   1764: #ifdef DEBUGLINMIN
                   1765:        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);
                   1766: #endif
                   1767:     }
                   1768:   }while(fx != fx);
                   1769: #endif
                   1770:   
1.191     brouard  1771: #ifdef DEBUGLINMIN
                   1772:   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  1773:   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  1774: #endif
1.187     brouard  1775:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1776:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1777:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1778:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1779:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1780: #ifdef DEBUG
                   1781:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1782:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1783: #endif
1.191     brouard  1784: #ifdef DEBUGLINMIN
                   1785:   printf("linmin end ");
1.202     brouard  1786:   fprintf(ficlog,"linmin end ");
1.191     brouard  1787: #endif
1.126     brouard  1788:   for (j=1;j<=n;j++) { 
1.203     brouard  1789: #ifdef LINMINORIGINAL
                   1790:     xi[j] *= xmin; 
                   1791: #else
                   1792: #ifdef DEBUGLINMIN
                   1793:     if(xxs <1.0)
                   1794:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1795: #endif
                   1796:     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) */
                   1797: #ifdef DEBUGLINMIN
                   1798:     if(xxs <1.0)
                   1799:       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 );
                   1800: #endif
                   1801: #endif
1.187     brouard  1802:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1803:   } 
1.191     brouard  1804: #ifdef DEBUGLINMIN
1.203     brouard  1805:   printf("\n");
1.191     brouard  1806:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1807:   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  1808:   for (j=1;j<=n;j++) { 
1.202     brouard  1809:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1810:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1811:     if(j % ncovmodel == 0){
1.191     brouard  1812:       printf("\n");
1.202     brouard  1813:       fprintf(ficlog,"\n");
                   1814:     }
1.191     brouard  1815:   }
1.203     brouard  1816: #else
1.191     brouard  1817: #endif
1.126     brouard  1818:   free_vector(xicom,1,n); 
                   1819:   free_vector(pcom,1,n); 
                   1820: } 
                   1821: 
                   1822: 
                   1823: /*************** powell ************************/
1.162     brouard  1824: /*
                   1825: Minimization of a function func of n variables. Input consists of an initial starting point
                   1826: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1827: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1828: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1829: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1830: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1831:  */
1.126     brouard  1832: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1833:            double (*func)(double [])) 
                   1834: { 
                   1835:   void linmin(double p[], double xi[], int n, double *fret, 
                   1836:              double (*func)(double [])); 
                   1837:   int i,ibig,j; 
                   1838:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1839:   double directest;
1.126     brouard  1840:   double fp,fptt;
                   1841:   double *xits;
                   1842:   int niterf, itmp;
                   1843: 
                   1844:   pt=vector(1,n); 
                   1845:   ptt=vector(1,n); 
                   1846:   xit=vector(1,n); 
                   1847:   xits=vector(1,n); 
                   1848:   *fret=(*func)(p); 
                   1849:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1850:   rcurr_time = time(NULL);  
1.126     brouard  1851:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1852:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1853:     ibig=0; 
                   1854:     del=0.0; 
1.157     brouard  1855:     rlast_time=rcurr_time;
                   1856:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1857:     rcurr_time = time(NULL);  
                   1858:     curr_time = *localtime(&rcurr_time);
                   1859:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1860:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1861: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1862:     for (i=1;i<=n;i++) {
1.126     brouard  1863:       printf(" %d %.12f",i, p[i]);
                   1864:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1865:       fprintf(ficrespow," %.12lf", p[i]);
                   1866:     }
                   1867:     printf("\n");
                   1868:     fprintf(ficlog,"\n");
                   1869:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1870:     if(*iter <=3){
1.157     brouard  1871:       tml = *localtime(&rcurr_time);
                   1872:       strcpy(strcurr,asctime(&tml));
                   1873:       rforecast_time=rcurr_time; 
1.126     brouard  1874:       itmp = strlen(strcurr);
                   1875:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1876:        strcurr[itmp-1]='\0';
1.162     brouard  1877:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1878:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1879:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1880:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1881:        forecast_time = *localtime(&rforecast_time);
                   1882:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1883:        itmp = strlen(strfor);
                   1884:        if(strfor[itmp-1]=='\n')
                   1885:        strfor[itmp-1]='\0';
1.157     brouard  1886:        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);
                   1887:        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  1888:       }
                   1889:     }
1.187     brouard  1890:     for (i=1;i<=n;i++) { /* For each direction i */
                   1891:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1892:       fptt=(*fret); 
                   1893: #ifdef DEBUG
1.203     brouard  1894:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1895:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1896: #endif
1.203     brouard  1897:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1898:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1899:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1900:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1901:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1902:        /* because that direction will be replaced unless the gain del is small */
                   1903:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1904:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1905:        /* with the new direction. */
1.126     brouard  1906:        del=fabs(fptt-(*fret)); 
                   1907:        ibig=i; 
                   1908:       } 
                   1909: #ifdef DEBUG
                   1910:       printf("%d %.12e",i,(*fret));
                   1911:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1912:       for (j=1;j<=n;j++) {
                   1913:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1914:        printf(" x(%d)=%.12e",j,xit[j]);
                   1915:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1916:       }
                   1917:       for(j=1;j<=n;j++) {
1.162     brouard  1918:        printf(" p(%d)=%.12e",j,p[j]);
                   1919:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1920:       }
                   1921:       printf("\n");
                   1922:       fprintf(ficlog,"\n");
                   1923: #endif
1.187     brouard  1924:     } /* end loop on each direction i */
                   1925:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1926:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1927:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1928:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1929:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1930:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1931:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1932:       /* decreased of more than 3.84  */
                   1933:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1934:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1935:       /* By adding 10 parameters more the gain should be 18.31 */
                   1936: 
                   1937:       /* Starting the program with initial values given by a former maximization will simply change */
                   1938:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1939:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1940:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1941: #ifdef DEBUG
                   1942:       int k[2],l;
                   1943:       k[0]=1;
                   1944:       k[1]=-1;
                   1945:       printf("Max: %.12e",(*func)(p));
                   1946:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1947:       for (j=1;j<=n;j++) {
                   1948:        printf(" %.12e",p[j]);
                   1949:        fprintf(ficlog," %.12e",p[j]);
                   1950:       }
                   1951:       printf("\n");
                   1952:       fprintf(ficlog,"\n");
                   1953:       for(l=0;l<=1;l++) {
                   1954:        for (j=1;j<=n;j++) {
                   1955:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1956:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1957:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1958:        }
                   1959:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1960:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1961:       }
                   1962: #endif
                   1963: 
                   1964: 
                   1965:       free_vector(xit,1,n); 
                   1966:       free_vector(xits,1,n); 
                   1967:       free_vector(ptt,1,n); 
                   1968:       free_vector(pt,1,n); 
                   1969:       return; 
1.192     brouard  1970:     } /* enough precision */ 
1.126     brouard  1971:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1972:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1973:       ptt[j]=2.0*p[j]-pt[j]; 
                   1974:       xit[j]=p[j]-pt[j]; 
                   1975:       pt[j]=p[j]; 
                   1976:     } 
1.181     brouard  1977:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1978: #ifdef POWELLF1F3
                   1979: #else
1.161     brouard  1980:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1981: #endif
1.162     brouard  1982:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1983:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1984:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1985:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1986:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1987:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1988:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1989: #ifdef NRCORIGINAL
                   1990:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1991: #else
                   1992:       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  1993:       t= t- del*SQR(fp-fptt);
1.183     brouard  1994: #endif
1.202     brouard  1995:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1996: #ifdef DEBUG
1.181     brouard  1997:       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);
                   1998:       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  1999:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2000:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2001:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2002:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2003:       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);
                   2004:       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);
                   2005: #endif
1.183     brouard  2006: #ifdef POWELLORIGINAL
                   2007:       if (t < 0.0) { /* Then we use it for new direction */
                   2008: #else
1.182     brouard  2009:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  2010:        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  2011:         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  2012:         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  2013:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2014:       } 
1.181     brouard  2015:       if (directest < 0.0) { /* Then we use it for new direction */
                   2016: #endif
1.191     brouard  2017: #ifdef DEBUGLINMIN
                   2018:        printf("Before linmin in direction P%d-P0\n",n);
                   2019:        for (j=1;j<=n;j++) { 
1.202     brouard  2020:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2021:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2022:          if(j % ncovmodel == 0){
1.191     brouard  2023:            printf("\n");
1.202     brouard  2024:            fprintf(ficlog,"\n");
                   2025:          }
1.191     brouard  2026:        }
                   2027: #endif
1.187     brouard  2028:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  2029: #ifdef DEBUGLINMIN
                   2030:        for (j=1;j<=n;j++) { 
                   2031:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  2032:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2033:          if(j % ncovmodel == 0){
1.191     brouard  2034:            printf("\n");
1.202     brouard  2035:            fprintf(ficlog,"\n");
                   2036:          }
1.191     brouard  2037:        }
                   2038: #endif
1.126     brouard  2039:        for (j=1;j<=n;j++) { 
1.181     brouard  2040:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2041:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  2042:        }
1.181     brouard  2043:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2044:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2045: 
1.126     brouard  2046: #ifdef DEBUG
1.164     brouard  2047:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2048:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2049:        for(j=1;j<=n;j++){
                   2050:          printf(" %.12e",xit[j]);
                   2051:          fprintf(ficlog," %.12e",xit[j]);
                   2052:        }
                   2053:        printf("\n");
                   2054:        fprintf(ficlog,"\n");
                   2055: #endif
1.192     brouard  2056:       } /* end of t or directest negative */
                   2057: #ifdef POWELLF1F3
                   2058: #else
1.162     brouard  2059:     } /* end if (fptt < fp)  */
1.192     brouard  2060: #endif
                   2061:   } /* loop iteration */ 
1.126     brouard  2062: } 
                   2063: 
                   2064: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2065: 
1.203     brouard  2066: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2067: {
1.218     brouard  2068:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2069:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2070:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2071:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2072:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2073:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2074:   /* Initial matrix pimij */
                   2075:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2076:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2077:   /*  0,                   0                  , 1} */
                   2078:   /*
                   2079:    * and after some iteration: */
                   2080:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2081:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2082:   /*  0,                   0                  , 1} */
                   2083:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2084:   /* {0.51571254859325999, 0.4842874514067399, */
                   2085:   /*  0.51326036147820708, 0.48673963852179264} */
                   2086:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2087: 
1.126     brouard  2088:   int i, ii,j,k;
1.209     brouard  2089:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2090:   /* double **matprod2(); */ /* test */
1.218     brouard  2091:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2092:   double **newm;
1.209     brouard  2093:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2094:   int ncvloop=0;
1.169     brouard  2095:   
1.209     brouard  2096:   min=vector(1,nlstate);
                   2097:   max=vector(1,nlstate);
                   2098:   meandiff=vector(1,nlstate);
                   2099: 
1.218     brouard  2100:        /* Starting with matrix unity */
1.126     brouard  2101:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2102:     for (j=1;j<=nlstate+ndeath;j++){
                   2103:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2104:     }
1.169     brouard  2105:   
                   2106:   cov[1]=1.;
                   2107:   
                   2108:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2109:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2110:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2111:     ncvloop++;
1.126     brouard  2112:     newm=savm;
                   2113:     /* Covariates have to be included here again */
1.138     brouard  2114:     cov[2]=agefin;
1.187     brouard  2115:     if(nagesqr==1)
                   2116:       cov[3]= agefin*agefin;;
1.138     brouard  2117:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2118:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2119:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2120:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2121:       /* 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  2122:     }
1.186     brouard  2123:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2124:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2125:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2126:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2127:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2128:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2129:     
                   2130:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2131:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2132:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2133:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2134:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2135:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2136:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2137:     
1.126     brouard  2138:     savm=oldm;
                   2139:     oldm=newm;
1.209     brouard  2140: 
                   2141:     for(j=1; j<=nlstate; j++){
                   2142:       max[j]=0.;
                   2143:       min[j]=1.;
                   2144:     }
                   2145:     for(i=1;i<=nlstate;i++){
                   2146:       sumnew=0;
                   2147:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2148:       for(j=1; j<=nlstate; j++){ 
                   2149:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2150:        max[j]=FMAX(max[j],prlim[i][j]);
                   2151:        min[j]=FMIN(min[j],prlim[i][j]);
                   2152:       }
                   2153:     }
                   2154: 
1.126     brouard  2155:     maxmax=0.;
1.209     brouard  2156:     for(j=1; j<=nlstate; j++){
                   2157:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2158:       maxmax=FMAX(maxmax,meandiff[j]);
                   2159:       /* 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  2160:     } /* j loop */
1.203     brouard  2161:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2162:     /* 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  2163:     if(maxmax < ftolpl){
1.209     brouard  2164:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2165:       free_vector(min,1,nlstate);
                   2166:       free_vector(max,1,nlstate);
                   2167:       free_vector(meandiff,1,nlstate);
1.126     brouard  2168:       return prlim;
                   2169:     }
1.169     brouard  2170:   } /* age loop */
1.208     brouard  2171:     /* After some age loop it doesn't converge */
1.209     brouard  2172:   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  2173: 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  2174:   /* 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); */
                   2175:   free_vector(min,1,nlstate);
                   2176:   free_vector(max,1,nlstate);
                   2177:   free_vector(meandiff,1,nlstate);
1.208     brouard  2178:   
1.169     brouard  2179:   return prlim; /* should not reach here */
1.126     brouard  2180: }
                   2181: 
1.217     brouard  2182: 
                   2183:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2184: 
1.218     brouard  2185:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2186:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2187:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2188: {
1.218     brouard  2189:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2190:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2191:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2192:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2193:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2194:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2195:   /* Initial matrix pimij */
                   2196:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2197:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2198:   /*  0,                   0                  , 1} */
                   2199:   /*
                   2200:    * and after some iteration: */
                   2201:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2202:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2203:   /*  0,                   0                  , 1} */
                   2204:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2205:   /* {0.51571254859325999, 0.4842874514067399, */
                   2206:   /*  0.51326036147820708, 0.48673963852179264} */
                   2207:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2208: 
                   2209:   int i, ii,j,k;
                   2210:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2211:   /* double **matprod2(); */ /* test */
                   2212:   double **out, cov[NCOVMAX+1], **bmij();
                   2213:   double **newm;
1.218     brouard  2214:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2215:   double        **oldm, **savm;  /* for use */
                   2216: 
1.217     brouard  2217:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2218:   int ncvloop=0;
                   2219:   
                   2220:   min=vector(1,nlstate);
                   2221:   max=vector(1,nlstate);
                   2222:   meandiff=vector(1,nlstate);
                   2223: 
1.218     brouard  2224:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2225:        oldm=oldms; savm=savms;
                   2226: 
                   2227:        /* Starting with matrix unity */
                   2228:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2229:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2230:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2231:     }
                   2232:   
                   2233:   cov[1]=1.;
                   2234:   
                   2235:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2236:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2237:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2238:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2239:     ncvloop++;
1.218     brouard  2240:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2241:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2242:     /* Covariates have to be included here again */
                   2243:     cov[2]=agefin;
                   2244:     if(nagesqr==1)
                   2245:       cov[3]= agefin*agefin;;
                   2246:     for (k=1; k<=cptcovn;k++) {
                   2247:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2248:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2249:       /* 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])]); */
                   2250:     }
                   2251:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2252:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2253:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2254:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2255:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2256:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2257:     
                   2258:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2259:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2260:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2261:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2262:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2263:                /* ij should be linked to the correct index of cov */
                   2264:                /* age and covariate values ij are in 'cov', but we need to pass
                   2265:                 * ij for the observed prevalence at age and status and covariate
                   2266:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2267:                 */
                   2268:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2269:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2270:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.217     brouard  2271:     savm=oldm;
                   2272:     oldm=newm;
                   2273:     for(j=1; j<=nlstate; j++){
                   2274:       max[j]=0.;
                   2275:       min[j]=1.;
                   2276:     }
                   2277:     for(j=1; j<=nlstate; j++){ 
                   2278:       for(i=1;i<=nlstate;i++){
1.218     brouard  2279:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2280:                                bprlim[i][j]= newm[i][j];
                   2281:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2282:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2283:       }
                   2284:     }
1.218     brouard  2285:                
1.217     brouard  2286:     maxmax=0.;
                   2287:     for(i=1; i<=nlstate; i++){
                   2288:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2289:       maxmax=FMAX(maxmax,meandiff[i]);
                   2290:       /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
                   2291:     } /* j loop */
                   2292:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2293:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2294:     if(maxmax < ftolpl){
1.220     brouard  2295:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2296:       free_vector(min,1,nlstate);
                   2297:       free_vector(max,1,nlstate);
                   2298:       free_vector(meandiff,1,nlstate);
                   2299:       return bprlim;
                   2300:     }
                   2301:   } /* age loop */
                   2302:     /* After some age loop it doesn't converge */
                   2303:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2304: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2305:   /* 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); */
                   2306:   free_vector(min,1,nlstate);
                   2307:   free_vector(max,1,nlstate);
                   2308:   free_vector(meandiff,1,nlstate);
                   2309:   
                   2310:   return bprlim; /* should not reach here */
                   2311: }
                   2312: 
1.126     brouard  2313: /*************** transition probabilities ***************/ 
                   2314: 
                   2315: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2316: {
1.138     brouard  2317:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2318:      computes the probability to be observed in state j being in state i by appying the
                   2319:      model to the ncovmodel covariates (including constant and age).
                   2320:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2321:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2322:      ncth covariate in the global vector x is given by the formula:
                   2323:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2324:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2325:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2326:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2327:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2328:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2329:   */
                   2330:   double s1, lnpijopii;
1.126     brouard  2331:   /*double t34;*/
1.164     brouard  2332:   int i,j, nc, ii, jj;
1.126     brouard  2333: 
1.218     brouard  2334:        for(i=1; i<= nlstate; i++){
                   2335:                for(j=1; j<i;j++){
                   2336:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2337:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2338:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2339:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2340:                        }
                   2341:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2342:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2343:                }
                   2344:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2345:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2346:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2347:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2348:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2349:                        }
                   2350:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2351:                }
                   2352:        }
                   2353:   
                   2354:        for(i=1; i<= nlstate; i++){
                   2355:                s1=0;
                   2356:                for(j=1; j<i; j++){
                   2357:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2358:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2359:                }
                   2360:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2361:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2362:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2363:                }
                   2364:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2365:                ps[i][i]=1./(s1+1.);
                   2366:                /* Computing other pijs */
                   2367:                for(j=1; j<i; j++)
                   2368:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2369:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2370:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2371:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2372:        } /* end i */
                   2373:   
                   2374:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2375:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2376:                        ps[ii][jj]=0;
                   2377:                        ps[ii][ii]=1;
                   2378:                }
                   2379:        }
                   2380:   
                   2381:   
                   2382:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2383:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2384:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2385:        /*   } */
                   2386:        /*   printf("\n "); */
                   2387:        /* } */
                   2388:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2389:        /*
                   2390:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2391:                goto end;*/
                   2392:        return ps;
1.126     brouard  2393: }
                   2394: 
1.218     brouard  2395: /*************** backward transition probabilities ***************/ 
                   2396: 
                   2397:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2398: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2399:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2400: {
1.222   ! brouard  2401:   /* Computes the backward probability at age agefin and covariate ij
        !          2402:    * and returns in **ps as well as **bmij.
        !          2403:    */
1.218     brouard  2404:   int i, ii, j,k;
1.222   ! brouard  2405:   
        !          2406:   double **out, **pmij();
        !          2407:   double sumnew=0.;
1.218     brouard  2408:   double agefin;
1.222   ! brouard  2409:   
        !          2410:   double **dnewm, **dsavm, **doldm;
        !          2411:   double **bbmij;
        !          2412:   
1.218     brouard  2413:   doldm=ddoldms; /* global pointers */
1.222   ! brouard  2414:   dnewm=ddnewms;
        !          2415:   dsavm=ddsavms;
        !          2416:   
        !          2417:   agefin=cov[2];
        !          2418:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
        !          2419:      the observed prevalence (with this covariate ij) */
        !          2420:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
        !          2421:   /* We do have the matrix Px in savm  and we need pij */
        !          2422:   for (j=1;j<=nlstate+ndeath;j++){
        !          2423:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
        !          2424:     for (ii=1;ii<=nlstate;ii++){
        !          2425:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
        !          2426:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
        !          2427:     for (ii=1;ii<=nlstate+ndeath;ii++){
        !          2428:       if(sumnew >= 1.e-10){
        !          2429:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
        !          2430:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
        !          2431:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
        !          2432:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
        !          2433:        /* }else */
        !          2434:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
        !          2435:       }else{
        !          2436:        printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
        !          2437:       }
        !          2438:     } /*End ii */
        !          2439:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
        !          2440:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
        !          2441:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
        !          2442:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
        !          2443:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
        !          2444:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
        !          2445:   /* left Product of this matrix by diag matrix of prevalences (savm) */
        !          2446:   for (j=1;j<=nlstate+ndeath;j++){
        !          2447:     for (ii=1;ii<=nlstate+ndeath;ii++){
        !          2448:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
        !          2449:     }
        !          2450:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
        !          2451:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
        !          2452:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
        !          2453:   /* end bmij */
        !          2454:   return ps; 
1.218     brouard  2455: }
1.217     brouard  2456: /*************** transition probabilities ***************/ 
                   2457: 
1.218     brouard  2458: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2459: {
                   2460:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2461:      computes the probability to be observed in state j being in state i by appying the
                   2462:      model to the ncovmodel covariates (including constant and age).
                   2463:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2464:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2465:      ncth covariate in the global vector x is given by the formula:
                   2466:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2467:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2468:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2469:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2470:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2471:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2472:   */
                   2473:   double s1, lnpijopii;
                   2474:   /*double t34;*/
                   2475:   int i,j, nc, ii, jj;
                   2476: 
1.218     brouard  2477:        for(i=1; i<= nlstate; i++){
                   2478:                for(j=1; j<i;j++){
                   2479:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2480:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2481:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2482:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2483:                        }
                   2484:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2485:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2486:                }
                   2487:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2488:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2489:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2490:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2491:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2492:                        }
                   2493:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2494:                }
                   2495:        }
                   2496:        
                   2497:        for(i=1; i<= nlstate; i++){
                   2498:                s1=0;
                   2499:                for(j=1; j<i; j++){
                   2500:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2501:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2502:                }
                   2503:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2504:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2505:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2506:                }
                   2507:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2508:                ps[i][i]=1./(s1+1.);
                   2509:                /* Computing other pijs */
                   2510:                for(j=1; j<i; j++)
                   2511:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2512:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2513:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2514:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2515:        } /* end i */
                   2516:        
                   2517:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2518:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2519:                        ps[ii][jj]=0;
                   2520:                        ps[ii][ii]=1;
                   2521:                }
                   2522:        }
                   2523:        /* Added for backcast */ /* Transposed matrix too */
                   2524:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2525:                s1=0.;
                   2526:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2527:                        s1+=ps[ii][jj];
                   2528:                }
                   2529:                for(ii=1; ii<= nlstate; ii++){
                   2530:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2531:                }
                   2532:        }
                   2533:        /* Transposition */
                   2534:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2535:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2536:                        s1=ps[ii][jj];
                   2537:                        ps[ii][jj]=ps[jj][ii];
                   2538:                        ps[jj][ii]=s1;
                   2539:                }
                   2540:        }
                   2541:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2542:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2543:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2544:        /*   } */
                   2545:        /*   printf("\n "); */
                   2546:        /* } */
                   2547:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2548:        /*
                   2549:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2550:                goto end;*/
                   2551:        return ps;
1.217     brouard  2552: }
                   2553: 
                   2554: 
1.126     brouard  2555: /**************** Product of 2 matrices ******************/
                   2556: 
1.145     brouard  2557: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2558: {
                   2559:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2560:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2561:   /* in, b, out are matrice of pointers which should have been initialized 
                   2562:      before: only the contents of out is modified. The function returns
                   2563:      a pointer to pointers identical to out */
1.145     brouard  2564:   int i, j, k;
1.126     brouard  2565:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2566:     for(k=ncolol; k<=ncoloh; k++){
                   2567:       out[i][k]=0.;
                   2568:       for(j=ncl; j<=nch; j++)
                   2569:        out[i][k] +=in[i][j]*b[j][k];
                   2570:     }
1.126     brouard  2571:   return out;
                   2572: }
                   2573: 
                   2574: 
                   2575: /************* Higher Matrix Product ***************/
                   2576: 
                   2577: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2578: {
1.218     brouard  2579:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2580:      'nhstepm*hstepm*stepm' months (i.e. until
                   2581:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2582:      nhstepm*hstepm matrices. 
                   2583:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2584:      (typically every 2 years instead of every month which is too big 
                   2585:      for the memory).
                   2586:      Model is determined by parameters x and covariates have to be 
                   2587:      included manually here. 
                   2588: 
                   2589:      */
                   2590: 
                   2591:   int i, j, d, h, k;
1.131     brouard  2592:   double **out, cov[NCOVMAX+1];
1.126     brouard  2593:   double **newm;
1.187     brouard  2594:   double agexact;
1.214     brouard  2595:   double agebegin, ageend;
1.126     brouard  2596: 
                   2597:   /* Hstepm could be zero and should return the unit matrix */
                   2598:   for (i=1;i<=nlstate+ndeath;i++)
                   2599:     for (j=1;j<=nlstate+ndeath;j++){
                   2600:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2601:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2602:     }
                   2603:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2604:   for(h=1; h <=nhstepm; h++){
                   2605:     for(d=1; d <=hstepm; d++){
                   2606:       newm=savm;
                   2607:       /* Covariates have to be included here again */
                   2608:       cov[1]=1.;
1.214     brouard  2609:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2610:       cov[2]=agexact;
                   2611:       if(nagesqr==1)
1.218     brouard  2612:                                cov[3]= agexact*agexact;
1.131     brouard  2613:       for (k=1; k<=cptcovn;k++) 
1.218     brouard  2614:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2615:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2616:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2617:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2618:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2619:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2620:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2621:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2622:                        /* 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  2623: 
                   2624: 
                   2625:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2626:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2627:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2628:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2629:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2630:       /* if((int)age == 70){ */
                   2631:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2632:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2633:       /*         printf("%d pmmij ",i); */
                   2634:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2635:       /*           printf("%f ",pmmij[i][j]); */
                   2636:       /*         } */
                   2637:       /*         printf(" oldm "); */
                   2638:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2639:       /*           printf("%f ",oldm[i][j]); */
                   2640:       /*         } */
                   2641:       /*         printf("\n"); */
                   2642:       /*       } */
                   2643:       /* } */
1.126     brouard  2644:       savm=oldm;
                   2645:       oldm=newm;
                   2646:     }
                   2647:     for(i=1; i<=nlstate+ndeath; i++)
                   2648:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2649:                                po[i][j][h]=newm[i][j];
                   2650:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2651:       }
1.128     brouard  2652:     /*printf("h=%d ",h);*/
1.126     brouard  2653:   } /* end h */
1.218     brouard  2654:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2655:   return po;
                   2656: }
                   2657: 
1.217     brouard  2658: /************* Higher Back Matrix Product ***************/
1.218     brouard  2659: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
1.222   ! brouard  2660: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2661: {
1.218     brouard  2662:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2663:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2664:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2665:      nhstepm*hstepm matrices.
                   2666:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2667:      (typically every 2 years instead of every month which is too big
1.217     brouard  2668:      for the memory).
1.218     brouard  2669:      Model is determined by parameters x and covariates have to be
                   2670:      included manually here.
1.217     brouard  2671: 
1.222   ! brouard  2672:   */
1.217     brouard  2673: 
                   2674:   int i, j, d, h, k;
                   2675:   double **out, cov[NCOVMAX+1];
                   2676:   double **newm;
                   2677:   double agexact;
                   2678:   double agebegin, ageend;
1.222   ! brouard  2679:   double **oldm, **savm;
1.217     brouard  2680: 
1.222   ! brouard  2681:   oldm=oldms;savm=savms;
1.217     brouard  2682:   /* Hstepm could be zero and should return the unit matrix */
                   2683:   for (i=1;i<=nlstate+ndeath;i++)
                   2684:     for (j=1;j<=nlstate+ndeath;j++){
                   2685:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2686:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2687:     }
                   2688:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2689:   for(h=1; h <=nhstepm; h++){
                   2690:     for(d=1; d <=hstepm; d++){
                   2691:       newm=savm;
                   2692:       /* Covariates have to be included here again */
                   2693:       cov[1]=1.;
                   2694:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2695:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2696:       cov[2]=agexact;
                   2697:       if(nagesqr==1)
1.222   ! brouard  2698:        cov[3]= agexact*agexact;
1.218     brouard  2699:       for (k=1; k<=cptcovn;k++)
1.222   ! brouard  2700:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
        !          2701:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2702:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222   ! brouard  2703:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          2704:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
        !          2705:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2706:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222   ! brouard  2707:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
        !          2708:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.218     brouard  2709:                        
                   2710:                        
1.217     brouard  2711:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2712:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2713:       /* Careful transposed matrix */
1.222   ! brouard  2714:       /* age is in cov[2] */
1.218     brouard  2715:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222   ! brouard  2716:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  2717:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222   ! brouard  2718:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2719:       /* if((int)age == 70){ */
                   2720:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2721:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2722:       /*         printf("%d pmmij ",i); */
                   2723:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2724:       /*           printf("%f ",pmmij[i][j]); */
                   2725:       /*         } */
                   2726:       /*         printf(" oldm "); */
                   2727:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2728:       /*           printf("%f ",oldm[i][j]); */
                   2729:       /*         } */
                   2730:       /*         printf("\n"); */
                   2731:       /*       } */
                   2732:       /* } */
                   2733:       savm=oldm;
                   2734:       oldm=newm;
                   2735:     }
                   2736:     for(i=1; i<=nlstate+ndeath; i++)
                   2737:       for(j=1;j<=nlstate+ndeath;j++) {
1.222   ! brouard  2738:        po[i][j][h]=newm[i][j];
        !          2739:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2740:       }
                   2741:     /*printf("h=%d ",h);*/
                   2742:   } /* end h */
1.222   ! brouard  2743:   /*     printf("\n H=%d \n",h); */
1.217     brouard  2744:   return po;
                   2745: }
                   2746: 
                   2747: 
1.162     brouard  2748: #ifdef NLOPT
                   2749:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2750:   double fret;
                   2751:   double *xt;
                   2752:   int j;
                   2753:   myfunc_data *d2 = (myfunc_data *) pd;
                   2754: /* xt = (p1-1); */
                   2755:   xt=vector(1,n); 
                   2756:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2757: 
                   2758:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2759:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2760:   printf("Function = %.12lf ",fret);
                   2761:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2762:   printf("\n");
                   2763:  free_vector(xt,1,n);
                   2764:   return fret;
                   2765: }
                   2766: #endif
1.126     brouard  2767: 
                   2768: /*************** log-likelihood *************/
                   2769: double func( double *x)
                   2770: {
                   2771:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2772:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2773:   double **out;
                   2774:   double sw; /* Sum of weights */
                   2775:   double lli; /* Individual log likelihood */
                   2776:   int s1, s2;
                   2777:   double bbh, survp;
                   2778:   long ipmx;
1.187     brouard  2779:   double agexact;
1.126     brouard  2780:   /*extern weight */
                   2781:   /* We are differentiating ll according to initial status */
                   2782:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2783:   /*for(i=1;i<imx;i++) 
                   2784:     printf(" %d\n",s[4][i]);
                   2785:   */
1.162     brouard  2786: 
                   2787:   ++countcallfunc;
                   2788: 
1.126     brouard  2789:   cov[1]=1.;
                   2790: 
                   2791:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2792: 
                   2793:   if(mle==1){
                   2794:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2795:       /* Computes the values of the ncovmodel covariates of the model
                   2796:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2797:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2798:         to be observed in j being in i according to the model.
                   2799:        */
1.145     brouard  2800:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2801:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2802:       }
1.137     brouard  2803:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2804:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2805:         has been calculated etc */
1.126     brouard  2806:       for(mi=1; mi<= wav[i]-1; mi++){
                   2807:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2808:          for (j=1;j<=nlstate+ndeath;j++){
                   2809:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2810:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2811:          }
                   2812:        for(d=0; d<dh[mi][i]; d++){
                   2813:          newm=savm;
1.187     brouard  2814:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2815:          cov[2]=agexact;
                   2816:          if(nagesqr==1)
                   2817:            cov[3]= agexact*agexact;
1.126     brouard  2818:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2819:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2820:          }
                   2821:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2822:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2823:          savm=oldm;
                   2824:          oldm=newm;
                   2825:        } /* end mult */
                   2826:       
                   2827:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2828:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2829:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2830:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2831:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2832:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2833:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2834:         * probability in order to take into account the bias as a fraction of the way
                   2835:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2836:         * -stepm/2 to stepm/2 .
                   2837:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2838:         * For stepm > 1 the results are less biased than in previous versions. 
                   2839:         */
                   2840:        s1=s[mw[mi][i]][i];
                   2841:        s2=s[mw[mi+1][i]][i];
                   2842:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2843:        /* bias bh is positive if real duration
                   2844:         * is higher than the multiple of stepm and negative otherwise.
                   2845:         */
                   2846:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2847:        if( s2 > nlstate){ 
                   2848:          /* i.e. if s2 is a death state and if the date of death is known 
                   2849:             then the contribution to the likelihood is the probability to 
                   2850:             die between last step unit time and current  step unit time, 
                   2851:             which is also equal to probability to die before dh 
                   2852:             minus probability to die before dh-stepm . 
                   2853:             In version up to 0.92 likelihood was computed
                   2854:        as if date of death was unknown. Death was treated as any other
                   2855:        health state: the date of the interview describes the actual state
                   2856:        and not the date of a change in health state. The former idea was
                   2857:        to consider that at each interview the state was recorded
                   2858:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2859:        introduced the exact date of death then we should have modified
                   2860:        the contribution of an exact death to the likelihood. This new
                   2861:        contribution is smaller and very dependent of the step unit
                   2862:        stepm. It is no more the probability to die between last interview
                   2863:        and month of death but the probability to survive from last
                   2864:        interview up to one month before death multiplied by the
                   2865:        probability to die within a month. Thanks to Chris
                   2866:        Jackson for correcting this bug.  Former versions increased
                   2867:        mortality artificially. The bad side is that we add another loop
                   2868:        which slows down the processing. The difference can be up to 10%
                   2869:        lower mortality.
                   2870:          */
1.183     brouard  2871:        /* If, at the beginning of the maximization mostly, the
                   2872:           cumulative probability or probability to be dead is
                   2873:           constant (ie = 1) over time d, the difference is equal to
                   2874:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2875:           s1 at precedent wave, to be dead a month before current
                   2876:           wave is equal to probability, being at state s1 at
                   2877:           precedent wave, to be dead at mont of the current
                   2878:           wave. Then the observed probability (that this person died)
                   2879:           is null according to current estimated parameter. In fact,
                   2880:           it should be very low but not zero otherwise the log go to
                   2881:           infinity.
                   2882:        */
                   2883: /* #ifdef INFINITYORIGINAL */
                   2884: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2885: /* #else */
                   2886: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2887: /*         lli=log(mytinydouble); */
                   2888: /*       else */
                   2889: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2890: /* #endif */
1.216     brouard  2891:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2892:          
                   2893:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2894:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2895:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2896:          /*survp += out[s1][j]; */
                   2897:          lli= log(survp);
                   2898:        }
                   2899:        else if  (s2==-4) { 
                   2900:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2901:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2902:          lli= log(survp); 
                   2903:        } 
                   2904:        else if  (s2==-5) { 
                   2905:          for (j=1,survp=0. ; j<=2; j++)  
                   2906:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2907:          lli= log(survp); 
                   2908:        } 
                   2909:        else{
                   2910:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2911:          /*  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 */
                   2912:        } 
                   2913:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2914:        /*if(lli ==000.0)*/
                   2915:        /*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); */
                   2916:        ipmx +=1;
                   2917:        sw += weight[i];
                   2918:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2919:        /* if (lli < log(mytinydouble)){ */
                   2920:        /*   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); */
                   2921:        /*   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]); */
                   2922:        /* } */
1.126     brouard  2923:       } /* end of wave */
                   2924:     } /* end of individual */
                   2925:   }  else if(mle==2){
                   2926:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2927:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2928:       for(mi=1; mi<= wav[i]-1; mi++){
                   2929:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2930:          for (j=1;j<=nlstate+ndeath;j++){
                   2931:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2932:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2933:          }
                   2934:        for(d=0; d<=dh[mi][i]; d++){
                   2935:          newm=savm;
1.187     brouard  2936:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2937:          cov[2]=agexact;
                   2938:          if(nagesqr==1)
                   2939:            cov[3]= agexact*agexact;
1.126     brouard  2940:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2941:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2942:          }
                   2943:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2944:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2945:          savm=oldm;
                   2946:          oldm=newm;
                   2947:        } /* end mult */
                   2948:       
                   2949:        s1=s[mw[mi][i]][i];
                   2950:        s2=s[mw[mi+1][i]][i];
                   2951:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2952:        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 */
                   2953:        ipmx +=1;
                   2954:        sw += weight[i];
                   2955:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2956:       } /* end of wave */
                   2957:     } /* end of individual */
                   2958:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2959:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2960:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2961:       for(mi=1; mi<= wav[i]-1; mi++){
                   2962:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2963:          for (j=1;j<=nlstate+ndeath;j++){
                   2964:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2965:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2966:          }
                   2967:        for(d=0; d<dh[mi][i]; d++){
                   2968:          newm=savm;
1.187     brouard  2969:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2970:          cov[2]=agexact;
                   2971:          if(nagesqr==1)
                   2972:            cov[3]= agexact*agexact;
1.126     brouard  2973:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2974:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2975:          }
                   2976:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2977:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2978:          savm=oldm;
                   2979:          oldm=newm;
                   2980:        } /* end mult */
                   2981:       
                   2982:        s1=s[mw[mi][i]][i];
                   2983:        s2=s[mw[mi+1][i]][i];
                   2984:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2985:        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 */
                   2986:        ipmx +=1;
                   2987:        sw += weight[i];
                   2988:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2989:       } /* end of wave */
                   2990:     } /* end of individual */
                   2991:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2992:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2993:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2994:       for(mi=1; mi<= wav[i]-1; mi++){
                   2995:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2996:          for (j=1;j<=nlstate+ndeath;j++){
                   2997:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2998:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2999:          }
                   3000:        for(d=0; d<dh[mi][i]; d++){
                   3001:          newm=savm;
1.187     brouard  3002:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3003:          cov[2]=agexact;
                   3004:          if(nagesqr==1)
                   3005:            cov[3]= agexact*agexact;
1.126     brouard  3006:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3007:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3008:          }
                   3009:        
                   3010:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3011:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3012:          savm=oldm;
                   3013:          oldm=newm;
                   3014:        } /* end mult */
                   3015:       
                   3016:        s1=s[mw[mi][i]][i];
                   3017:        s2=s[mw[mi+1][i]][i];
                   3018:        if( s2 > nlstate){ 
                   3019:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3020:        } else if  ( s2==-1 ) { /* alive */
                   3021:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3022:            survp += out[s1][j];
                   3023:          lli= log(survp);
1.126     brouard  3024:        }else{
                   3025:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3026:        }
                   3027:        ipmx +=1;
                   3028:        sw += weight[i];
                   3029:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3030: /*     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]); */
                   3031:       } /* end of wave */
                   3032:     } /* end of individual */
                   3033:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3034:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3035:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3036:       for(mi=1; mi<= wav[i]-1; mi++){
                   3037:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3038:          for (j=1;j<=nlstate+ndeath;j++){
                   3039:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3040:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3041:          }
                   3042:        for(d=0; d<dh[mi][i]; d++){
                   3043:          newm=savm;
1.187     brouard  3044:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3045:          cov[2]=agexact;
                   3046:          if(nagesqr==1)
                   3047:            cov[3]= agexact*agexact;
1.126     brouard  3048:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3049:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3050:          }
                   3051:        
                   3052:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3053:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3054:          savm=oldm;
                   3055:          oldm=newm;
                   3056:        } /* end mult */
                   3057:       
                   3058:        s1=s[mw[mi][i]][i];
                   3059:        s2=s[mw[mi+1][i]][i];
                   3060:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3061:        ipmx +=1;
                   3062:        sw += weight[i];
                   3063:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3064:        /*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]);*/
                   3065:       } /* end of wave */
                   3066:     } /* end of individual */
                   3067:   } /* End of if */
                   3068:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3069:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3070:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3071:   return -l;
                   3072: }
                   3073: 
                   3074: /*************** log-likelihood *************/
                   3075: double funcone( double *x)
                   3076: {
                   3077:   /* Same as likeli but slower because of a lot of printf and if */
                   3078:   int i, ii, j, k, mi, d, kk;
1.131     brouard  3079:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3080:   double **out;
                   3081:   double lli; /* Individual log likelihood */
                   3082:   double llt;
                   3083:   int s1, s2;
                   3084:   double bbh, survp;
1.187     brouard  3085:   double agexact;
1.214     brouard  3086:   double agebegin, ageend;
1.126     brouard  3087:   /*extern weight */
                   3088:   /* We are differentiating ll according to initial status */
                   3089:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3090:   /*for(i=1;i<imx;i++) 
                   3091:     printf(" %d\n",s[4][i]);
                   3092:   */
                   3093:   cov[1]=1.;
                   3094: 
                   3095:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   3096: 
                   3097:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3098:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3099:     for(mi=1; mi<= wav[i]-1; mi++){
                   3100:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   3101:        for (j=1;j<=nlstate+ndeath;j++){
                   3102:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3103:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3104:        }
1.214     brouard  3105:       
                   3106:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3107:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3108:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   3109:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3110:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  3111:        newm=savm;
1.187     brouard  3112:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3113:        cov[2]=agexact;
                   3114:        if(nagesqr==1)
                   3115:          cov[3]= agexact*agexact;
1.126     brouard  3116:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3117:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3118:        }
1.187     brouard  3119: 
1.145     brouard  3120:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  3121:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3122:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  3123:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3124:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  3125:        savm=oldm;
                   3126:        oldm=newm;
                   3127:       } /* end mult */
                   3128:       
                   3129:       s1=s[mw[mi][i]][i];
                   3130:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3131:       /* if(s2==-1){ */
                   3132:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3133:       /*       /\* exit(1); *\/ */
                   3134:       /* } */
1.126     brouard  3135:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3136:       /* bias is positive if real duration
                   3137:        * is higher than the multiple of stepm and negative otherwise.
                   3138:        */
                   3139:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   3140:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3141:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  3142:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3143:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3144:        lli= log(survp);
                   3145:       }else if (mle==1){
                   3146:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3147:       } else if(mle==2){
                   3148:        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 */
                   3149:       } else if(mle==3){  /* exponential inter-extrapolation */
                   3150:        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 */
                   3151:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   3152:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3153:       } else{  /* mle=0 back to 1 */
                   3154:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3155:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3156:       } /* End of if */
                   3157:       ipmx +=1;
                   3158:       sw += weight[i];
                   3159:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3160:       /*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  3161:       if(globpr){
1.214     brouard  3162:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  3163:  %11.6f %11.6f %11.6f ", \
1.214     brouard  3164:                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  3165:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3166:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3167:          llt +=ll[k]*gipmx/gsw;
                   3168:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3169:        }
                   3170:        fprintf(ficresilk," %10.6f\n", -llt);
                   3171:       }
                   3172:     } /* end of wave */
                   3173:   } /* end of individual */
                   3174:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3175:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3176:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3177:   if(globpr==0){ /* First time we count the contributions and weights */
                   3178:     gipmx=ipmx;
                   3179:     gsw=sw;
                   3180:   }
                   3181:   return -l;
                   3182: }
                   3183: 
                   3184: 
                   3185: /*************** function likelione ***********/
                   3186: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3187: {
                   3188:   /* This routine should help understanding what is done with 
                   3189:      the selection of individuals/waves and
                   3190:      to check the exact contribution to the likelihood.
                   3191:      Plotting could be done.
                   3192:    */
                   3193:   int k;
                   3194: 
                   3195:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3196:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3197:     strcat(fileresilk,fileresu);
1.126     brouard  3198:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3199:       printf("Problem with resultfile: %s\n", fileresilk);
                   3200:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3201:     }
1.214     brouard  3202:     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");
                   3203:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3204:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3205:     for(k=1; k<=nlstate; k++) 
                   3206:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3207:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3208:   }
                   3209: 
                   3210:   *fretone=(*funcone)(p);
                   3211:   if(*globpri !=0){
                   3212:     fclose(ficresilk);
1.205     brouard  3213:     if (mle ==0)
                   3214:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3215:     else if(mle >=1)
                   3216:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3217:     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  3218:     
1.208     brouard  3219:       
                   3220:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3221:       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  3222: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3223:     }
1.207     brouard  3224:     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  3225: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3226:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3227: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3228:     fflush(fichtm);
1.205     brouard  3229:   }
1.126     brouard  3230:   return;
                   3231: }
                   3232: 
                   3233: 
                   3234: /*********** Maximum Likelihood Estimation ***************/
                   3235: 
                   3236: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3237: {
1.165     brouard  3238:   int i,j, iter=0;
1.126     brouard  3239:   double **xi;
                   3240:   double fret;
                   3241:   double fretone; /* Only one call to likelihood */
                   3242:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3243: 
                   3244: #ifdef NLOPT
                   3245:   int creturn;
                   3246:   nlopt_opt opt;
                   3247:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3248:   double *lb;
                   3249:   double minf; /* the minimum objective value, upon return */
                   3250:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3251:   myfunc_data dinst, *d = &dinst;
                   3252: #endif
                   3253: 
                   3254: 
1.126     brouard  3255:   xi=matrix(1,npar,1,npar);
                   3256:   for (i=1;i<=npar;i++)
                   3257:     for (j=1;j<=npar;j++)
                   3258:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3259:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3260:   strcpy(filerespow,"POW_"); 
1.126     brouard  3261:   strcat(filerespow,fileres);
                   3262:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3263:     printf("Problem with resultfile: %s\n", filerespow);
                   3264:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3265:   }
                   3266:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3267:   for (i=1;i<=nlstate;i++)
                   3268:     for(j=1;j<=nlstate+ndeath;j++)
                   3269:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3270:   fprintf(ficrespow,"\n");
1.162     brouard  3271: #ifdef POWELL
1.126     brouard  3272:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3273: #endif
1.126     brouard  3274: 
1.162     brouard  3275: #ifdef NLOPT
                   3276: #ifdef NEWUOA
                   3277:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3278: #else
                   3279:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3280: #endif
                   3281:   lb=vector(0,npar-1);
                   3282:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3283:   nlopt_set_lower_bounds(opt, lb);
                   3284:   nlopt_set_initial_step1(opt, 0.1);
                   3285:   
                   3286:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3287:   d->function = func;
                   3288:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3289:   nlopt_set_min_objective(opt, myfunc, d);
                   3290:   nlopt_set_xtol_rel(opt, ftol);
                   3291:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3292:     printf("nlopt failed! %d\n",creturn); 
                   3293:   }
                   3294:   else {
                   3295:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3296:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3297:     iter=1; /* not equal */
                   3298:   }
                   3299:   nlopt_destroy(opt);
                   3300: #endif
1.126     brouard  3301:   free_matrix(xi,1,npar,1,npar);
                   3302:   fclose(ficrespow);
1.203     brouard  3303:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3304:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3305:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3306: 
                   3307: }
                   3308: 
                   3309: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3310: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3311: {
                   3312:   double  **a,**y,*x,pd;
1.203     brouard  3313:   /* double **hess; */
1.164     brouard  3314:   int i, j;
1.126     brouard  3315:   int *indx;
                   3316: 
                   3317:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3318:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3319:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3320:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3321:   double gompertz(double p[]);
1.203     brouard  3322:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3323: 
                   3324:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3325:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3326:   for (i=1;i<=npar;i++){
1.203     brouard  3327:     printf("%d-",i);fflush(stdout);
                   3328:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3329:    
                   3330:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3331:     
                   3332:     /*  printf(" %f ",p[i]);
                   3333:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3334:   }
                   3335:   
                   3336:   for (i=1;i<=npar;i++) {
                   3337:     for (j=1;j<=npar;j++)  {
                   3338:       if (j>i) { 
1.203     brouard  3339:        printf(".%d-%d",i,j);fflush(stdout);
                   3340:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3341:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3342:        
                   3343:        hess[j][i]=hess[i][j];    
                   3344:        /*printf(" %lf ",hess[i][j]);*/
                   3345:       }
                   3346:     }
                   3347:   }
                   3348:   printf("\n");
                   3349:   fprintf(ficlog,"\n");
                   3350: 
                   3351:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3352:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3353:   
                   3354:   a=matrix(1,npar,1,npar);
                   3355:   y=matrix(1,npar,1,npar);
                   3356:   x=vector(1,npar);
                   3357:   indx=ivector(1,npar);
                   3358:   for (i=1;i<=npar;i++)
                   3359:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3360:   ludcmp(a,npar,indx,&pd);
                   3361: 
                   3362:   for (j=1;j<=npar;j++) {
                   3363:     for (i=1;i<=npar;i++) x[i]=0;
                   3364:     x[j]=1;
                   3365:     lubksb(a,npar,indx,x);
                   3366:     for (i=1;i<=npar;i++){ 
                   3367:       matcov[i][j]=x[i];
                   3368:     }
                   3369:   }
                   3370: 
                   3371:   printf("\n#Hessian matrix#\n");
                   3372:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3373:   for (i=1;i<=npar;i++) { 
                   3374:     for (j=1;j<=npar;j++) { 
1.203     brouard  3375:       printf("%.6e ",hess[i][j]);
                   3376:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3377:     }
                   3378:     printf("\n");
                   3379:     fprintf(ficlog,"\n");
                   3380:   }
                   3381: 
1.203     brouard  3382:   /* printf("\n#Covariance matrix#\n"); */
                   3383:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3384:   /* for (i=1;i<=npar;i++) {  */
                   3385:   /*   for (j=1;j<=npar;j++) {  */
                   3386:   /*     printf("%.6e ",matcov[i][j]); */
                   3387:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3388:   /*   } */
                   3389:   /*   printf("\n"); */
                   3390:   /*   fprintf(ficlog,"\n"); */
                   3391:   /* } */
                   3392: 
1.126     brouard  3393:   /* Recompute Inverse */
1.203     brouard  3394:   /* for (i=1;i<=npar;i++) */
                   3395:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3396:   /* ludcmp(a,npar,indx,&pd); */
                   3397: 
                   3398:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3399: 
                   3400:   /* for (j=1;j<=npar;j++) { */
                   3401:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3402:   /*   x[j]=1; */
                   3403:   /*   lubksb(a,npar,indx,x); */
                   3404:   /*   for (i=1;i<=npar;i++){  */
                   3405:   /*     y[i][j]=x[i]; */
                   3406:   /*     printf("%.3e ",y[i][j]); */
                   3407:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3408:   /*   } */
                   3409:   /*   printf("\n"); */
                   3410:   /*   fprintf(ficlog,"\n"); */
                   3411:   /* } */
                   3412: 
                   3413:   /* Verifying the inverse matrix */
                   3414: #ifdef DEBUGHESS
                   3415:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3416: 
1.203     brouard  3417:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3418:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3419: 
                   3420:   for (j=1;j<=npar;j++) {
                   3421:     for (i=1;i<=npar;i++){ 
1.203     brouard  3422:       printf("%.2f ",y[i][j]);
                   3423:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3424:     }
                   3425:     printf("\n");
                   3426:     fprintf(ficlog,"\n");
                   3427:   }
1.203     brouard  3428: #endif
1.126     brouard  3429: 
                   3430:   free_matrix(a,1,npar,1,npar);
                   3431:   free_matrix(y,1,npar,1,npar);
                   3432:   free_vector(x,1,npar);
                   3433:   free_ivector(indx,1,npar);
1.203     brouard  3434:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3435: 
                   3436: 
                   3437: }
                   3438: 
                   3439: /*************** hessian matrix ****************/
                   3440: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3441: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3442:   int i;
                   3443:   int l=1, lmax=20;
1.203     brouard  3444:   double k1,k2, res, fx;
1.132     brouard  3445:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3446:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3447:   int k=0,kmax=10;
                   3448:   double l1;
                   3449: 
                   3450:   fx=func(x);
                   3451:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3452:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3453:     l1=pow(10,l);
                   3454:     delts=delt;
                   3455:     for(k=1 ; k <kmax; k=k+1){
                   3456:       delt = delta*(l1*k);
                   3457:       p2[theta]=x[theta] +delt;
1.145     brouard  3458:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3459:       p2[theta]=x[theta]-delt;
                   3460:       k2=func(p2)-fx;
                   3461:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3462:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3463:       
1.203     brouard  3464: #ifdef DEBUGHESSII
1.126     brouard  3465:       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);
                   3466:       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);
                   3467: #endif
                   3468:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3469:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3470:        k=kmax;
                   3471:       }
                   3472:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3473:        k=kmax; l=lmax*10;
1.126     brouard  3474:       }
                   3475:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3476:        delts=delt;
                   3477:       }
1.203     brouard  3478:     } /* End loop k */
1.126     brouard  3479:   }
                   3480:   delti[theta]=delts;
                   3481:   return res; 
                   3482:   
                   3483: }
                   3484: 
1.203     brouard  3485: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3486: {
                   3487:   int i;
1.164     brouard  3488:   int l=1, lmax=20;
1.126     brouard  3489:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3490:   double p2[MAXPARM+1];
1.203     brouard  3491:   int k, kmax=1;
                   3492:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3493: 
                   3494:   int firstime=0;
1.203     brouard  3495:   
1.126     brouard  3496:   fx=func(x);
1.203     brouard  3497:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3498:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3499:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3500:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3501:     k1=func(p2)-fx;
                   3502:   
1.203     brouard  3503:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3504:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3505:     k2=func(p2)-fx;
                   3506:   
1.203     brouard  3507:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3508:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3509:     k3=func(p2)-fx;
                   3510:   
1.203     brouard  3511:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3512:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3513:     k4=func(p2)-fx;
1.203     brouard  3514:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3515:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3516:       firstime=1;
1.203     brouard  3517:       kmax=kmax+10;
1.208     brouard  3518:     }
                   3519:     if(kmax >=10 || firstime ==1){
1.218     brouard  3520:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3521:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  3522:       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);
                   3523:       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);
                   3524:     }
                   3525: #ifdef DEBUGHESSIJ
                   3526:     v1=hess[thetai][thetai];
                   3527:     v2=hess[thetaj][thetaj];
                   3528:     cv12=res;
                   3529:     /* Computing eigen value of Hessian matrix */
                   3530:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3531:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3532:     if ((lc2 <0) || (lc1 <0) ){
                   3533:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3534:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3535:       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);
                   3536:       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);
                   3537:     }
1.126     brouard  3538: #endif
                   3539:   }
                   3540:   return res;
                   3541: }
                   3542: 
1.203     brouard  3543:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3544: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3545: /* { */
                   3546: /*   int i; */
                   3547: /*   int l=1, lmax=20; */
                   3548: /*   double k1,k2,k3,k4,res,fx; */
                   3549: /*   double p2[MAXPARM+1]; */
                   3550: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3551: /*   int k=0,kmax=10; */
                   3552: /*   double l1; */
                   3553:   
                   3554: /*   fx=func(x); */
                   3555: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3556: /*     l1=pow(10,l); */
                   3557: /*     delts=delt; */
                   3558: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3559: /*       delt = delti*(l1*k); */
                   3560: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3561: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3562: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3563: /*       k1=func(p2)-fx; */
                   3564:       
                   3565: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3566: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3567: /*       k2=func(p2)-fx; */
                   3568:       
                   3569: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3570: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3571: /*       k3=func(p2)-fx; */
                   3572:       
                   3573: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3574: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3575: /*       k4=func(p2)-fx; */
                   3576: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3577: /* #ifdef DEBUGHESSIJ */
                   3578: /*       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); */
                   3579: /*       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); */
                   3580: /* #endif */
                   3581: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3582: /*     k=kmax; */
                   3583: /*       } */
                   3584: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3585: /*     k=kmax; l=lmax*10; */
                   3586: /*       } */
                   3587: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3588: /*     delts=delt; */
                   3589: /*       } */
                   3590: /*     } /\* End loop k *\/ */
                   3591: /*   } */
                   3592: /*   delti[theta]=delts; */
                   3593: /*   return res;  */
                   3594: /* } */
                   3595: 
                   3596: 
1.126     brouard  3597: /************** Inverse of matrix **************/
                   3598: void ludcmp(double **a, int n, int *indx, double *d) 
                   3599: { 
                   3600:   int i,imax,j,k; 
                   3601:   double big,dum,sum,temp; 
                   3602:   double *vv; 
                   3603:  
                   3604:   vv=vector(1,n); 
                   3605:   *d=1.0; 
                   3606:   for (i=1;i<=n;i++) { 
                   3607:     big=0.0; 
                   3608:     for (j=1;j<=n;j++) 
                   3609:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3610:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3611:     vv[i]=1.0/big; 
                   3612:   } 
                   3613:   for (j=1;j<=n;j++) { 
                   3614:     for (i=1;i<j;i++) { 
                   3615:       sum=a[i][j]; 
                   3616:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3617:       a[i][j]=sum; 
                   3618:     } 
                   3619:     big=0.0; 
                   3620:     for (i=j;i<=n;i++) { 
                   3621:       sum=a[i][j]; 
                   3622:       for (k=1;k<j;k++) 
                   3623:        sum -= a[i][k]*a[k][j]; 
                   3624:       a[i][j]=sum; 
                   3625:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3626:        big=dum; 
                   3627:        imax=i; 
                   3628:       } 
                   3629:     } 
                   3630:     if (j != imax) { 
                   3631:       for (k=1;k<=n;k++) { 
                   3632:        dum=a[imax][k]; 
                   3633:        a[imax][k]=a[j][k]; 
                   3634:        a[j][k]=dum; 
                   3635:       } 
                   3636:       *d = -(*d); 
                   3637:       vv[imax]=vv[j]; 
                   3638:     } 
                   3639:     indx[j]=imax; 
                   3640:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3641:     if (j != n) { 
                   3642:       dum=1.0/(a[j][j]); 
                   3643:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3644:     } 
                   3645:   } 
                   3646:   free_vector(vv,1,n);  /* Doesn't work */
                   3647: ;
                   3648: } 
                   3649: 
                   3650: void lubksb(double **a, int n, int *indx, double b[]) 
                   3651: { 
                   3652:   int i,ii=0,ip,j; 
                   3653:   double sum; 
                   3654:  
                   3655:   for (i=1;i<=n;i++) { 
                   3656:     ip=indx[i]; 
                   3657:     sum=b[ip]; 
                   3658:     b[ip]=b[i]; 
                   3659:     if (ii) 
                   3660:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3661:     else if (sum) ii=i; 
                   3662:     b[i]=sum; 
                   3663:   } 
                   3664:   for (i=n;i>=1;i--) { 
                   3665:     sum=b[i]; 
                   3666:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3667:     b[i]=sum/a[i][i]; 
                   3668:   } 
                   3669: } 
                   3670: 
                   3671: void pstamp(FILE *fichier)
                   3672: {
1.196     brouard  3673:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3674: }
                   3675: 
                   3676: /************ Frequencies ********************/
1.220     brouard  3677:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3678:                                                                         int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   3679:                                                                         int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3680:  {  /* Some frequencies */
                   3681:   
                   3682:         int i, m, jk, j1, bool, z1,j;
                   3683:         int iind=0, iage=0;
                   3684:         int mi; /* Effective wave */
                   3685:         int first;
                   3686:         double ***freq; /* Frequencies */
                   3687:         double *pp, **prop, *posprop, *pospropt;
                   3688:         double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   3689:         char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3690:         double agebegin, ageend;
                   3691:     
                   3692:         pp=vector(1,nlstate);
                   3693:         prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3694:         posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   3695:         pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   3696:         /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   3697:         strcpy(fileresp,"P_");
                   3698:         strcat(fileresp,fileresu);
                   3699:         /*strcat(fileresphtm,fileresu);*/
                   3700:         if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3701:                 printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3702:                 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3703:                 exit(0);
                   3704:         }
1.214     brouard  3705: 
1.220     brouard  3706:         strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3707:         if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3708:                 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3709:                 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3710:                 fflush(ficlog);
                   3711:                 exit(70); 
                   3712:         }
                   3713:         else{
                   3714:                 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3715: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3716: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3717:                                                 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3718:         }
                   3719:         fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
1.214     brouard  3720:     
1.220     brouard  3721:         strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3722:         if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3723:                 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3724:                 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3725:                 fflush(ficlog);
                   3726:                 exit(70); 
                   3727:         }
                   3728:         else{
                   3729:                 fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3730: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3731: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3732:                                                 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3733:         }
                   3734:         fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
1.214     brouard  3735: 
1.220     brouard  3736:         freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   3737:         j1=0;
1.126     brouard  3738:   
1.220     brouard  3739:         j=cptcoveff;
                   3740:         if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3741: 
                   3742:         first=1;
                   3743: 
                   3744:         /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   3745:                        reference=low_education V1=0,V2=0
                   3746:                        med_educ                V1=1 V2=0, 
                   3747:                        high_educ               V1=0 V2=1
                   3748:                        Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   3749:         */
1.126     brouard  3750: 
1.220     brouard  3751:         for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
                   3752:                 posproptt=0.;
                   3753:                 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3754:                         scanf("%d", i);*/
                   3755:                 for (i=-5; i<=nlstate+ndeath; i++)  
                   3756:                         for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3757:                                 for(m=iagemin; m <= iagemax+3; m++)
                   3758:                                         freq[i][jk][m]=0;
                   3759:       
                   3760:                 for (i=1; i<=nlstate; i++)  {
                   3761:                         for(m=iagemin; m <= iagemax+3; m++)
                   3762:                                 prop[i][m]=0;
                   3763:                         posprop[i]=0;
                   3764:                         pospropt[i]=0;
                   3765:                 }
                   3766:       
                   3767:                 dateintsum=0;
                   3768:                 k2cpt=0;
1.126     brouard  3769: 
1.220     brouard  3770:                 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   3771:                         bool=1;
                   3772:                         if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3773:                                 for (z1=1; z1<=cptcoveff; z1++) {      
                   3774:                                         if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   3775:                                                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
                   3776:                                                 bool=0;
                   3777:                                                 /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
1.198     brouard  3778:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3779:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.220     brouard  3780:                                                 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   3781:                                         } 
                   3782:                                 } /* end z1 */
                   3783:                         } /* cptcovn > 0 */
                   3784: 
                   3785:                         if (bool==1){
                   3786:                                 /* for(m=firstpass; m<=lastpass; m++){ */
                   3787:                                 for(mi=1; mi<wav[iind];mi++){
                   3788:                                         m=mw[mi][iind];
                   3789:                                         /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   3790:                                                        and mw[mi+1][iind]. dh depends on stepm. */
                   3791:                                         agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   3792:                                         ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   3793:                                         if(m >=firstpass && m <=lastpass){
                   3794:                                                 k2=anint[m][iind]+(mint[m][iind]/12.);
                   3795:                                                 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3796:                                                 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3797:                                                 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3798:                                                 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   3799:                                                         prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   3800:                                                 if (m<lastpass) {
                   3801:                                                         /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   3802:                                                         /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
                   3803:                                                         if(s[m][iind]==-1)
                   3804:                                                                 printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   3805:                                                         freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   3806:                                                         /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   3807:                                                         freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
                   3808:                                                 }
                   3809:                                         }  
                   3810:                                         if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   3811:                                                 dateintsum=dateintsum+k2;
                   3812:                                                 k2cpt++;
                   3813:                                                 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3814:                                         }
                   3815:                                         /*}*/
                   3816:                                 } /* end m */
                   3817:                         } /* end bool */
                   3818:                 } /* end iind = 1 to imx */
                   3819:        /* prop[s][age] is feeded for any initial and valid live state as well as
                   3820:                                        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   3821: 
                   3822: 
                   3823:                 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3824:                 pstamp(ficresp);
                   3825:                 if  (cptcovn>0) {
                   3826:                         fprintf(ficresp, "\n#********** Variable "); 
                   3827:                         fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3828:                         fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   3829:                         for (z1=1; z1<=cptcoveff; z1++){
                   3830:                                 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3831:                                 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3832:                                 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3833:                         }
                   3834:                         fprintf(ficresp, "**********\n#");
                   3835:                         fprintf(ficresphtm, "**********</h3>\n");
                   3836:                         fprintf(ficresphtmfr, "**********</h3>\n");
                   3837:                         fprintf(ficlog, "\n#********** Variable "); 
                   3838:                         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3839:                         fprintf(ficlog, "**********\n");
                   3840:                 }
                   3841:                 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   3842:                 for(i=1; i<=nlstate;i++) {
                   3843:                         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3844:                         fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3845:                 }
                   3846:                 fprintf(ficresp, "\n");
                   3847:                 fprintf(ficresphtm, "\n");
                   3848:       
                   3849:                 /* Header of frequency table by age */
                   3850:                 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3851:                 fprintf(ficresphtmfr,"<th>Age</th> ");
                   3852:                 for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3853:                         for(m=-1; m <=nlstate+ndeath; m++){
                   3854:                                 if(jk!=0 && m!=0)
                   3855:                                         fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3856:                         }
                   3857:                 }
                   3858:                 fprintf(ficresphtmfr, "\n");
1.214     brouard  3859:       
1.220     brouard  3860:                 /* For each age */
                   3861:                 for(iage=iagemin; iage <= iagemax+3; iage++){
                   3862:                         fprintf(ficresphtm,"<tr>");
                   3863:                         if(iage==iagemax+1){
                   3864:                                 fprintf(ficlog,"1");
                   3865:                                 fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3866:                         }else if(iage==iagemax+2){
                   3867:                                 fprintf(ficlog,"0");
                   3868:                                 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3869:                         }else if(iage==iagemax+3){
                   3870:                                 fprintf(ficlog,"Total");
                   3871:                                 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   3872:                         }else{
                   3873:                                 if(first==1){
                   3874:                                         first=0;
                   3875:                                         printf("See log file for details...\n");
                   3876:                                 }
                   3877:                                 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   3878:                                 fprintf(ficlog,"Age %d", iage);
                   3879:                         }
                   3880:                         for(jk=1; jk <=nlstate ; jk++){
                   3881:                                 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3882:                                         pp[jk] += freq[jk][m][iage]; 
                   3883:                         }
                   3884:                         for(jk=1; jk <=nlstate ; jk++){
                   3885:                                 for(m=-1, pos=0; m <=0 ; m++)
                   3886:                                         pos += freq[jk][m][iage];
                   3887:                                 if(pp[jk]>=1.e-10){
                   3888:                                         if(first==1){
                   3889:                                                 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3890:                                         }
                   3891:                                         fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3892:                                 }else{
                   3893:                                         if(first==1)
                   3894:                                                 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3895:                                         fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3896:                                 }
                   3897:                         }
                   3898: 
                   3899:                         for(jk=1; jk <=nlstate ; jk++){ 
                   3900:                                 /* posprop[jk]=0; */
                   3901:                                 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   3902:                                         pp[jk] += freq[jk][m][iage];
                   3903:                         }      /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   3904: 
                   3905:                         for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   3906:                                 pos += pp[jk]; /* pos is the total number of transitions until this age */
                   3907:                                 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3908:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3909:                                 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3910:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3911:                         }
                   3912:                         for(jk=1; jk <=nlstate ; jk++){
                   3913:                                 if(pos>=1.e-5){
                   3914:                                         if(first==1)
                   3915:                                                 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3916:                                         fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3917:                                 }else{
                   3918:                                         if(first==1)
                   3919:                                                 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3920:                                         fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3921:                                 }
                   3922:                                 if( iage <= iagemax){
                   3923:                                         if(pos>=1.e-5){
                   3924:                                                 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3925:                                                 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3926:                                                 /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   3927:                                                 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   3928:                                         }
                   3929:                                         else{
                   3930:                                                 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   3931:                                                 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   3932:                                         }
                   3933:                                 }
                   3934:                                 pospropt[jk] +=posprop[jk];
                   3935:                         } /* end loop jk */
                   3936:                         /* pospropt=0.; */
                   3937:                         for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3938:                                 for(m=-1; m <=nlstate+ndeath; m++){
                   3939:                                         if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   3940:                                                 if(first==1){
                   3941:                                                         printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3942:                                                 }
                   3943:                                                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3944:                                         }
                   3945:                                         if(jk!=0 && m!=0)
                   3946:                                                 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   3947:                                 }
                   3948:                         } /* end loop jk */
                   3949:                         posproptt=0.; 
                   3950:                         for(jk=1; jk <=nlstate; jk++){
                   3951:                                 posproptt += pospropt[jk];
                   3952:                         }
                   3953:                         fprintf(ficresphtmfr,"</tr>\n ");
                   3954:                         if(iage <= iagemax){
                   3955:                                 fprintf(ficresp,"\n");
                   3956:                                 fprintf(ficresphtm,"</tr>\n");
                   3957:                         }
                   3958:                         if(first==1)
                   3959:                                 printf("Others in log...\n");
                   3960:                         fprintf(ficlog,"\n");
                   3961:                 } /* end loop age iage */
                   3962:                 fprintf(ficresphtm,"<tr><th>Tot</th>");
                   3963:                 for(jk=1; jk <=nlstate ; jk++){
                   3964:                         if(posproptt < 1.e-5){
1.221     brouard  3965:                                 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
                   3966:                         }else{
1.220     brouard  3967:                                 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
                   3968:                         }
                   3969:                 }
                   3970:                 fprintf(ficresphtm,"</tr>\n");
                   3971:                 fprintf(ficresphtm,"</table>\n");
                   3972:                 fprintf(ficresphtmfr,"</table>\n");
                   3973:                 if(posproptt < 1.e-5){
                   3974:                         fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   3975:                         fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   3976:                         fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   3977:                         invalidvarcomb[j1]=1;
                   3978:                 }else{
                   3979:                         fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   3980:                         invalidvarcomb[j1]=0;
                   3981:                 }
                   3982:                 fprintf(ficresphtmfr,"</table>\n");
                   3983:         } /* end selected combination of covariate j1 */
                   3984:         dateintmean=dateintsum/k2cpt; 
                   3985:                 
                   3986:         fclose(ficresp);
                   3987:         fclose(ficresphtm);
                   3988:         fclose(ficresphtmfr);
                   3989:         free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   3990:         free_vector(pospropt,1,nlstate);
                   3991:         free_vector(posprop,1,nlstate);
                   3992:         free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   3993:         free_vector(pp,1,nlstate);
                   3994:         /* End of Freq */
                   3995:  }
1.126     brouard  3996: 
                   3997: /************ Prevalence ********************/
1.222   ! brouard  3998:  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)
        !          3999:  {  
        !          4000:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
        !          4001:       in each health status at the date of interview (if between dateprev1 and dateprev2).
        !          4002:       We still use firstpass and lastpass as another selection.
        !          4003:    */
1.126     brouard  4004:  
1.222   ! brouard  4005:    int i, m, jk, j1, bool, z1,j;
        !          4006:    int mi; /* Effective wave */
        !          4007:    int iage;
        !          4008:    double agebegin, ageend;
        !          4009: 
        !          4010:    double **prop;
        !          4011:    double posprop; 
        !          4012:    double  y2; /* in fractional years */
        !          4013:    int iagemin, iagemax;
        !          4014:    int first; /** to stop verbosity which is redirected to log file */
        !          4015: 
        !          4016:    iagemin= (int) agemin;
        !          4017:    iagemax= (int) agemax;
        !          4018:    /*pp=vector(1,nlstate);*/
        !          4019:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
        !          4020:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
        !          4021:    j1=0;
        !          4022:   
        !          4023:    /*j=cptcoveff;*/
        !          4024:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
        !          4025:   
        !          4026:    first=1;
        !          4027:    for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
        !          4028:      for (i=1; i<=nlstate; i++)  
        !          4029:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
        !          4030:         prop[i][iage]=0.0;
        !          4031:     
        !          4032:      for (i=1; i<=imx; i++) { /* Each individual */
        !          4033:        bool=1;
        !          4034:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          4035:         for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
        !          4036:           if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
        !          4037:             bool=0;
        !          4038:        } 
        !          4039:        if (bool==1) { /* For this combination of covariates values, this individual fits */
        !          4040:         /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
        !          4041:         for(mi=1; mi<wav[i];mi++){
        !          4042:           m=mw[mi][i];
        !          4043:           agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
        !          4044:           /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
        !          4045:           if(m >=firstpass && m <=lastpass){
        !          4046:             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
        !          4047:             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
        !          4048:               if(agev[m][i]==0) agev[m][i]=iagemax+1;
        !          4049:               if(agev[m][i]==1) agev[m][i]=iagemax+2;
        !          4050:               if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
        !          4051:                 printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
        !          4052:                 exit(1);
        !          4053:               }
        !          4054:               if (s[m][i]>0 && s[m][i]<=nlstate) { 
        !          4055:                 /*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]]);*/
        !          4056:                 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
        !          4057:                 prop[s[m][i]][iagemax+3] += weight[i]; 
        !          4058:               } /* end valid statuses */ 
        !          4059:             } /* end selection of dates */
        !          4060:           } /* end selection of waves */
        !          4061:         } /* end effective waves */
        !          4062:        } /* end bool */
        !          4063:      }
        !          4064:      for(i=iagemin; i <= iagemax+3; i++){  
        !          4065:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
        !          4066:         posprop += prop[jk][i]; 
        !          4067:        } 
        !          4068:       
        !          4069:        for(jk=1; jk <=nlstate ; jk++){     
        !          4070:         if( i <=  iagemax){ 
        !          4071:           if(posprop>=1.e-5){ 
        !          4072:             probs[i][jk][j1]= prop[jk][i]/posprop;
        !          4073:           } else{
        !          4074:             if(first==1){
        !          4075:               first=0;
        !          4076:               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]);
        !          4077:             }
        !          4078:           }
        !          4079:         } 
        !          4080:        }/* end jk */ 
        !          4081:      }/* end i */ 
        !          4082:      /*} *//* end i1 */
        !          4083:    } /* end j1 */
        !          4084:   
        !          4085:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
        !          4086:    /*free_vector(pp,1,nlstate);*/
        !          4087:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
        !          4088:  }  /* End of prevalence */
1.126     brouard  4089: 
                   4090: /************* Waves Concatenation ***************/
                   4091: 
                   4092: 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)
                   4093: {
                   4094:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4095:      Death is a valid wave (if date is known).
                   4096:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4097:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4098:      and mw[mi+1][i]. dh depends on stepm.
                   4099:      */
                   4100: 
                   4101:   int i, mi, m;
                   4102:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4103:      double sum=0., jmean=0.;*/
1.218     brouard  4104:   int first, firstwo, firsthree, firstfour;
1.126     brouard  4105:   int j, k=0,jk, ju, jl;
                   4106:   double sum=0.;
                   4107:   first=0;
1.214     brouard  4108:   firstwo=0;
1.217     brouard  4109:   firsthree=0;
1.218     brouard  4110:   firstfour=0;
1.164     brouard  4111:   jmin=100000;
1.126     brouard  4112:   jmax=-1;
                   4113:   jmean=0.;
1.214     brouard  4114:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  4115:     mi=0;
                   4116:     m=firstpass;
1.214     brouard  4117:     while(s[m][i] <= nlstate){  /* a live state */
1.216     brouard  4118:       if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
1.126     brouard  4119:        mw[++mi][i]=m;
1.216     brouard  4120:       }
                   4121:       if(m >=lastpass){
                   4122:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
1.217     brouard  4123:          if(firsthree == 0){
                   4124:            printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
                   4125:            firsthree=1;
                   4126:          }
1.218     brouard  4127:          fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
1.216     brouard  4128:          mw[++mi][i]=m;
                   4129:        }
                   4130:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4131:          nbwarn++;
                   4132:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4133:            printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4134:            fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4135:          }
                   4136:          break;
                   4137:        }
1.126     brouard  4138:        break;
1.216     brouard  4139:       }
1.126     brouard  4140:       else
                   4141:        m++;
                   4142:     }/* end while */
1.216     brouard  4143:     
                   4144:     /* After last pass */
1.214     brouard  4145:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  4146:       mi++;    /* Death is another wave */
                   4147:       /* if(mi==0)  never been interviewed correctly before death */
                   4148:         /* Only death is a correct wave */
                   4149:       mw[mi][i]=m;
1.216     brouard  4150:     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
                   4151:       /* m++; */
                   4152:       /* mi++; */
                   4153:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4154:       /* mw[mi][i]=m; */
                   4155:       nberr++;
1.218     brouard  4156:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
                   4157:        if(firstwo==0){
                   4158:          printf("Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4159:          firstwo=1;
                   4160:        }
                   4161:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4162:       }else{ /* end date of interview is known */
                   4163:        /* death is known but not confirmed by death status at any wave */
                   4164:        if(firstfour==0){
                   4165:          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4166:          firstfour=1;
                   4167:        }
                   4168:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.214     brouard  4169:       }
1.126     brouard  4170:     }
                   4171:     wav[i]=mi;
                   4172:     if(mi==0){
                   4173:       nbwarn++;
                   4174:       if(first==0){
                   4175:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4176:        first=1;
                   4177:       }
                   4178:       if(first==1){
                   4179:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   4180:       }
                   4181:     } /* end mi==0 */
                   4182:   } /* End individuals */
1.214     brouard  4183:   /* wav and mw are no more changed */
1.126     brouard  4184: 
1.214     brouard  4185:   
1.126     brouard  4186:   for(i=1; i<=imx; i++){
                   4187:     for(mi=1; mi<wav[i];mi++){
                   4188:       if (stepm <=0)
                   4189:        dh[mi][i]=1;
                   4190:       else{
                   4191:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4192:          if (agedc[i] < 2*AGESUP) {
                   4193:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4194:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4195:            else if(j<0){
                   4196:              nberr++;
                   4197:              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]);
                   4198:              j=1; /* Temporary Dangerous patch */
                   4199:              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);
                   4200:              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]);
                   4201:              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);
                   4202:            }
                   4203:            k=k+1;
                   4204:            if (j >= jmax){
                   4205:              jmax=j;
                   4206:              ijmax=i;
                   4207:            }
                   4208:            if (j <= jmin){
                   4209:              jmin=j;
                   4210:              ijmin=i;
                   4211:            }
                   4212:            sum=sum+j;
                   4213:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4214:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4215:          }
                   4216:        }
                   4217:        else{
                   4218:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   4219: /*       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]); */
                   4220: 
                   4221:          k=k+1;
                   4222:          if (j >= jmax) {
                   4223:            jmax=j;
                   4224:            ijmax=i;
                   4225:          }
                   4226:          else if (j <= jmin){
                   4227:            jmin=j;
                   4228:            ijmin=i;
                   4229:          }
                   4230:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4231:          /*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]);*/
                   4232:          if(j<0){
                   4233:            nberr++;
                   4234:            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]);
                   4235:            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]);
                   4236:          }
                   4237:          sum=sum+j;
                   4238:        }
                   4239:        jk= j/stepm;
                   4240:        jl= j -jk*stepm;
                   4241:        ju= j -(jk+1)*stepm;
                   4242:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4243:          if(jl==0){
                   4244:            dh[mi][i]=jk;
                   4245:            bh[mi][i]=0;
                   4246:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  4247:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  4248:            dh[mi][i]=jk+1;
                   4249:            bh[mi][i]=ju;
                   4250:          }
                   4251:        }else{
                   4252:          if(jl <= -ju){
                   4253:            dh[mi][i]=jk;
                   4254:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4255:                                 * is higher than the multiple of stepm and negative otherwise.
                   4256:                                 */
                   4257:          }
                   4258:          else{
                   4259:            dh[mi][i]=jk+1;
                   4260:            bh[mi][i]=ju;
                   4261:          }
                   4262:          if(dh[mi][i]==0){
                   4263:            dh[mi][i]=1; /* At least one step */
                   4264:            bh[mi][i]=ju; /* At least one step */
                   4265:            /*  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);*/
                   4266:          }
                   4267:        } /* end if mle */
                   4268:       }
                   4269:     } /* end wave */
                   4270:   }
                   4271:   jmean=sum/k;
                   4272:   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  4273:   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  4274:  }
                   4275: 
                   4276: /*********** Tricode ****************************/
1.220     brouard  4277:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4278: {
1.144     brouard  4279:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4280:   /*     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  4281:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  4282:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.220     brouard  4283:    * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
1.144     brouard  4284:   */
1.130     brouard  4285: 
1.145     brouard  4286:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4287:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4288:   int cptcode=0; /* Modality max of covariates j */
                   4289:   int modmincovj=0; /* Modality min of covariates j */
                   4290: 
                   4291: 
1.220     brouard  4292:   /* cptcoveff=0;  */
                   4293:        *cptcov=0;
1.126     brouard  4294:  
1.144     brouard  4295:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4296: 
1.145     brouard  4297:   /* Loop on covariates without age and products */
1.186     brouard  4298:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4299:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4300:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.219     brouard  4301:                                                                                                                                modality of this covariate Vj*/ 
1.145     brouard  4302:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
1.219     brouard  4303:                                                                                                                                                * If product of Vn*Vm, still boolean *:
                   4304:                                                                                                                                                * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4305:                                                                                                                                                * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
1.145     brouard  4306:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  4307:                                      modality of the nth covariate of individual i. */
1.145     brouard  4308:       if (ij > modmaxcovj)
                   4309:         modmaxcovj=ij; 
                   4310:       else if (ij < modmincovj) 
1.219     brouard  4311:                                modmincovj=ij; 
1.145     brouard  4312:       if ((ij < -1) && (ij > NCOVMAX)){
1.219     brouard  4313:                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4314:                                exit(1);
1.145     brouard  4315:       }else
1.136     brouard  4316:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4317:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4318:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4319:       /* getting the maximum value of the modality of the covariate
                   4320:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4321:         female is 1, then modmaxcovj=1.*/
1.192     brouard  4322:     } /* end for loop on individuals i */
1.145     brouard  4323:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4324:     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  4325:     cptcode=modmaxcovj;
1.137     brouard  4326:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  4327:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4328:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4329:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4330:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4331:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
1.219     brouard  4332:                                if( k != -1){
                   4333:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4334:                                                                                                                 covariate for which somebody answered excluding 
                   4335:                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4336:                                }
                   4337:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4338:                                                                                                                                covariate for which somebody answered including 
                   4339:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4340:       }
                   4341:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.219     brouard  4342:                                 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4343:     } /* Ndum[-1] number of undefined modalities */
1.219     brouard  4344:                
1.136     brouard  4345:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4346:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4347:        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  4348:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4349:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4350:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4351:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4352:        nbcode[Tvar[j]][ij]=k;
                   4353:        nbcode[Tvar[j]][1]=0;
                   4354:        nbcode[Tvar[j]][2]=1;
                   4355:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4356:        To be continued (not working yet).
1.145     brouard  4357:     */
1.197     brouard  4358:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4359:     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*/
                   4360:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.219     brouard  4361:                                break;
                   4362:                        }
1.192     brouard  4363:        ij++;
1.197     brouard  4364:        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  4365:        cptcode = ij; /* New max modality for covar j */
                   4366:     } /* end of loop on modality i=-1 to 1 or more */
                   4367:       
                   4368:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4369:     /*         /\*recode from 0 *\/ */
                   4370:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4371:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4372:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4373:     /*         } */
                   4374:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4375:     /*         if (ij > ncodemax[j]) { */
                   4376:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4377:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4378:     /*           break; */
                   4379:     /*         } */
                   4380:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4381:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4382:   
1.219     brouard  4383:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4384:   
1.187     brouard  4385:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.219     brouard  4386:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4387:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   4388:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
                   4389:        } 
                   4390:        
                   4391:        ij=0;
                   4392:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4393:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4394:                if((Ndum[i]!=0) && (i<=ncovcol)){
                   4395:                        ij++;
                   4396:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4397:                        Tvaraff[ij]=i; /*For printing (unclear) */
                   4398:                }else{
                   4399:                        /* Tvaraff[ij]=0; */
                   4400:                }
                   4401:        }
                   4402:        /* ij--; */
1.220     brouard  4403:        /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4404:        *cptcov=ij; /*Number of total covariates*/
1.219     brouard  4405:        
1.126     brouard  4406: }
                   4407: 
1.145     brouard  4408: 
1.126     brouard  4409: /*********** Health Expectancies ****************/
                   4410: 
1.127     brouard  4411: 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  4412: 
                   4413: {
                   4414:   /* Health expectancies, no variances */
1.164     brouard  4415:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4416:   int nhstepma, nstepma; /* Decreasing with age */
                   4417:   double age, agelim, hf;
                   4418:   double ***p3mat;
                   4419:   double eip;
                   4420: 
                   4421:   pstamp(ficreseij);
                   4422:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4423:   fprintf(ficreseij,"# Age");
                   4424:   for(i=1; i<=nlstate;i++){
                   4425:     for(j=1; j<=nlstate;j++){
                   4426:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4427:     }
                   4428:     fprintf(ficreseij," e%1d. ",i);
                   4429:   }
                   4430:   fprintf(ficreseij,"\n");
                   4431: 
                   4432:   
                   4433:   if(estepm < stepm){
                   4434:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4435:   }
                   4436:   else  hstepm=estepm;   
                   4437:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4438:    * This is mainly to measure the difference between two models: for example
                   4439:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4440:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4441:    * progression in between and thus overestimating or underestimating according
                   4442:    * to the curvature of the survival function. If, for the same date, we 
                   4443:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4444:    * to compare the new estimate of Life expectancy with the same linear 
                   4445:    * hypothesis. A more precise result, taking into account a more precise
                   4446:    * curvature will be obtained if estepm is as small as stepm. */
                   4447: 
                   4448:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4449:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4450:      nhstepm is the number of hstepm from age to agelim 
                   4451:      nstepm is the number of stepm from age to agelin. 
                   4452:      Look at hpijx to understand the reason of that which relies in memory size
                   4453:      and note for a fixed period like estepm months */
                   4454:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4455:      survival function given by stepm (the optimization length). Unfortunately it
                   4456:      means that if the survival funtion is printed only each two years of age and if
                   4457:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4458:      results. So we changed our mind and took the option of the best precision.
                   4459:   */
                   4460:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4461: 
                   4462:   agelim=AGESUP;
                   4463:   /* If stepm=6 months */
                   4464:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4465:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4466:     
                   4467: /* nhstepm age range expressed in number of stepm */
                   4468:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4469:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4470:   /* if (stepm >= YEARM) hstepm=1;*/
                   4471:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4472:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4473: 
                   4474:   for (age=bage; age<=fage; age ++){ 
                   4475:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4476:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4477:     /* if (stepm >= YEARM) hstepm=1;*/
                   4478:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4479: 
                   4480:     /* If stepm=6 months */
                   4481:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4482:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4483:     
                   4484:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4485:     
                   4486:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4487:     
                   4488:     printf("%d|",(int)age);fflush(stdout);
                   4489:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4490:     
                   4491:     /* Computing expectancies */
                   4492:     for(i=1; i<=nlstate;i++)
                   4493:       for(j=1; j<=nlstate;j++)
                   4494:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4495:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4496:          
                   4497:          /* 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]);*/
                   4498: 
                   4499:        }
                   4500: 
                   4501:     fprintf(ficreseij,"%3.0f",age );
                   4502:     for(i=1; i<=nlstate;i++){
                   4503:       eip=0;
                   4504:       for(j=1; j<=nlstate;j++){
                   4505:        eip +=eij[i][j][(int)age];
                   4506:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4507:       }
                   4508:       fprintf(ficreseij,"%9.4f", eip );
                   4509:     }
                   4510:     fprintf(ficreseij,"\n");
                   4511:     
                   4512:   }
                   4513:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4514:   printf("\n");
                   4515:   fprintf(ficlog,"\n");
                   4516:   
                   4517: }
                   4518: 
1.127     brouard  4519: 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  4520: 
                   4521: {
                   4522:   /* Covariances of health expectancies eij and of total life expectancies according
1.222   ! brouard  4523:      to initial status i, ei. .
1.126     brouard  4524:   */
                   4525:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4526:   int nhstepma, nstepma; /* Decreasing with age */
                   4527:   double age, agelim, hf;
                   4528:   double ***p3matp, ***p3matm, ***varhe;
                   4529:   double **dnewm,**doldm;
                   4530:   double *xp, *xm;
                   4531:   double **gp, **gm;
                   4532:   double ***gradg, ***trgradg;
                   4533:   int theta;
                   4534: 
                   4535:   double eip, vip;
                   4536: 
                   4537:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4538:   xp=vector(1,npar);
                   4539:   xm=vector(1,npar);
                   4540:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4541:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4542:   
                   4543:   pstamp(ficresstdeij);
                   4544:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4545:   fprintf(ficresstdeij,"# Age");
                   4546:   for(i=1; i<=nlstate;i++){
                   4547:     for(j=1; j<=nlstate;j++)
                   4548:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4549:     fprintf(ficresstdeij," e%1d. ",i);
                   4550:   }
                   4551:   fprintf(ficresstdeij,"\n");
                   4552: 
                   4553:   pstamp(ficrescveij);
                   4554:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4555:   fprintf(ficrescveij,"# Age");
                   4556:   for(i=1; i<=nlstate;i++)
                   4557:     for(j=1; j<=nlstate;j++){
                   4558:       cptj= (j-1)*nlstate+i;
                   4559:       for(i2=1; i2<=nlstate;i2++)
                   4560:        for(j2=1; j2<=nlstate;j2++){
                   4561:          cptj2= (j2-1)*nlstate+i2;
                   4562:          if(cptj2 <= cptj)
                   4563:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4564:        }
                   4565:     }
                   4566:   fprintf(ficrescveij,"\n");
                   4567:   
                   4568:   if(estepm < stepm){
                   4569:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4570:   }
                   4571:   else  hstepm=estepm;   
                   4572:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4573:    * This is mainly to measure the difference between two models: for example
                   4574:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4575:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4576:    * progression in between and thus overestimating or underestimating according
                   4577:    * to the curvature of the survival function. If, for the same date, we 
                   4578:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4579:    * to compare the new estimate of Life expectancy with the same linear 
                   4580:    * hypothesis. A more precise result, taking into account a more precise
                   4581:    * curvature will be obtained if estepm is as small as stepm. */
                   4582: 
                   4583:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4584:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4585:      nhstepm is the number of hstepm from age to agelim 
                   4586:      nstepm is the number of stepm from age to agelin. 
                   4587:      Look at hpijx to understand the reason of that which relies in memory size
                   4588:      and note for a fixed period like estepm months */
                   4589:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4590:      survival function given by stepm (the optimization length). Unfortunately it
                   4591:      means that if the survival funtion is printed only each two years of age and if
                   4592:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4593:      results. So we changed our mind and took the option of the best precision.
                   4594:   */
                   4595:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4596: 
                   4597:   /* If stepm=6 months */
                   4598:   /* nhstepm age range expressed in number of stepm */
                   4599:   agelim=AGESUP;
                   4600:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4601:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4602:   /* if (stepm >= YEARM) hstepm=1;*/
                   4603:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4604:   
                   4605:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4606:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4607:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4608:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4609:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4610:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4611: 
                   4612:   for (age=bage; age<=fage; age ++){ 
                   4613:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4614:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4615:     /* if (stepm >= YEARM) hstepm=1;*/
                   4616:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  4617:                
1.126     brouard  4618:     /* If stepm=6 months */
                   4619:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4620:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4621:     
                   4622:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  4623:                
1.126     brouard  4624:     /* Computing  Variances of health expectancies */
                   4625:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4626:        decrease memory allocation */
                   4627:     for(theta=1; theta <=npar; theta++){
                   4628:       for(i=1; i<=npar; i++){ 
1.222   ! brouard  4629:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
        !          4630:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  4631:       }
                   4632:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4633:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  4634:                        
1.126     brouard  4635:       for(j=1; j<= nlstate; j++){
1.222   ! brouard  4636:        for(i=1; i<=nlstate; i++){
        !          4637:          for(h=0; h<=nhstepm-1; h++){
        !          4638:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
        !          4639:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
        !          4640:          }
        !          4641:        }
1.126     brouard  4642:       }
1.218     brouard  4643:                        
1.126     brouard  4644:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222   ! brouard  4645:        for(h=0; h<=nhstepm-1; h++){
        !          4646:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
        !          4647:        }
1.126     brouard  4648:     }/* End theta */
                   4649:     
                   4650:     
                   4651:     for(h=0; h<=nhstepm-1; h++)
                   4652:       for(j=1; j<=nlstate*nlstate;j++)
1.222   ! brouard  4653:        for(theta=1; theta <=npar; theta++)
        !          4654:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  4655:     
1.218     brouard  4656:                
1.222   ! brouard  4657:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  4658:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222   ! brouard  4659:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  4660:                
1.222   ! brouard  4661:     printf("%d|",(int)age);fflush(stdout);
        !          4662:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
        !          4663:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  4664:       for(k=0;k<=nhstepm-1;k++){
1.222   ! brouard  4665:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
        !          4666:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
        !          4667:        for(ij=1;ij<=nlstate*nlstate;ij++)
        !          4668:          for(ji=1;ji<=nlstate*nlstate;ji++)
        !          4669:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  4670:       }
                   4671:     }
1.218     brouard  4672:                
1.126     brouard  4673:     /* Computing expectancies */
                   4674:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4675:     for(i=1; i<=nlstate;i++)
                   4676:       for(j=1; j<=nlstate;j++)
1.222   ! brouard  4677:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
        !          4678:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  4679:                                        
1.222   ! brouard  4680:          /* if((int)age==70)printf("i=%2d,j=%2d,h=%2d,age=%3d,%9.4f,%9.4f,%9.4f\n",i,j,h,(int)age,p3mat[i][j][h],hf,eij[i][j][(int)age]);*/
1.218     brouard  4681:                                        
1.222   ! brouard  4682:        }
1.218     brouard  4683:                
1.126     brouard  4684:     fprintf(ficresstdeij,"%3.0f",age );
                   4685:     for(i=1; i<=nlstate;i++){
                   4686:       eip=0.;
                   4687:       vip=0.;
                   4688:       for(j=1; j<=nlstate;j++){
1.222   ! brouard  4689:        eip += eij[i][j][(int)age];
        !          4690:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
        !          4691:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
        !          4692:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
1.126     brouard  4693:       }
                   4694:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4695:     }
                   4696:     fprintf(ficresstdeij,"\n");
1.218     brouard  4697:                
1.126     brouard  4698:     fprintf(ficrescveij,"%3.0f",age );
                   4699:     for(i=1; i<=nlstate;i++)
                   4700:       for(j=1; j<=nlstate;j++){
1.222   ! brouard  4701:        cptj= (j-1)*nlstate+i;
        !          4702:        for(i2=1; i2<=nlstate;i2++)
        !          4703:          for(j2=1; j2<=nlstate;j2++){
        !          4704:            cptj2= (j2-1)*nlstate+i2;
        !          4705:            if(cptj2 <= cptj)
        !          4706:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
        !          4707:          }
1.126     brouard  4708:       }
                   4709:     fprintf(ficrescveij,"\n");
1.218     brouard  4710:                
1.126     brouard  4711:   }
                   4712:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4713:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4714:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4715:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4716:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4717:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4718:   printf("\n");
                   4719:   fprintf(ficlog,"\n");
1.218     brouard  4720:        
1.126     brouard  4721:   free_vector(xm,1,npar);
                   4722:   free_vector(xp,1,npar);
                   4723:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4724:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4725:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4726: }
1.218     brouard  4727:  
1.126     brouard  4728: /************ Variance ******************/
1.209     brouard  4729:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.218     brouard  4730:  {
                   4731:    /* Variance of health expectancies */
                   4732:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4733:    /* double **newm;*/
                   4734:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4735:   
                   4736:    /* int movingaverage(); */
                   4737:    double **dnewm,**doldm;
                   4738:    double **dnewmp,**doldmp;
                   4739:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4740:    int k;
                   4741:    double *xp;
                   4742:    double **gp, **gm;  /* for var eij */
                   4743:    double ***gradg, ***trgradg; /*for var eij */
                   4744:    double **gradgp, **trgradgp; /* for var p point j */
                   4745:    double *gpp, *gmp; /* for var p point j */
                   4746:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4747:    double ***p3mat;
                   4748:    double age,agelim, hf;
                   4749:    /* double ***mobaverage; */
                   4750:    int theta;
                   4751:    char digit[4];
                   4752:    char digitp[25];
                   4753: 
                   4754:    char fileresprobmorprev[FILENAMELENGTH];
                   4755: 
                   4756:    if(popbased==1){
                   4757:      if(mobilav!=0)
                   4758:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4759:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4760:    }
                   4761:    else 
                   4762:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  4763: 
1.218     brouard  4764:    /* if (mobilav!=0) { */
                   4765:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4766:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4767:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4768:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4769:    /*   } */
                   4770:    /* } */
                   4771: 
                   4772:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4773:    sprintf(digit,"%-d",ij);
                   4774:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4775:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4776:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4777:    strcat(fileresprobmorprev,fileresu);
                   4778:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4779:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4780:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4781:    }
                   4782:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4783:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4784:    pstamp(ficresprobmorprev);
                   4785:    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);
                   4786:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4787:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4788:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4789:      for(i=1; i<=nlstate;i++)
                   4790:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4791:    }  
                   4792:    fprintf(ficresprobmorprev,"\n");
                   4793:   
                   4794:    fprintf(ficgp,"\n# Routine varevsij");
                   4795:    fprintf(ficgp,"\nunset title \n");
                   4796:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4797:    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");
                   4798:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4799:    /*   } */
                   4800:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4801:    pstamp(ficresvij);
                   4802:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4803:    if(popbased==1)
                   4804:      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);
                   4805:    else
                   4806:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4807:    fprintf(ficresvij,"# Age");
                   4808:    for(i=1; i<=nlstate;i++)
                   4809:      for(j=1; j<=nlstate;j++)
                   4810:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4811:    fprintf(ficresvij,"\n");
                   4812: 
                   4813:    xp=vector(1,npar);
                   4814:    dnewm=matrix(1,nlstate,1,npar);
                   4815:    doldm=matrix(1,nlstate,1,nlstate);
                   4816:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4817:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4818: 
                   4819:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4820:    gpp=vector(nlstate+1,nlstate+ndeath);
                   4821:    gmp=vector(nlstate+1,nlstate+ndeath);
                   4822:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  4823:   
1.218     brouard  4824:    if(estepm < stepm){
                   4825:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   4826:    }
                   4827:    else  hstepm=estepm;   
                   4828:    /* For example we decided to compute the life expectancy with the smallest unit */
                   4829:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4830:       nhstepm is the number of hstepm from age to agelim 
                   4831:       nstepm is the number of stepm from age to agelim. 
                   4832:       Look at function hpijx to understand why because of memory size limitations, 
                   4833:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   4834:       survival function given by stepm (the optimization length). Unfortunately it
                   4835:       means that if the survival funtion is printed every two years of age and if
                   4836:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4837:       results. So we changed our mind and took the option of the best precision.
                   4838:    */
                   4839:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4840:    agelim = AGESUP;
                   4841:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4842:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4843:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4844:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4845:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4846:      gp=matrix(0,nhstepm,1,nlstate);
                   4847:      gm=matrix(0,nhstepm,1,nlstate);
                   4848:                
                   4849:                
                   4850:      for(theta=1; theta <=npar; theta++){
                   4851:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4852:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4853:        }
                   4854:                        
                   4855:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4856:                        
                   4857:        if (popbased==1) {
                   4858:         if(mobilav ==0){
                   4859:           for(i=1; i<=nlstate;i++)
                   4860:             prlim[i][i]=probs[(int)age][i][ij];
                   4861:         }else{ /* mobilav */ 
                   4862:           for(i=1; i<=nlstate;i++)
                   4863:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4864:         }
                   4865:        }
                   4866:                        
                   4867:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   4868:        for(j=1; j<= nlstate; j++){
                   4869:         for(h=0; h<=nhstepm; h++){
                   4870:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4871:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4872:         }
                   4873:        }
                   4874:        /* Next for computing probability of death (h=1 means
                   4875:          computed over hstepm matrices product = hstepm*stepm months) 
                   4876:          as a weighted average of prlim.
                   4877:        */
                   4878:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4879:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4880:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4881:        }    
                   4882:        /* end probability of death */
                   4883:                        
                   4884:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4885:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4886:                        
                   4887:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   4888:                        
                   4889:        if (popbased==1) {
                   4890:         if(mobilav ==0){
                   4891:           for(i=1; i<=nlstate;i++)
                   4892:             prlim[i][i]=probs[(int)age][i][ij];
                   4893:         }else{ /* mobilav */ 
                   4894:           for(i=1; i<=nlstate;i++)
                   4895:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4896:         }
                   4897:        }
                   4898:                        
                   4899:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4900:                        
                   4901:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   4902:         for(h=0; h<=nhstepm; h++){
                   4903:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4904:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4905:         }
                   4906:        }
                   4907:        /* This for computing probability of death (h=1 means
                   4908:          computed over hstepm matrices product = hstepm*stepm months) 
                   4909:          as a weighted average of prlim.
                   4910:        */
                   4911:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4912:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4913:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4914:        }    
                   4915:        /* end probability of death */
                   4916:                        
                   4917:        for(j=1; j<= nlstate; j++) /* vareij */
                   4918:         for(h=0; h<=nhstepm; h++){
                   4919:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4920:         }
                   4921:                        
                   4922:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4923:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4924:        }
                   4925:                        
                   4926:      } /* End theta */
                   4927:                
                   4928:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4929:                
                   4930:      for(h=0; h<=nhstepm; h++) /* veij */
                   4931:        for(j=1; j<=nlstate;j++)
                   4932:         for(theta=1; theta <=npar; theta++)
                   4933:           trgradg[h][j][theta]=gradg[h][theta][j];
                   4934:                
                   4935:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4936:        for(theta=1; theta <=npar; theta++)
                   4937:         trgradgp[j][theta]=gradgp[theta][j];
                   4938:                
                   4939:                
                   4940:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4941:      for(i=1;i<=nlstate;i++)
                   4942:        for(j=1;j<=nlstate;j++)
                   4943:         vareij[i][j][(int)age] =0.;
                   4944:                
                   4945:      for(h=0;h<=nhstepm;h++){
                   4946:        for(k=0;k<=nhstepm;k++){
                   4947:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4948:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4949:         for(i=1;i<=nlstate;i++)
                   4950:           for(j=1;j<=nlstate;j++)
                   4951:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4952:        }
                   4953:      }
                   4954:                
                   4955:      /* pptj */
                   4956:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4957:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4958:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4959:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4960:         varppt[j][i]=doldmp[j][i];
                   4961:      /* end ppptj */
                   4962:      /*  x centered again */
                   4963:                
                   4964:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4965:                
                   4966:      if (popbased==1) {
                   4967:        if(mobilav ==0){
                   4968:         for(i=1; i<=nlstate;i++)
                   4969:           prlim[i][i]=probs[(int)age][i][ij];
                   4970:        }else{ /* mobilav */ 
                   4971:         for(i=1; i<=nlstate;i++)
                   4972:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   4973:        }
                   4974:      }
                   4975:                
                   4976:      /* This for computing probability of death (h=1 means
                   4977:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4978:        as a weighted average of prlim.
                   4979:      */
                   4980:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4981:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4982:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4983:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4984:      }    
                   4985:      /* end probability of death */
                   4986:                
                   4987:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4988:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4989:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4990:        for(i=1; i<=nlstate;i++){
                   4991:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4992:        }
                   4993:      } 
                   4994:      fprintf(ficresprobmorprev,"\n");
                   4995:                
                   4996:      fprintf(ficresvij,"%.0f ",age );
                   4997:      for(i=1; i<=nlstate;i++)
                   4998:        for(j=1; j<=nlstate;j++){
                   4999:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5000:        }
                   5001:      fprintf(ficresvij,"\n");
                   5002:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5003:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5004:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5005:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5006:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5007:    } /* End age */
                   5008:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5009:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5010:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5011:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5012:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5013:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5014:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5015:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5016:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5017:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5018:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5019:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5020:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5021:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5022:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5023:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5024:    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);
                   5025:    /*  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  5026:     */
1.218     brouard  5027:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5028:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5029: 
1.218     brouard  5030:    free_vector(xp,1,npar);
                   5031:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5032:    free_matrix(dnewm,1,nlstate,1,npar);
                   5033:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5034:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5035:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5036:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5037:    fclose(ficresprobmorprev);
                   5038:    fflush(ficgp);
                   5039:    fflush(fichtm); 
                   5040:  }  /* end varevsij */
1.126     brouard  5041: 
                   5042: /************ Variance of prevlim ******************/
1.209     brouard  5043:  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  5044: {
1.205     brouard  5045:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5046:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5047: 
1.126     brouard  5048:   double **dnewm,**doldm;
                   5049:   int i, j, nhstepm, hstepm;
                   5050:   double *xp;
                   5051:   double *gp, *gm;
                   5052:   double **gradg, **trgradg;
1.208     brouard  5053:   double **mgm, **mgp;
1.126     brouard  5054:   double age,agelim;
                   5055:   int theta;
                   5056:   
                   5057:   pstamp(ficresvpl);
                   5058:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5059:   fprintf(ficresvpl,"# Age");
                   5060:   for(i=1; i<=nlstate;i++)
                   5061:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5062:   fprintf(ficresvpl,"\n");
                   5063: 
                   5064:   xp=vector(1,npar);
                   5065:   dnewm=matrix(1,nlstate,1,npar);
                   5066:   doldm=matrix(1,nlstate,1,nlstate);
                   5067:   
                   5068:   hstepm=1*YEARM; /* Every year of age */
                   5069:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5070:   agelim = AGESUP;
                   5071:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5072:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5073:     if (stepm >= YEARM) hstepm=1;
                   5074:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5075:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5076:     mgp=matrix(1,npar,1,nlstate);
                   5077:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5078:     gp=vector(1,nlstate);
                   5079:     gm=vector(1,nlstate);
                   5080: 
                   5081:     for(theta=1; theta <=npar; theta++){
                   5082:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5083:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5084:       }
1.209     brouard  5085:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5086:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5087:       else
                   5088:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5089:       for(i=1;i<=nlstate;i++){
1.126     brouard  5090:        gp[i] = prlim[i][i];
1.208     brouard  5091:        mgp[theta][i] = prlim[i][i];
                   5092:       }
1.126     brouard  5093:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5094:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5095:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5096:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5097:       else
                   5098:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5099:       for(i=1;i<=nlstate;i++){
1.126     brouard  5100:        gm[i] = prlim[i][i];
1.208     brouard  5101:        mgm[theta][i] = prlim[i][i];
                   5102:       }
1.126     brouard  5103:       for(i=1;i<=nlstate;i++)
                   5104:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5105:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5106:     } /* End theta */
                   5107: 
                   5108:     trgradg =matrix(1,nlstate,1,npar);
                   5109: 
                   5110:     for(j=1; j<=nlstate;j++)
                   5111:       for(theta=1; theta <=npar; theta++)
                   5112:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5113:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5114:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5115:     /*   for(j=1; j<=nlstate;j++){ */
                   5116:     /*         printf(" %d ",j); */
                   5117:     /*         for(theta=1; theta <=npar; theta++) */
                   5118:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5119:     /*         printf("\n "); */
                   5120:     /*   } */
                   5121:     /* } */
                   5122:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5123:     /*   printf("\n gradg %d ",(int)age); */
                   5124:     /*   for(j=1; j<=nlstate;j++){ */
                   5125:     /*         printf("%d ",j); */
                   5126:     /*         for(theta=1; theta <=npar; theta++) */
                   5127:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5128:     /*         printf("\n "); */
                   5129:     /*   } */
                   5130:     /* } */
1.126     brouard  5131: 
                   5132:     for(i=1;i<=nlstate;i++)
                   5133:       varpl[i][(int)age] =0.;
1.209     brouard  5134:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5135:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5136:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5137:     }else{
1.126     brouard  5138:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5139:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5140:     }
1.126     brouard  5141:     for(i=1;i<=nlstate;i++)
                   5142:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5143: 
                   5144:     fprintf(ficresvpl,"%.0f ",age );
                   5145:     for(i=1; i<=nlstate;i++)
                   5146:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5147:     fprintf(ficresvpl,"\n");
                   5148:     free_vector(gp,1,nlstate);
                   5149:     free_vector(gm,1,nlstate);
1.208     brouard  5150:     free_matrix(mgm,1,npar,1,nlstate);
                   5151:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5152:     free_matrix(gradg,1,npar,1,nlstate);
                   5153:     free_matrix(trgradg,1,nlstate,1,npar);
                   5154:   } /* End age */
                   5155: 
                   5156:   free_vector(xp,1,npar);
                   5157:   free_matrix(doldm,1,nlstate,1,npar);
                   5158:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5159: 
                   5160: }
                   5161: 
                   5162: /************ Variance of one-step probabilities  ******************/
                   5163: void varprob(char optionfilefiname[], double **matcov, double x[], double delti[], int nlstate, double bage, double fage, int ij, int *Tvar, int **nbcode, int *ncodemax, char strstart[])
1.222   ! brouard  5164:  {
        !          5165:    int i, j=0,  k1, l1, tj;
        !          5166:    int k2, l2, j1,  z1;
        !          5167:    int k=0, l;
        !          5168:    int first=1, first1, first2;
        !          5169:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
        !          5170:    double **dnewm,**doldm;
        !          5171:    double *xp;
        !          5172:    double *gp, *gm;
        !          5173:    double **gradg, **trgradg;
        !          5174:    double **mu;
        !          5175:    double age, cov[NCOVMAX+1];
        !          5176:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
        !          5177:    int theta;
        !          5178:    char fileresprob[FILENAMELENGTH];
        !          5179:    char fileresprobcov[FILENAMELENGTH];
        !          5180:    char fileresprobcor[FILENAMELENGTH];
        !          5181:    double ***varpij;
        !          5182: 
        !          5183:    strcpy(fileresprob,"PROB_"); 
        !          5184:    strcat(fileresprob,fileres);
        !          5185:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
        !          5186:      printf("Problem with resultfile: %s\n", fileresprob);
        !          5187:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
        !          5188:    }
        !          5189:    strcpy(fileresprobcov,"PROBCOV_"); 
        !          5190:    strcat(fileresprobcov,fileresu);
        !          5191:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
        !          5192:      printf("Problem with resultfile: %s\n", fileresprobcov);
        !          5193:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
        !          5194:    }
        !          5195:    strcpy(fileresprobcor,"PROBCOR_"); 
        !          5196:    strcat(fileresprobcor,fileresu);
        !          5197:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
        !          5198:      printf("Problem with resultfile: %s\n", fileresprobcor);
        !          5199:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
        !          5200:    }
        !          5201:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
        !          5202:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
        !          5203:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
        !          5204:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
        !          5205:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
        !          5206:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
        !          5207:    pstamp(ficresprob);
        !          5208:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
        !          5209:    fprintf(ficresprob,"# Age");
        !          5210:    pstamp(ficresprobcov);
        !          5211:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
        !          5212:    fprintf(ficresprobcov,"# Age");
        !          5213:    pstamp(ficresprobcor);
        !          5214:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
        !          5215:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5216: 
                   5217: 
1.222   ! brouard  5218:    for(i=1; i<=nlstate;i++)
        !          5219:      for(j=1; j<=(nlstate+ndeath);j++){
        !          5220:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
        !          5221:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
        !          5222:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
        !          5223:      }  
        !          5224:    /* fprintf(ficresprob,"\n");
        !          5225:       fprintf(ficresprobcov,"\n");
        !          5226:       fprintf(ficresprobcor,"\n");
        !          5227:    */
        !          5228:    xp=vector(1,npar);
        !          5229:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        !          5230:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
        !          5231:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
        !          5232:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
        !          5233:    first=1;
        !          5234:    fprintf(ficgp,"\n# Routine varprob");
        !          5235:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
        !          5236:    fprintf(fichtm,"\n");
        !          5237: 
        !          5238:    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);
        !          5239:    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);
        !          5240:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5241: and drawn. It helps understanding how is the covariance between two incidences.\
                   5242:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222   ! brouard  5243:    fprintf(fichtmcov,"\n<br> Contour plot corresponding to x'cov<sup>-1</sup>x = 4 (where x is the column vector (pij,pkl)) are drawn. \
1.126     brouard  5244: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5245: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5246: standard deviations wide on each axis. <br>\
                   5247:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5248:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5249: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5250: 
1.222   ! brouard  5251:    cov[1]=1;
        !          5252:    /* tj=cptcoveff; */
        !          5253:    tj = (int) pow(2,cptcoveff);
        !          5254:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
        !          5255:    j1=0;
        !          5256:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates */
        !          5257:      if  (cptcovn>0) {
        !          5258:        fprintf(ficresprob, "\n#********** Variable "); 
        !          5259:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          5260:        fprintf(ficresprob, "**********\n#\n");
        !          5261:        fprintf(ficresprobcov, "\n#********** Variable "); 
        !          5262:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          5263:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5264:                        
1.222   ! brouard  5265:        fprintf(ficgp, "\n#********** Variable "); 
        !          5266:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          5267:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5268:                        
                   5269:                        
1.222   ! brouard  5270:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
        !          5271:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          5272:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5273:                        
1.222   ! brouard  5274:        fprintf(ficresprobcor, "\n#********** Variable ");    
        !          5275:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          5276:        fprintf(ficresprobcor, "**********\n#");    
        !          5277:        if(invalidvarcomb[j1]){
        !          5278:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
        !          5279:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
        !          5280:         continue;
        !          5281:        }
        !          5282:      }
        !          5283:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
        !          5284:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        !          5285:      gp=vector(1,(nlstate)*(nlstate+ndeath));
        !          5286:      gm=vector(1,(nlstate)*(nlstate+ndeath));
        !          5287:      for (age=bage; age<=fage; age ++){ 
        !          5288:        cov[2]=age;
        !          5289:        if(nagesqr==1)
        !          5290:         cov[3]= age*age;
        !          5291:        for (k=1; k<=cptcovn;k++) {
        !          5292:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
        !          5293:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
        !          5294:                                                                    * 1  1 1 1 1
        !          5295:                                                                    * 2  2 1 1 1
        !          5296:                                                                    * 3  1 2 1 1
        !          5297:                                                                    */
        !          5298:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
        !          5299:        }
        !          5300:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          5301:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
        !          5302:        for (k=1; k<=cptcovprod;k++)
        !          5303:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5304:                        
                   5305:                        
1.222   ! brouard  5306:        for(theta=1; theta <=npar; theta++){
        !          5307:         for(i=1; i<=npar; i++)
        !          5308:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5309:                                
1.222   ! brouard  5310:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5311:                                
1.222   ! brouard  5312:         k=0;
        !          5313:         for(i=1; i<= (nlstate); i++){
        !          5314:           for(j=1; j<=(nlstate+ndeath);j++){
        !          5315:             k=k+1;
        !          5316:             gp[k]=pmmij[i][j];
        !          5317:           }
        !          5318:         }
1.220     brouard  5319:                                
1.222   ! brouard  5320:         for(i=1; i<=npar; i++)
        !          5321:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5322:                                
1.222   ! brouard  5323:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
        !          5324:         k=0;
        !          5325:         for(i=1; i<=(nlstate); i++){
        !          5326:           for(j=1; j<=(nlstate+ndeath);j++){
        !          5327:             k=k+1;
        !          5328:             gm[k]=pmmij[i][j];
        !          5329:           }
        !          5330:         }
1.220     brouard  5331:                                
1.222   ! brouard  5332:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
        !          5333:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
        !          5334:        }
1.126     brouard  5335: 
1.222   ! brouard  5336:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
        !          5337:         for(theta=1; theta <=npar; theta++)
        !          5338:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5339:                        
1.222   ! brouard  5340:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
        !          5341:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5342:                        
1.222   ! brouard  5343:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5344:                        
1.222   ! brouard  5345:        k=0;
        !          5346:        for(i=1; i<=(nlstate); i++){
        !          5347:         for(j=1; j<=(nlstate+ndeath);j++){
        !          5348:           k=k+1;
        !          5349:           mu[k][(int) age]=pmmij[i][j];
        !          5350:         }
        !          5351:        }
        !          5352:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
        !          5353:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
        !          5354:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5355:                        
1.222   ! brouard  5356:        /*printf("\n%d ",(int)age);
        !          5357:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        !          5358:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
        !          5359:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
        !          5360:         }*/
1.220     brouard  5361:                        
1.222   ! brouard  5362:        fprintf(ficresprob,"\n%d ",(int)age);
        !          5363:        fprintf(ficresprobcov,"\n%d ",(int)age);
        !          5364:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5365:                        
1.222   ! brouard  5366:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
        !          5367:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
        !          5368:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        !          5369:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
        !          5370:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
        !          5371:        }
        !          5372:        i=0;
        !          5373:        for (k=1; k<=(nlstate);k++){
        !          5374:         for (l=1; l<=(nlstate+ndeath);l++){ 
        !          5375:           i++;
        !          5376:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
        !          5377:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
        !          5378:           for (j=1; j<=i;j++){
        !          5379:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
        !          5380:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
        !          5381:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
        !          5382:           }
        !          5383:         }
        !          5384:        }/* end of loop for state */
        !          5385:      } /* end of loop for age */
        !          5386:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
        !          5387:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
        !          5388:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
        !          5389:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
        !          5390:     
        !          5391:      /* Confidence intervalle of pij  */
        !          5392:      /*
        !          5393:        fprintf(ficgp,"\nunset parametric;unset label");
        !          5394:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
        !          5395:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
        !          5396:        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);
        !          5397:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
        !          5398:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
        !          5399:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
        !          5400:      */
        !          5401:                
        !          5402:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
        !          5403:      first1=1;first2=2;
        !          5404:      for (k2=1; k2<=(nlstate);k2++){
        !          5405:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
        !          5406:         if(l2==k2) continue;
        !          5407:         j=(k2-1)*(nlstate+ndeath)+l2;
        !          5408:         for (k1=1; k1<=(nlstate);k1++){
        !          5409:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
        !          5410:             if(l1==k1) continue;
        !          5411:             i=(k1-1)*(nlstate+ndeath)+l1;
        !          5412:             if(i<=j) continue;
        !          5413:             for (age=bage; age<=fage; age ++){ 
        !          5414:               if ((int)age %5==0){
        !          5415:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
        !          5416:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
        !          5417:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
        !          5418:                 mu1=mu[i][(int) age]/stepm*YEARM ;
        !          5419:                 mu2=mu[j][(int) age]/stepm*YEARM;
        !          5420:                 c12=cv12/sqrt(v1*v2);
        !          5421:                 /* Computing eigen value of matrix of covariance */
        !          5422:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          5423:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          5424:                 if ((lc2 <0) || (lc1 <0) ){
        !          5425:                   if(first2==1){
        !          5426:                     first1=0;
        !          5427:                     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);
        !          5428:                   }
        !          5429:                   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);
        !          5430:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
        !          5431:                   /* lc2=fabs(lc2); */
        !          5432:                 }
1.220     brouard  5433:                                                                
1.222   ! brouard  5434:                 /* Eigen vectors */
        !          5435:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
        !          5436:                 /*v21=sqrt(1.-v11*v11); *//* error */
        !          5437:                 v21=(lc1-v1)/cv12*v11;
        !          5438:                 v12=-v21;
        !          5439:                 v22=v11;
        !          5440:                 tnalp=v21/v11;
        !          5441:                 if(first1==1){
        !          5442:                   first1=0;
        !          5443:                   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);
        !          5444:                 }
        !          5445:                 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);
        !          5446:                 /*printf(fignu*/
        !          5447:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
        !          5448:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
        !          5449:                 if(first==1){
        !          5450:                   first=0;
        !          5451:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
        !          5452:                   fprintf(ficgp,"\nset parametric;unset label");
        !          5453:                   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);
        !          5454:                   fprintf(ficgp,"\nset ter svg size 640, 480");
        !          5455:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5456:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5457: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222   ! brouard  5458:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
        !          5459:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
        !          5460:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
        !          5461:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
        !          5462:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
        !          5463:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
        !          5464:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
        !          5465:                   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",      \
        !          5466:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
        !          5467:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
        !          5468:                 }else{
        !          5469:                   first=0;
        !          5470:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
        !          5471:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
        !          5472:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
        !          5473:                   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", \
        !          5474:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
        !          5475:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
        !          5476:                 }/* if first */
        !          5477:               } /* age mod 5 */
        !          5478:             } /* end loop age */
        !          5479:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
        !          5480:             first=1;
        !          5481:           } /*l12 */
        !          5482:         } /* k12 */
        !          5483:        } /*l1 */
        !          5484:      }/* k1 */
        !          5485:    }  /* loop on combination of covariates j1 */
        !          5486:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
        !          5487:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
        !          5488:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
        !          5489:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
        !          5490:    free_vector(xp,1,npar);
        !          5491:    fclose(ficresprob);
        !          5492:    fclose(ficresprobcov);
        !          5493:    fclose(ficresprobcor);
        !          5494:    fflush(ficgp);
        !          5495:    fflush(fichtmcov);
        !          5496:  }
1.126     brouard  5497: 
                   5498: 
                   5499: /******************* Printing html file ***********/
1.201     brouard  5500: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5501:                  int lastpass, int stepm, int weightopt, char model[],\
                   5502:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5503:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5504:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5505:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5506:   int jj1, k1, i1, cpt;
                   5507: 
                   5508:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5509:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5510: </ul>");
1.214     brouard  5511:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5512:    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",
                   5513:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5514:    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  5515:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5516:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5517:    fprintf(fichtm,"\
                   5518:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5519:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5520:    fprintf(fichtm,"\
1.217     brouard  5521:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5522:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5523:    fprintf(fichtm,"\
1.126     brouard  5524:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5525:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5526:    fprintf(fichtm,"\
1.217     brouard  5527:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5528:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5529:    fprintf(fichtm,"\
1.211     brouard  5530:  - (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  5531:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5532:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5533:    if(prevfcast==1){
                   5534:      fprintf(fichtm,"\
                   5535:  - Prevalence projections by age and states:                           \
1.201     brouard  5536:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5537:    }
1.126     brouard  5538: 
1.222   ! brouard  5539:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  5540: 
1.222   ! brouard  5541:    m=pow(2,cptcoveff);
        !          5542:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5543: 
1.222   ! brouard  5544:    jj1=0;
        !          5545:    for(k1=1; k1<=m;k1++){
1.220     brouard  5546: 
1.222   ! brouard  5547:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
        !          5548:      jj1++;
        !          5549:      if (cptcovn > 0) {
        !          5550:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
        !          5551:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
        !          5552:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
        !          5553:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
        !          5554:        }
        !          5555:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        !          5556:        if(invalidvarcomb[k1]){
        !          5557:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
        !          5558:         printf("\nCombination (%d) ignored because no cases \n",k1); 
        !          5559:         continue;
        !          5560:        }
        !          5561:      }
        !          5562:      /* aij, bij */
        !          5563:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
1.211     brouard  5564: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222   ! brouard  5565:      /* Pij */
        !          5566:      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  5567: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222   ! brouard  5568:      /* Quasi-incidences */
        !          5569:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.220     brouard  5570:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  5571:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5572: 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  5573: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222   ! brouard  5574:      /* Survival functions (period) in state j */
        !          5575:      for(cpt=1; cpt<=nlstate;cpt++){
        !          5576:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
1.201     brouard  5577: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
1.222   ! brouard  5578:      }
        !          5579:      /* State specific survival functions (period) */
        !          5580:      for(cpt=1; cpt<=nlstate;cpt++){
        !          5581:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  5582:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  5583:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
1.222   ! brouard  5584:      }
        !          5585:      /* Period (stable) prevalence in each health state */
        !          5586:      for(cpt=1; cpt<=nlstate;cpt++){
        !          5587:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
1.201     brouard  5588: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
1.222   ! brouard  5589:      }
        !          5590:      if(backcast==1){
        !          5591:        /* Period (stable) back prevalence in each health state */
        !          5592:        for(cpt=1; cpt<=nlstate;cpt++){
        !          5593:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
1.217     brouard  5594: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
1.222   ! brouard  5595:        }
1.217     brouard  5596:      }
1.222   ! brouard  5597:      if(prevfcast==1){
        !          5598:        /* Projection of prevalence up to period (stable) prevalence in each health state */
        !          5599:        for(cpt=1; cpt<=nlstate;cpt++){
        !          5600:         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  5601: <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.222   ! brouard  5602:        }
        !          5603:      }
1.220     brouard  5604:         
1.222   ! brouard  5605:      for(cpt=1; cpt<=nlstate;cpt++) {
        !          5606:        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  5607: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.222   ! brouard  5608:      }
        !          5609:      /* } /\* end i1 *\/ */
        !          5610:    }/* End k1 */
        !          5611:    fprintf(fichtm,"</ul>");
1.126     brouard  5612: 
1.222   ! brouard  5613:    fprintf(fichtm,"\
1.126     brouard  5614: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5615:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5616:  - 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  5617: But because parameters are usually highly correlated (a higher incidence of disability \
                   5618: and a higher incidence of recovery can give very close observed transition) it might \
                   5619: be very useful to look not only at linear confidence intervals estimated from the \
                   5620: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5621: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5622: covariance matrix of the one-step probabilities. \
                   5623: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5624: 
1.222   ! brouard  5625:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        !          5626:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
        !          5627:    fprintf(fichtm,"\
1.126     brouard  5628:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222   ! brouard  5629:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5630: 
1.222   ! brouard  5631:    fprintf(fichtm,"\
1.126     brouard  5632:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222   ! brouard  5633:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
        !          5634:    fprintf(fichtm,"\
1.126     brouard  5635:  - 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): \
                   5636:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5637:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222   ! brouard  5638:    fprintf(fichtm,"\
1.126     brouard  5639:  - (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): \
                   5640:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5641:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222   ! brouard  5642:    fprintf(fichtm,"\
1.128     brouard  5643:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.222   ! brouard  5644:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
        !          5645:    fprintf(fichtm,"\
1.128     brouard  5646:  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
1.222   ! brouard  5647:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
        !          5648:    fprintf(fichtm,"\
1.126     brouard  5649:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222   ! brouard  5650:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5651: 
                   5652: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5653: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5654: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5655: /*     <br>",fileres,fileres,fileres,fileres); */
                   5656: /*  else  */
                   5657: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222   ! brouard  5658:    fflush(fichtm);
        !          5659:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  5660: 
1.222   ! brouard  5661:    m=pow(2,cptcoveff);
        !          5662:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5663: 
1.222   ! brouard  5664:    jj1=0;
        !          5665:    for(k1=1; k1<=m;k1++){
        !          5666:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
        !          5667:      jj1++;
1.126     brouard  5668:      if (cptcovn > 0) {
                   5669:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5670:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.222   ! brouard  5671:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5672:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5673: 
1.222   ! brouard  5674:        if(invalidvarcomb[k1]){
        !          5675:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
        !          5676:         continue;
        !          5677:        }
1.126     brouard  5678:      }
                   5679:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  5680:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5681: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  5682: <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  5683:      }
                   5684:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5685: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5686: true period expectancies (those weighted with period prevalences are also\
                   5687:  drawn in addition to the population based expectancies computed using\
1.218     brouard  5688:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  5689: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222   ! brouard  5690:      /* } /\* end i1 *\/ */
        !          5691:    }/* End k1 */
        !          5692:    fprintf(fichtm,"</ul>");
        !          5693:    fflush(fichtm);
1.126     brouard  5694: }
                   5695: 
                   5696: /******************* Gnuplot file **************/
1.218     brouard  5697:  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  5698: 
                   5699:   char dirfileres[132],optfileres[132];
1.220     brouard  5700:        char gplotcondition[132];
1.164     brouard  5701:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5702:   int lv=0, vlv=0, kl=0;
1.130     brouard  5703:   int ng=0;
1.201     brouard  5704:   int vpopbased;
1.219     brouard  5705:        int ioffset; /* variable offset for columns */
                   5706: 
1.126     brouard  5707: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5708: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5709: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5710: /*   } */
                   5711: 
                   5712:   /*#ifdef windows */
                   5713:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5714:     /*#endif */
                   5715:   m=pow(2,cptcoveff);
                   5716: 
1.202     brouard  5717:   /* Contribution to likelihood */
                   5718:   /* Plot the probability implied in the likelihood */
                   5719:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5720:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5721:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5722:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5723: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5724:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5725: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5726:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5727:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5728:     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  5729:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5730:     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  5731:     for (i=1; i<= nlstate ; i ++) {
                   5732:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5733:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5734:       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  5735:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.219     brouard  5736:                                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  5737:       }
                   5738:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5739:     }
                   5740:     /* 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 */             
                   5741:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5742:     /* 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  5743:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5744:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5745: 
1.126     brouard  5746:   strcpy(dirfileres,optionfilefiname);
                   5747:   strcpy(optfileres,"vpl");
                   5748:  /* 1eme*/
1.211     brouard  5749:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.220     brouard  5750:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
1.211     brouard  5751:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5752:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.219     brouard  5753:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   5754:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   5755:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5756:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5757:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5758:                                vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   5759:                        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.220     brouard  5760:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5761:       }
                   5762:       fprintf(ficgp,"\n#\n");
1.220     brouard  5763:                        if(invalidvarcomb[k1]){
                   5764:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5765:                                                continue;
                   5766:                        }
1.211     brouard  5767: 
1.219     brouard  5768:                        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5769:                        fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   5770:                        fprintf(ficgp,"set xlabel \"Age\" \n\
                   5771: set ylabel \"Probability\" \n  \
                   5772: set ter svg size 640, 480\n    \
1.201     brouard  5773: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219     brouard  5774:                        
                   5775:                        for (i=1; i<= nlstate ; i ++) {
                   5776:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5777:                                else        fprintf(ficgp," %%*lf (%%*lf)");
                   5778:                        }
                   5779:                        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);
                   5780:                        for (i=1; i<= nlstate ; i ++) {
                   5781:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5782:                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5783:                        } 
                   5784:                        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); 
                   5785:                        for (i=1; i<= nlstate ; i ++) {
                   5786:                                if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5787:                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5788:                        }  
                   5789:                        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));
                   5790:                        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   5791:                                /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
                   5792:                                fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
                   5793:                                kl=0;
                   5794:                                for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   5795:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5796:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5797:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5798:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5799:                                        vlv= nbcode[Tvaraff[k]][lv];
                   5800:                                        kl++;
                   5801:                                        /* 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 *\/ */
                   5802:                                        /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5803:                                        /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5804:                                        /* ''  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*/
                   5805:                                        if(k==cptcoveff){
1.220     brouard  5806:                                                        fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   5807:                                                                                        6+(cpt-1),  cpt );
1.219     brouard  5808:                                        }else{
1.220     brouard  5809:                                                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
1.219     brouard  5810:                                                kl++;
                   5811:                                        }
                   5812:                                } /* end covariate */
                   5813:                        }
                   5814:                        fprintf(ficgp,"\nset out \n");
1.201     brouard  5815:     } /* k1 */
                   5816:   } /* cpt */
1.126     brouard  5817:   /*2 eme*/
                   5818:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5819: 
1.211     brouard  5820:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5821:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219     brouard  5822:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5823:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5824:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5825:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5826:                                vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  5827:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5828:       }
                   5829:       fprintf(ficgp,"\n#\n");
1.220     brouard  5830:                        if(invalidvarcomb[k1]){
                   5831:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5832:                                                continue;
                   5833:                        }
1.219     brouard  5834:                        
                   5835:                        fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5836:                        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5837:                                if(vpopbased==0)
                   5838:                                        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5839:                                else
                   5840:                                        fprintf(ficgp,"\nreplot ");
                   5841:                                for (i=1; i<= nlstate+1 ; i ++) {
                   5842:                                        k=2*i;
                   5843:                                        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);
                   5844:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5845:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5846:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5847:                                        }   
                   5848:                                        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5849:                                        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5850:                                        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);
                   5851:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5852:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5853:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5854:                                        }   
                   5855:                                        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5856:                                        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);
                   5857:                                        for (j=1; j<= nlstate+1 ; j ++) {
                   5858:                                                if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5859:                                                else fprintf(ficgp," %%*lf (%%*lf)");
                   5860:                                        }   
                   5861:                                        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5862:                                        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5863:                                } /* state */
                   5864:                        } /* vpopbased */
                   5865:                        fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  5866:   } /* k1 */
1.219     brouard  5867:        
                   5868:        
1.126     brouard  5869:   /*3eme*/
                   5870:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5871: 
1.126     brouard  5872:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5873:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5874:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.219     brouard  5875:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5876:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5877:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5878:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5879:                                vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  5880:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5881:       }
                   5882:       fprintf(ficgp,"\n#\n");
1.220     brouard  5883:                        if(invalidvarcomb[k1]){
                   5884:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5885:                                                continue;
                   5886:                        }
1.219     brouard  5887:                        
1.126     brouard  5888:       /*       k=2+nlstate*(2*cpt-2); */
                   5889:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5890:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5891:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5892: 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  5893:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.219     brouard  5894:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5895:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5896:                                fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5897:                                for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5898:                                fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5899:                                
1.126     brouard  5900:       */
                   5901:       for (i=1; i< nlstate ; i ++) {
1.219     brouard  5902:                                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);
                   5903:                                /*      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);*/
                   5904:                                
1.126     brouard  5905:       } 
1.201     brouard  5906:       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  5907:     }
                   5908:   }
                   5909:   
1.220     brouard  5910:        /* 4eme */
1.201     brouard  5911:   /* Survival functions (period) from state i in state j by initial state i */
                   5912:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
1.220     brouard  5913: 
1.201     brouard  5914:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5915:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5916:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  5917:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5918:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5919:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5920:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5921:                                vlv= nbcode[Tvaraff[k]][lv];
                   5922:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5923:       }
                   5924:       fprintf(ficgp,"\n#\n");
1.220     brouard  5925:                        if(invalidvarcomb[k1]){
                   5926:                                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5927:                                                        continue;
                   5928:                        }
                   5929:                        
1.201     brouard  5930:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5931:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  5932: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   5933: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  5934: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5935:       k=3;
1.201     brouard  5936:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  5937:                                if(i==1){
                   5938:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5939:                                }else{
                   5940:                                        fprintf(ficgp,", '' ");
                   5941:                                }
                   5942:                                l=(nlstate+ndeath)*(i-1)+1;
                   5943:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5944:                                for (j=2; j<= nlstate+ndeath ; j ++)
                   5945:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   5946:                                fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  5947:       } /* nlstate */
                   5948:       fprintf(ficgp,"\nset out\n");
                   5949:     } /* end cpt state*/ 
                   5950:   } /* end covariate */  
1.220     brouard  5951:        
                   5952: /* 5eme */
1.201     brouard  5953:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5954:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5955:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.220     brouard  5956: 
1.201     brouard  5957:       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  5958:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  5959:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5960:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5961:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5962:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5963:                                vlv= nbcode[Tvaraff[k]][lv];
                   5964:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5965:       }
                   5966:       fprintf(ficgp,"\n#\n");
1.220     brouard  5967:                        if(invalidvarcomb[k1]){
                   5968:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5969:                                                continue;
                   5970:                        }
                   5971:                        
1.201     brouard  5972:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5973:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  5974: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   5975: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  5976: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5977:       k=3;
1.201     brouard  5978:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  5979:                                if(j==1)
                   5980:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5981:                                else
                   5982:                                        fprintf(ficgp,", '' ");
                   5983:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   5984:                                fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5985:                                /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5986:                                /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5987:                                fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  5988:       } /* nlstate */
                   5989:       fprintf(ficgp,", '' ");
                   5990:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5991:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  5992:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   5993:                                if(j < nlstate)
                   5994:                                        fprintf(ficgp,"$%d +",k+l);
                   5995:                                else
                   5996:                                        fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  5997:       }
                   5998:       fprintf(ficgp,"\nset out\n");
                   5999:     } /* end cpt state*/ 
                   6000:   } /* end covariate */  
1.220     brouard  6001:        
                   6002: /* 6eme */
1.202     brouard  6003:   /* CV preval stable (period) for each covariate */
1.211     brouard  6004:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6005:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6006: 
1.211     brouard  6007:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6008:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  6009:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6010:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6011:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6012:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6013:                                vlv= nbcode[Tvaraff[k]][lv];
                   6014:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6015:       }
                   6016:       fprintf(ficgp,"\n#\n");
1.220     brouard  6017:                        if(invalidvarcomb[k1]){
                   6018:                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6019:                                                continue;
                   6020:                        }
1.211     brouard  6021: 
1.201     brouard  6022:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6023:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  6024: set ter svg size 640, 480\n\
1.126     brouard  6025: unset log y\n\
1.153     brouard  6026: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6027:       k=3; /* Offset */
1.153     brouard  6028:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  6029:                                if(i==1)
                   6030:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6031:                                else
                   6032:                                        fprintf(ficgp,", '' ");
                   6033:                                l=(nlstate+ndeath)*(i-1)+1;
                   6034:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6035:                                for (j=2; j<= nlstate ; j ++)
                   6036:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   6037:                                fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6038:       } /* nlstate */
1.201     brouard  6039:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6040:     } /* end cpt state*/ 
                   6041:   } /* end covariate */  
1.220     brouard  6042: 
                   6043: 
                   6044: /* 7eme */
1.218     brouard  6045:   if(backcast == 1){
1.217     brouard  6046:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6047:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6048:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6049:                                fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6050:                                for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6051:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6052:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6053:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6054:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6055:                                        vlv= nbcode[Tvaraff[k]][lv];
                   6056:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6057:                                }
                   6058:                                fprintf(ficgp,"\n#\n");
                   6059:                                if(invalidvarcomb[k1]){
                   6060:                                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6061:                                                                continue;
                   6062:                                }
                   6063:                                
                   6064:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6065:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6066: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6067: unset log y\n                                                                                                                                                                                                                                          \
1.218     brouard  6068: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.220     brouard  6069:                                k=3; /* Offset */
                   6070:                                for (i=1; i<= nlstate ; i ++){
                   6071:                                        if(i==1)
                   6072:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6073:                                        else
                   6074:                                                fprintf(ficgp,", '' ");
                   6075:                                        /* l=(nlstate+ndeath)*(i-1)+1; */
                   6076:                                        l=(nlstate+ndeath)*(cpt-1)+1;
                   6077:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6078:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6079:                                        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6080:                                        /* for (j=2; j<= nlstate ; j ++) */
                   6081:                                        /*      fprintf(ficgp,"+$%d",k+l+j-1); */
                   6082:                                        /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6083:                                        fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6084:                                } /* nlstate */
                   6085:                                fprintf(ficgp,"\nset out\n");
1.218     brouard  6086:       } /* end cpt state*/ 
                   6087:     } /* end covariate */  
                   6088:   } /* End if backcast */
                   6089:   
1.220     brouard  6090:        /* 8eme */
1.218     brouard  6091:   if(prevfcast==1){
                   6092:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6093:     
                   6094:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6095:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.219     brouard  6096:                                fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6097:                                for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6098:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6099:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6100:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6101:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6102:                                        vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  6103:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.219     brouard  6104:                                }
                   6105:                                fprintf(ficgp,"\n#\n");
1.220     brouard  6106:                                if(invalidvarcomb[k1]){
                   6107:                                                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6108:                                                                continue;
                   6109:                                }
1.219     brouard  6110:                                
                   6111:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6112:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6113:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   6114: set ter svg size 640, 480\n    \
                   6115: unset log y\n  \
                   6116: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6117:                                for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6118:                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6119:                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6120:                                        /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6121:                                        /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6122:                                        if(i==1){
                   6123:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6124:                                        }else{
                   6125:                                                fprintf(ficgp,",\\\n '' ");
                   6126:                                        }
                   6127:                                        if(cptcoveff ==0){ /* No covariate */
                   6128:                                                ioffset=2; /* Age is in 2 */
                   6129:                                                /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6130:                                                /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6131:                                                /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6132:                                                /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6133:                                                fprintf(ficgp," u %d:(", ioffset); 
                   6134:                                                if(i==nlstate+1)
                   6135:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
                   6136:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6137:                                                else
                   6138:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
                   6139:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6140:                                        }else{ /* more than 2 covariates */
                   6141:                                                if(cptcoveff ==1){
                   6142:                                                        ioffset=4; /* Age is in 4 */
                   6143:                                                }else{
                   6144:                                                        ioffset=6; /* Age is in 6 */
                   6145:                                                /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6146:                                                /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6147:                                                }   
1.220     brouard  6148:                                                fprintf(ficgp," u %d:(",ioffset); 
1.219     brouard  6149:                                                kl=0;
1.220     brouard  6150:                                                strcpy(gplotcondition,"(");
                   6151:                                                for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.219     brouard  6152:                                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6153:                                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6154:                                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6155:                                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6156:                                                        vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6157:                                                        kl++;
                   6158:                                                        sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
1.219     brouard  6159:                                                        kl++;
1.220     brouard  6160:                                                        if(k <cptcoveff && cptcoveff>1)
                   6161:                                                                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6162:                                                }
                   6163:                                                strcpy(gplotcondition+strlen(gplotcondition),")");
                   6164:                                                /* 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 *\/ */
                   6165:                                                /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6166:                                                /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6167:                                                /* ''  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*/
                   6168:                                                if(i==nlstate+1){
                   6169:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6170:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6171:                                                }else{
                   6172:                                                                fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6173:                                                                                                ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6174:                                                }
1.219     brouard  6175:                                        } /* end if covariate */
                   6176:                                } /* nlstate */
                   6177:                                fprintf(ficgp,"\nset out\n");
                   6178:                        } /* end cpt state*/
                   6179:                } /* end covariate */
                   6180:        } /* End if prevfcast */
                   6181:        
1.211     brouard  6182:        
1.219     brouard  6183:        /* proba elementaires */
                   6184:        fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6185:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6186:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6187:     for(k=1; k <=(nlstate+ndeath); k++){
                   6188:       if (k != i) {
1.187     brouard  6189:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  6190:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  6191:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  6192:          jk++; 
                   6193:        }
1.187     brouard  6194:        fprintf(ficgp,"\n");
1.126     brouard  6195:       }
                   6196:     }
                   6197:    }
1.187     brouard  6198:   fprintf(ficgp,"##############\n#\n");
                   6199: 
1.145     brouard  6200:   /*goto avoid;*/
1.200     brouard  6201:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6202:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6203:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6204:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6205:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6206:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6207:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6208:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6209:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6210:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6211:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6212:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6213:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6214:   fprintf(ficgp,"#\n");
1.201     brouard  6215:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  6216:      fprintf(ficgp,"# ng=%d\n",ng);
                   6217:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  6218:      for(jk=1; jk <=m; jk++) {
1.187     brouard  6219:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  6220:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6221:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6222:        if (ng==1){
                   6223:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6224:         fprintf(ficgp,"\nunset log y");
                   6225:        }else if (ng==2){
                   6226:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6227:         fprintf(ficgp,"\nset log y");
                   6228:        }else if (ng==3){
1.126     brouard  6229:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  6230:         fprintf(ficgp,"\nset log y");
                   6231:        }else
                   6232:         fprintf(ficgp,"\nunset title ");
                   6233:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  6234:        i=1;
                   6235:        for(k2=1; k2<=nlstate; k2++) {
                   6236:         k3=i;
                   6237:         for(k=1; k<=(nlstate+ndeath); k++) {
                   6238:           if (k != k2){
1.201     brouard  6239:             switch( ng) {
                   6240:             case 1:
1.187     brouard  6241:               if(nagesqr==0)
1.201     brouard  6242:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  6243:               else /* nagesqr =1 */
1.201     brouard  6244:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6245:               break;
                   6246:             case 2: /* ng=2 */
1.187     brouard  6247:               if(nagesqr==0)
                   6248:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6249:               else /* nagesqr =1 */
1.201     brouard  6250:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6251:               break;
                   6252:             case 3:
                   6253:               if(nagesqr==0)
                   6254:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6255:               else /* nagesqr =1 */
                   6256:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6257:               break;
                   6258:             }
1.141     brouard  6259:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  6260:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  6261:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6262:               if(ij <=cptcovage) { /* Bug valgrind */
                   6263:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  6264:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6265:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  6266:                   ij++;
                   6267:                 }
1.186     brouard  6268:               }
                   6269:               else
1.198     brouard  6270:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6271:             }
1.217     brouard  6272:           }else{
                   6273:             i=i-ncovmodel;
                   6274:             if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6275:               fprintf(ficgp," (1.");
                   6276:           }
                   6277:           
                   6278:           if(ng != 1){
                   6279:             fprintf(ficgp,")/(1");
1.126     brouard  6280:             
1.217     brouard  6281:             for(k1=1; k1 <=nlstate; k1++){ 
                   6282:               if(nagesqr==0)
                   6283:                 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6284:               else /* nagesqr =1 */
                   6285:                 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);
                   6286:               
                   6287:               ij=1;
                   6288:               for(j=3; j <=ncovmodel-nagesqr; j++){
                   6289:                 if(ij <=cptcovage) { /* Bug valgrind */
                   6290:                   if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6291:                     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6292:                     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6293:                     ij++;
1.197     brouard  6294:                   }
1.186     brouard  6295:                 }
1.217     brouard  6296:                 else
                   6297:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  6298:               }
                   6299:               fprintf(ficgp,")");
1.217     brouard  6300:             }
                   6301:             fprintf(ficgp,")");
                   6302:             if(ng ==2)
                   6303:               fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6304:             else /* ng= 3 */
                   6305:               fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6306:           }else{ /* end ng <> 1 */
                   6307:             if( k !=k2) /* logit p11 is hard to draw */
1.201     brouard  6308:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  6309:           }
1.217     brouard  6310:           if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6311:             fprintf(ficgp,",");
                   6312:           if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6313:             fprintf(ficgp,",");
                   6314:           i=i+ncovmodel;
1.126     brouard  6315:         } /* end k */
                   6316:        } /* end k2 */
1.201     brouard  6317:        fprintf(ficgp,"\n set out\n");
1.126     brouard  6318:      } /* end jk */
                   6319:    } /* end ng */
1.164     brouard  6320:  /* avoid: */
1.126     brouard  6321:    fflush(ficgp); 
                   6322: }  /* end gnuplot */
                   6323: 
                   6324: 
                   6325: /*************** Moving average **************/
1.219     brouard  6326: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222   ! brouard  6327:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6328:    
1.222   ! brouard  6329:    int i, cpt, cptcod;
        !          6330:    int modcovmax =1;
        !          6331:    int mobilavrange, mob;
        !          6332:    int iage=0;
        !          6333: 
        !          6334:    double sum=0.;
        !          6335:    double age;
        !          6336:    double *sumnewp, *sumnewm;
        !          6337:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
        !          6338:   
        !          6339:   
        !          6340:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
        !          6341:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
        !          6342: 
        !          6343:    sumnewp = vector(1,ncovcombmax);
        !          6344:    sumnewm = vector(1,ncovcombmax);
        !          6345:    agemingood = vector(1,ncovcombmax); 
        !          6346:    agemaxgood = vector(1,ncovcombmax);
        !          6347: 
        !          6348:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
        !          6349:      sumnewm[cptcod]=0.;
        !          6350:      sumnewp[cptcod]=0.;
        !          6351:      agemingood[cptcod]=0;
        !          6352:      agemaxgood[cptcod]=0;
        !          6353:    }
        !          6354:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
        !          6355:   
        !          6356:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
        !          6357:      if(mobilav==1) mobilavrange=5; /* default */
        !          6358:      else mobilavrange=mobilav;
        !          6359:      for (age=bage; age<=fage; age++)
        !          6360:        for (i=1; i<=nlstate;i++)
        !          6361:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
        !          6362:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
        !          6363:      /* We keep the original values on the extreme ages bage, fage and for 
        !          6364:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
        !          6365:        we use a 5 terms etc. until the borders are no more concerned. 
        !          6366:      */ 
        !          6367:      for (mob=3;mob <=mobilavrange;mob=mob+2){
        !          6368:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
        !          6369:         for (i=1; i<=nlstate;i++){
        !          6370:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
        !          6371:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
        !          6372:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
        !          6373:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
        !          6374:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
        !          6375:             }
        !          6376:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
        !          6377:           }
        !          6378:         }
        !          6379:        }/* end age */
        !          6380:      }/* end mob */
        !          6381:    }else
        !          6382:      return -1;
        !          6383:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
        !          6384:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
        !          6385:      if(invalidvarcomb[cptcod]){
        !          6386:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
        !          6387:        continue;
        !          6388:      }
1.219     brouard  6389: 
1.222   ! brouard  6390:      agemingood[cptcod]=fage-(mob-1)/2;
        !          6391:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
        !          6392:        sumnewm[cptcod]=0.;
        !          6393:        for (i=1; i<=nlstate;i++){
        !          6394:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
        !          6395:        }
        !          6396:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
        !          6397:         agemingood[cptcod]=age;
        !          6398:        }else{ /* bad */
        !          6399:         for (i=1; i<=nlstate;i++){
        !          6400:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
        !          6401:         } /* i */
        !          6402:        } /* end bad */
        !          6403:      }/* age */
        !          6404:      sum=0.;
        !          6405:      for (i=1; i<=nlstate;i++){
        !          6406:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
        !          6407:      }
        !          6408:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
        !          6409:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
        !          6410:        /* for (i=1; i<=nlstate;i++){ */
        !          6411:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
        !          6412:        /* } /\* i *\/ */
        !          6413:      } /* end bad */
        !          6414:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
        !          6415:      /* From youngest, finding the oldest wrong */
        !          6416:      agemaxgood[cptcod]=bage+(mob-1)/2;
        !          6417:      for (age=bage+(mob-1)/2; age<=fage; age++){
        !          6418:        sumnewm[cptcod]=0.;
        !          6419:        for (i=1; i<=nlstate;i++){
        !          6420:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
        !          6421:        }
        !          6422:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
        !          6423:         agemaxgood[cptcod]=age;
        !          6424:        }else{ /* bad */
        !          6425:         for (i=1; i<=nlstate;i++){
        !          6426:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6427:         } /* i */
        !          6428:        } /* end bad */
        !          6429:      }/* age */
        !          6430:      sum=0.;
        !          6431:      for (i=1; i<=nlstate;i++){
        !          6432:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6433:      }
        !          6434:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
        !          6435:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
        !          6436:        /* for (i=1; i<=nlstate;i++){ */
        !          6437:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
        !          6438:        /* } /\* i *\/ */
        !          6439:      } /* end bad */
        !          6440:                
        !          6441:      for (age=bage; age<=fage; age++){
        !          6442:        printf("%d %d ", cptcod, (int)age);
        !          6443:        sumnewp[cptcod]=0.;
        !          6444:        sumnewm[cptcod]=0.;
        !          6445:        for (i=1; i<=nlstate;i++){
        !          6446:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
        !          6447:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
        !          6448:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
        !          6449:        }
        !          6450:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
        !          6451:      }
        !          6452:      /* printf("\n"); */
        !          6453:      /* } */
        !          6454:      /* brutal averaging */
        !          6455:      for (i=1; i<=nlstate;i++){
        !          6456:        for (age=1; age<=bage; age++){
        !          6457:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
        !          6458:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
        !          6459:        }       
        !          6460:        for (age=fage; age<=AGESUP; age++){
        !          6461:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
        !          6462:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
        !          6463:        }
        !          6464:      } /* end i status */
        !          6465:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
        !          6466:        for (age=1; age<=AGESUP; age++){
        !          6467:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
        !          6468:         mobaverage[(int)age][i][cptcod]=0.;
        !          6469:        }
        !          6470:      }
        !          6471:    }/* end cptcod */
        !          6472:    free_vector(sumnewm,1, ncovcombmax);
        !          6473:    free_vector(sumnewp,1, ncovcombmax);
        !          6474:    free_vector(agemaxgood,1, ncovcombmax);
        !          6475:    free_vector(agemingood,1, ncovcombmax);
        !          6476:    return 0;
        !          6477:  }/* End movingaverage */
1.218     brouard  6478:  
1.126     brouard  6479: 
                   6480: /************** Forecasting ******************/
1.169     brouard  6481: 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  6482:   /* proj1, year, month, day of starting projection 
                   6483:      agemin, agemax range of age
                   6484:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6485:      anproj2 year of en of projection (same day and month as proj1).
                   6486:   */
1.164     brouard  6487:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6488:   double agec; /* generic age */
                   6489:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6490:   double *popeffectif,*popcount;
                   6491:   double ***p3mat;
1.218     brouard  6492:   /* double ***mobaverage; */
1.126     brouard  6493:   char fileresf[FILENAMELENGTH];
                   6494: 
                   6495:   agelim=AGESUP;
1.211     brouard  6496:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6497:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6498:      We still use firstpass and lastpass as another selection.
                   6499:   */
1.214     brouard  6500:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6501:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6502:  
1.201     brouard  6503:   strcpy(fileresf,"F_"); 
                   6504:   strcat(fileresf,fileresu);
1.126     brouard  6505:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6506:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6507:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6508:   }
1.215     brouard  6509:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6510:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6511: 
                   6512:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6513: 
                   6514: 
                   6515:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6516:   if (stepm<=12) stepsize=1;
                   6517:   if(estepm < stepm){
                   6518:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6519:   }
                   6520:   else  hstepm=estepm;   
                   6521: 
                   6522:   hstepm=hstepm/stepm; 
                   6523:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6524:                                fractional in yp1 */
                   6525:   anprojmean=yp;
                   6526:   yp2=modf((yp1*12),&yp);
                   6527:   mprojmean=yp;
                   6528:   yp1=modf((yp2*30.5),&yp);
                   6529:   jprojmean=yp;
                   6530:   if(jprojmean==0) jprojmean=1;
                   6531:   if(mprojmean==0) jprojmean=1;
                   6532: 
                   6533:   i1=cptcoveff;
                   6534:   if (cptcovn < 1){i1=1;}
                   6535:   
                   6536:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6537:   
                   6538:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6539: 
                   6540: /*           if (h==(int)(YEARM*yearp)){ */
                   6541:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6542:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6543:       k=k+1;
1.211     brouard  6544:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  6545:       for(j=1;j<=cptcoveff;j++) {
1.219     brouard  6546:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6547:       }
1.211     brouard  6548:       fprintf(ficresf," yearproj age");
1.126     brouard  6549:       for(j=1; j<=nlstate+ndeath;j++){ 
1.219     brouard  6550:                                for(i=1; i<=nlstate;i++)              
1.126     brouard  6551:           fprintf(ficresf," p%d%d",i,j);
1.219     brouard  6552:                                fprintf(ficresf," wp.%d",j);
1.126     brouard  6553:       }
1.217     brouard  6554:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.219     brouard  6555:                                fprintf(ficresf,"\n");
                   6556:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6557:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6558:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6559:                                        nhstepm = nhstepm/hstepm; 
                   6560:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6561:                                        oldm=oldms;savm=savms;
                   6562:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6563:                                        
                   6564:                                        for (h=0; h<=nhstepm; h++){
                   6565:                                                if (h*hstepm/YEARM*stepm ==yearp) {
1.126     brouard  6566:               fprintf(ficresf,"\n");
                   6567:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6568:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  6569:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6570:                                                } 
                   6571:                                                for(j=1; j<=nlstate+ndeath;j++) {
                   6572:                                                        ppij=0.;
                   6573:                                                        for(i=1; i<=nlstate;i++) {
                   6574:                                                                if (mobilav==1) 
                   6575:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6576:                                                                else {
                   6577:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6578:                                                                }
                   6579:                                                                if (h*hstepm/YEARM*stepm== yearp) {
                   6580:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6581:                                                                }
                   6582:                                                        } /* end i */
                   6583:                                                        if (h*hstepm/YEARM*stepm==yearp) {
                   6584:                                                                fprintf(ficresf," %.3f", ppij);
                   6585:                                                        }
                   6586:                                                }/* end j */
                   6587:                                        } /* end h */
                   6588:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6589:                                } /* end agec */
1.126     brouard  6590:       } /* end yearp */
                   6591:     } /* end cptcod */
                   6592:   } /* end  cptcov */
1.219     brouard  6593:        
1.126     brouard  6594:   fclose(ficresf);
1.215     brouard  6595:   printf("End of Computing forecasting \n");
                   6596:   fprintf(ficlog,"End of Computing forecasting\n");
                   6597: 
1.126     brouard  6598: }
                   6599: 
1.218     brouard  6600: /* /\************** Back Forecasting ******************\/ */
                   6601: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
                   6602: /*   /\* back1, year, month, day of starting backection  */
                   6603: /*      agemin, agemax range of age */
                   6604: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6605: /*      anback2 year of en of backection (same day and month as back1). */
                   6606: /*   *\/ */
                   6607: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6608: /*   double agec; /\* generic age *\/ */
                   6609: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6610: /*   double *popeffectif,*popcount; */
                   6611: /*   double ***p3mat; */
                   6612: /*   /\* double ***mobaverage; *\/ */
                   6613: /*   char fileresfb[FILENAMELENGTH]; */
                   6614:        
                   6615: /*   agelim=AGESUP; */
                   6616: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6617: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6618: /*      We still use firstpass and lastpass as another selection. */
                   6619: /*   *\/ */
                   6620: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6621: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6622: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6623:        
                   6624: /*   strcpy(fileresfb,"FB_");  */
                   6625: /*   strcat(fileresfb,fileresu); */
                   6626: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6627: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6628: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6629: /*   } */
                   6630: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6631: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6632:        
                   6633: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   6634:        
                   6635: /*   /\* if (mobilav!=0) { *\/ */
                   6636: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6637: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6638: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6639: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6640: /*   /\*   } *\/ */
                   6641: /*   /\* } *\/ */
                   6642:        
                   6643: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6644: /*   if (stepm<=12) stepsize=1; */
                   6645: /*   if(estepm < stepm){ */
                   6646: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6647: /*   } */
                   6648: /*   else  hstepm=estepm;    */
                   6649:        
                   6650: /*   hstepm=hstepm/stepm;  */
                   6651: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6652: /*                                fractional in yp1 *\/ */
                   6653: /*   anprojmean=yp; */
                   6654: /*   yp2=modf((yp1*12),&yp); */
                   6655: /*   mprojmean=yp; */
                   6656: /*   yp1=modf((yp2*30.5),&yp); */
                   6657: /*   jprojmean=yp; */
                   6658: /*   if(jprojmean==0) jprojmean=1; */
                   6659: /*   if(mprojmean==0) jprojmean=1; */
                   6660:        
                   6661: /*   i1=cptcoveff; */
                   6662: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  6663:   
1.218     brouard  6664: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  6665:   
1.218     brouard  6666: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6667:        
                   6668: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6669: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
                   6670: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   6671: /*       k=k+1; */
                   6672: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
                   6673: /*       for(j=1;j<=cptcoveff;j++) { */
                   6674: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6675: /*       } */
                   6676: /*       fprintf(ficresfb," yearbproj age"); */
                   6677: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6678: /*                             for(i=1; i<=nlstate;i++)               */
                   6679: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6680: /*                             fprintf(ficresfb," p.%d",j); */
                   6681: /*       } */
                   6682: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6683: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6684: /*                             fprintf(ficresfb,"\n"); */
                   6685: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6686: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6687: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6688: /*                                     nhstepm = nhstepm/hstepm;  */
                   6689: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6690: /*                                     oldm=oldms;savm=savms; */
                   6691: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6692: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6693: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6694: /*               fprintf(ficresfb,"\n"); */
                   6695: /*               for(j=1;j<=cptcoveff;j++)  */
                   6696: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6697: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6698: /*                                             }  */
                   6699: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6700: /*                                                     ppij=0.; */
                   6701: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6702: /*                                                             if (mobilav==1)  */
                   6703: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6704: /*                                                             else { */
                   6705: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6706: /*                                                             } */
                   6707: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6708: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6709: /*                                                             } */
                   6710: /*                                                     } /\* end i *\/ */
                   6711: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6712: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6713: /*                                                     } */
                   6714: /*                                             }/\* end j *\/ */
                   6715: /*                                     } /\* end h *\/ */
                   6716: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6717: /*                             } /\* end agec *\/ */
                   6718: /*       } /\* end yearp *\/ */
                   6719: /*     } /\* end cptcod *\/ */
                   6720: /*   } /\* end  cptcov *\/ */
                   6721:        
                   6722: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6723:        
                   6724: /*   fclose(ficresfb); */
                   6725: /*   printf("End of Computing Back forecasting \n"); */
                   6726: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  6727:        
1.218     brouard  6728: /* } */
1.217     brouard  6729: 
1.126     brouard  6730: /************** Forecasting *****not tested NB*************/
1.169     brouard  6731: 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  6732:   
                   6733:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6734:   int *popage;
                   6735:   double calagedatem, agelim, kk1, kk2;
                   6736:   double *popeffectif,*popcount;
                   6737:   double ***p3mat,***tabpop,***tabpopprev;
1.218     brouard  6738:   /* double ***mobaverage; */
1.126     brouard  6739:   char filerespop[FILENAMELENGTH];
                   6740: 
                   6741:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6742:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6743:   agelim=AGESUP;
                   6744:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6745:   
                   6746:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6747:   
                   6748:   
1.201     brouard  6749:   strcpy(filerespop,"POP_"); 
                   6750:   strcat(filerespop,fileresu);
1.126     brouard  6751:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6752:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6753:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6754:   }
                   6755:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6756:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6757: 
                   6758:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6759: 
1.218     brouard  6760:   /* if (mobilav!=0) { */
                   6761:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6762:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6763:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6764:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6765:   /*   } */
                   6766:   /* } */
1.126     brouard  6767: 
                   6768:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6769:   if (stepm<=12) stepsize=1;
                   6770:   
                   6771:   agelim=AGESUP;
                   6772:   
                   6773:   hstepm=1;
                   6774:   hstepm=hstepm/stepm; 
1.218     brouard  6775:        
1.126     brouard  6776:   if (popforecast==1) {
                   6777:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6778:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6779:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6780:     } 
                   6781:     popage=ivector(0,AGESUP);
                   6782:     popeffectif=vector(0,AGESUP);
                   6783:     popcount=vector(0,AGESUP);
                   6784:     
                   6785:     i=1;   
                   6786:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
1.218     brouard  6787:     
1.126     brouard  6788:     imx=i;
                   6789:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6790:   }
1.218     brouard  6791:   
1.126     brouard  6792:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
1.218     brouard  6793:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
1.126     brouard  6794:       k=k+1;
                   6795:       fprintf(ficrespop,"\n#******");
                   6796:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6797:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6798:       }
                   6799:       fprintf(ficrespop,"******\n");
                   6800:       fprintf(ficrespop,"# Age");
                   6801:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6802:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6803:       
                   6804:       for (cpt=0; cpt<=0;cpt++) { 
                   6805:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6806:        
1.218     brouard  6807:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
1.126     brouard  6808:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6809:          nhstepm = nhstepm/hstepm; 
                   6810:          
                   6811:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6812:          oldm=oldms;savm=savms;
                   6813:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
1.218     brouard  6814:          
1.126     brouard  6815:          for (h=0; h<=nhstepm; h++){
                   6816:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6817:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6818:            } 
                   6819:            for(j=1; j<=nlstate+ndeath;j++) {
                   6820:              kk1=0.;kk2=0;
                   6821:              for(i=1; i<=nlstate;i++) {              
                   6822:                if (mobilav==1) 
                   6823:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6824:                else {
                   6825:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6826:                }
                   6827:              }
                   6828:              if (h==(int)(calagedatem+12*cpt)){
                   6829:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
1.218     brouard  6830:                /*fprintf(ficrespop," %.3f", kk1);
                   6831:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
1.126     brouard  6832:              }
                   6833:            }
                   6834:            for(i=1; i<=nlstate;i++){
                   6835:              kk1=0.;
1.218     brouard  6836:              for(j=1; j<=nlstate;j++){
                   6837:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6838:              }
                   6839:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
1.126     brouard  6840:            }
1.218     brouard  6841:            
                   6842:            if (h==(int)(calagedatem+12*cpt))
                   6843:              for(j=1; j<=nlstate;j++) 
                   6844:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
1.126     brouard  6845:          }
                   6846:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6847:        }
                   6848:       }
1.218     brouard  6849:       
                   6850:       /******/
                   6851:       
1.126     brouard  6852:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6853:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6854:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6855:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6856:          nhstepm = nhstepm/hstepm; 
                   6857:          
                   6858:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6859:          oldm=oldms;savm=savms;
                   6860:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6861:          for (h=0; h<=nhstepm; h++){
                   6862:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6863:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6864:            } 
                   6865:            for(j=1; j<=nlstate+ndeath;j++) {
                   6866:              kk1=0.;kk2=0;
                   6867:              for(i=1; i<=nlstate;i++) {              
                   6868:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6869:              }
                   6870:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6871:            }
                   6872:          }
                   6873:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6874:        }
                   6875:       }
1.218     brouard  6876:     } 
1.126     brouard  6877:   }
1.218     brouard  6878:   
                   6879:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6880:   
1.126     brouard  6881:   if (popforecast==1) {
                   6882:     free_ivector(popage,0,AGESUP);
                   6883:     free_vector(popeffectif,0,AGESUP);
                   6884:     free_vector(popcount,0,AGESUP);
                   6885:   }
                   6886:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6887:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6888:   fclose(ficrespop);
                   6889: } /* End of popforecast */
1.218     brouard  6890:  
1.126     brouard  6891: int fileappend(FILE *fichier, char *optionfich)
                   6892: {
                   6893:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   6894:     printf("Problem with file: %s\n", optionfich);
                   6895:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   6896:     return (0);
                   6897:   }
                   6898:   fflush(fichier);
                   6899:   return (1);
                   6900: }
                   6901: 
                   6902: 
                   6903: /**************** function prwizard **********************/
                   6904: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6905: {
                   6906: 
                   6907:   /* Wizard to print covariance matrix template */
                   6908: 
1.164     brouard  6909:   char ca[32], cb[32];
                   6910:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6911:   int numlinepar;
                   6912: 
                   6913:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6914:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6915:   for(i=1; i <=nlstate; i++){
                   6916:     jj=0;
                   6917:     for(j=1; j <=nlstate+ndeath; j++){
                   6918:       if(j==i) continue;
                   6919:       jj++;
                   6920:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6921:       printf("%1d%1d",i,j);
                   6922:       fprintf(ficparo,"%1d%1d",i,j);
                   6923:       for(k=1; k<=ncovmodel;k++){
                   6924:        /*        printf(" %lf",param[i][j][k]); */
                   6925:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6926:        printf(" 0.");
                   6927:        fprintf(ficparo," 0.");
                   6928:       }
                   6929:       printf("\n");
                   6930:       fprintf(ficparo,"\n");
                   6931:     }
                   6932:   }
                   6933:   printf("# Scales (for hessian or gradient estimation)\n");
                   6934:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6935:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6936:   for(i=1; i <=nlstate; i++){
                   6937:     jj=0;
                   6938:     for(j=1; j <=nlstate+ndeath; j++){
                   6939:       if(j==i) continue;
                   6940:       jj++;
                   6941:       fprintf(ficparo,"%1d%1d",i,j);
                   6942:       printf("%1d%1d",i,j);
                   6943:       fflush(stdout);
                   6944:       for(k=1; k<=ncovmodel;k++){
                   6945:        /*      printf(" %le",delti3[i][j][k]); */
                   6946:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6947:        printf(" 0.");
                   6948:        fprintf(ficparo," 0.");
                   6949:       }
                   6950:       numlinepar++;
                   6951:       printf("\n");
                   6952:       fprintf(ficparo,"\n");
                   6953:     }
                   6954:   }
                   6955:   printf("# Covariance matrix\n");
                   6956: /* # 121 Var(a12)\n\ */
                   6957: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6958: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6959: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6960: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6961: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6962: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6963: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6964:   fflush(stdout);
                   6965:   fprintf(ficparo,"# Covariance matrix\n");
                   6966:   /* # 121 Var(a12)\n\ */
                   6967:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6968:   /* #   ...\n\ */
                   6969:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6970:   
                   6971:   for(itimes=1;itimes<=2;itimes++){
                   6972:     jj=0;
                   6973:     for(i=1; i <=nlstate; i++){
                   6974:       for(j=1; j <=nlstate+ndeath; j++){
                   6975:        if(j==i) continue;
                   6976:        for(k=1; k<=ncovmodel;k++){
                   6977:          jj++;
                   6978:          ca[0]= k+'a'-1;ca[1]='\0';
                   6979:          if(itimes==1){
                   6980:            printf("#%1d%1d%d",i,j,k);
                   6981:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6982:          }else{
                   6983:            printf("%1d%1d%d",i,j,k);
                   6984:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6985:            /*  printf(" %.5le",matcov[i][j]); */
                   6986:          }
                   6987:          ll=0;
                   6988:          for(li=1;li <=nlstate; li++){
                   6989:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6990:              if(lj==li) continue;
                   6991:              for(lk=1;lk<=ncovmodel;lk++){
                   6992:                ll++;
                   6993:                if(ll<=jj){
                   6994:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6995:                  if(ll<jj){
                   6996:                    if(itimes==1){
                   6997:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6998:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6999:                    }else{
                   7000:                      printf(" 0.");
                   7001:                      fprintf(ficparo," 0.");
                   7002:                    }
                   7003:                  }else{
                   7004:                    if(itimes==1){
                   7005:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7006:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7007:                    }else{
                   7008:                      printf(" 0.");
                   7009:                      fprintf(ficparo," 0.");
                   7010:                    }
                   7011:                  }
                   7012:                }
                   7013:              } /* end lk */
                   7014:            } /* end lj */
                   7015:          } /* end li */
                   7016:          printf("\n");
                   7017:          fprintf(ficparo,"\n");
                   7018:          numlinepar++;
                   7019:        } /* end k*/
                   7020:       } /*end j */
                   7021:     } /* end i */
                   7022:   } /* end itimes */
                   7023: 
                   7024: } /* end of prwizard */
                   7025: /******************* Gompertz Likelihood ******************************/
                   7026: double gompertz(double x[])
                   7027: { 
                   7028:   double A,B,L=0.0,sump=0.,num=0.;
                   7029:   int i,n=0; /* n is the size of the sample */
                   7030: 
1.220     brouard  7031:   for (i=1;i<=imx ; i++) {
1.126     brouard  7032:     sump=sump+weight[i];
                   7033:     /*    sump=sump+1;*/
                   7034:     num=num+1;
                   7035:   }
                   7036:  
                   7037:  
                   7038:   /* for (i=0; i<=imx; i++) 
                   7039:      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]);*/
                   7040: 
                   7041:   for (i=1;i<=imx ; i++)
                   7042:     {
                   7043:       if (cens[i] == 1 && wav[i]>1)
                   7044:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7045:       
                   7046:       if (cens[i] == 0 && wav[i]>1)
                   7047:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7048:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7049:       
                   7050:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7051:       if (wav[i] > 1 ) { /* ??? */
                   7052:        L=L+A*weight[i];
                   7053:        /*      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]);*/
                   7054:       }
                   7055:     }
                   7056: 
                   7057:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7058:  
                   7059:   return -2*L*num/sump;
                   7060: }
                   7061: 
1.136     brouard  7062: #ifdef GSL
                   7063: /******************* Gompertz_f Likelihood ******************************/
                   7064: double gompertz_f(const gsl_vector *v, void *params)
                   7065: { 
                   7066:   double A,B,LL=0.0,sump=0.,num=0.;
                   7067:   double *x= (double *) v->data;
                   7068:   int i,n=0; /* n is the size of the sample */
                   7069: 
                   7070:   for (i=0;i<=imx-1 ; i++) {
                   7071:     sump=sump+weight[i];
                   7072:     /*    sump=sump+1;*/
                   7073:     num=num+1;
                   7074:   }
                   7075:  
                   7076:  
                   7077:   /* for (i=0; i<=imx; i++) 
                   7078:      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]);*/
                   7079:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7080:   for (i=1;i<=imx ; i++)
                   7081:     {
                   7082:       if (cens[i] == 1 && wav[i]>1)
                   7083:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7084:       
                   7085:       if (cens[i] == 0 && wav[i]>1)
                   7086:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7087:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7088:       
                   7089:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7090:       if (wav[i] > 1 ) { /* ??? */
                   7091:        LL=LL+A*weight[i];
                   7092:        /*      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]);*/
                   7093:       }
                   7094:     }
                   7095: 
                   7096:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7097:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7098:  
                   7099:   return -2*LL*num/sump;
                   7100: }
                   7101: #endif
                   7102: 
1.126     brouard  7103: /******************* Printing html file ***********/
1.201     brouard  7104: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7105:                  int lastpass, int stepm, int weightopt, char model[],\
                   7106:                  int imx,  double p[],double **matcov,double agemortsup){
                   7107:   int i,k;
                   7108: 
                   7109:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7110:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7111:   for (i=1;i<=2;i++) 
                   7112:     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  7113:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7114:   fprintf(fichtm,"</ul>");
                   7115: 
                   7116: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7117: 
                   7118:  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>");
                   7119: 
                   7120:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7121:    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]);
                   7122: 
                   7123:  
                   7124:   fflush(fichtm);
                   7125: }
                   7126: 
                   7127: /******************* Gnuplot file **************/
1.201     brouard  7128: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7129: 
                   7130:   char dirfileres[132],optfileres[132];
1.164     brouard  7131: 
1.126     brouard  7132:   int ng;
                   7133: 
                   7134: 
                   7135:   /*#ifdef windows */
                   7136:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7137:     /*#endif */
                   7138: 
                   7139: 
                   7140:   strcpy(dirfileres,optionfilefiname);
                   7141:   strcpy(optfileres,"vpl");
1.199     brouard  7142:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7143:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7144:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7145:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7146:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7147: 
                   7148: } 
                   7149: 
1.136     brouard  7150: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7151: {
1.126     brouard  7152: 
1.136     brouard  7153:   /*-------- data file ----------*/
                   7154:   FILE *fic;
                   7155:   char dummy[]="                         ";
1.164     brouard  7156:   int i=0, j=0, n=0;
1.136     brouard  7157:   int linei, month, year,iout;
                   7158:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7159:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7160:   char *stratrunc;
                   7161:   int lstra;
1.126     brouard  7162: 
                   7163: 
1.136     brouard  7164:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7165:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7166:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7167:   }
1.126     brouard  7168: 
1.136     brouard  7169:   i=1;
                   7170:   linei=0;
                   7171:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7172:     linei=linei+1;
                   7173:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7174:       if(line[j] == '\t')
                   7175:        line[j] = ' ';
                   7176:     }
                   7177:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7178:       ;
                   7179:     };
                   7180:     line[j+1]=0;  /* Trims blanks at end of line */
                   7181:     if(line[0]=='#'){
                   7182:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7183:       printf("Comment line\n%s\n",line);
                   7184:       continue;
                   7185:     }
                   7186:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7187:     strcpy(line, linetmp);
1.136     brouard  7188:   
1.126     brouard  7189: 
1.136     brouard  7190:     for (j=maxwav;j>=1;j--){
1.137     brouard  7191:       cutv(stra, strb, line, ' '); 
1.136     brouard  7192:       if(strb[0]=='.') { /* Missing status */
                   7193:        lval=-1;
                   7194:       }else{
                   7195:        errno=0;
                   7196:        lval=strtol(strb,&endptr,10); 
                   7197:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7198:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7199:          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);
                   7200:          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  7201:          return 1;
                   7202:        }
                   7203:       }
                   7204:       s[j][i]=lval;
                   7205:       
                   7206:       strcpy(line,stra);
                   7207:       cutv(stra, strb,line,' ');
1.169     brouard  7208:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7209:       }
1.169     brouard  7210:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7211:        month=99;
                   7212:        year=9999;
                   7213:       }else{
1.141     brouard  7214:        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);
                   7215:        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  7216:        return 1;
                   7217:       }
                   7218:       anint[j][i]= (double) year; 
                   7219:       mint[j][i]= (double)month; 
                   7220:       strcpy(line,stra);
                   7221:     } /* ENd Waves */
                   7222:     
                   7223:     cutv(stra, strb,line,' '); 
1.169     brouard  7224:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7225:     }
1.169     brouard  7226:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7227:       month=99;
                   7228:       year=9999;
                   7229:     }else{
1.141     brouard  7230:       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);
                   7231:        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  7232:        return 1;
                   7233:     }
                   7234:     andc[i]=(double) year; 
                   7235:     moisdc[i]=(double) month; 
                   7236:     strcpy(line,stra);
                   7237:     
                   7238:     cutv(stra, strb,line,' '); 
1.169     brouard  7239:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7240:     }
1.169     brouard  7241:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7242:       month=99;
                   7243:       year=9999;
                   7244:     }else{
1.141     brouard  7245:       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);
                   7246:       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  7247:        return 1;
                   7248:     }
                   7249:     if (year==9999) {
1.141     brouard  7250:       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);
                   7251:       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  7252:        return 1;
1.126     brouard  7253: 
1.136     brouard  7254:     }
                   7255:     annais[i]=(double)(year);
                   7256:     moisnais[i]=(double)(month); 
                   7257:     strcpy(line,stra);
                   7258:     
                   7259:     cutv(stra, strb,line,' '); 
                   7260:     errno=0;
                   7261:     dval=strtod(strb,&endptr); 
                   7262:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7263:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7264:       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  7265:       fflush(ficlog);
                   7266:       return 1;
                   7267:     }
                   7268:     weight[i]=dval; 
                   7269:     strcpy(line,stra);
                   7270:     
                   7271:     for (j=ncovcol;j>=1;j--){
                   7272:       cutv(stra, strb,line,' '); 
                   7273:       if(strb[0]=='.') { /* Missing status */
                   7274:        lval=-1;
                   7275:       }else{
                   7276:        errno=0;
                   7277:        lval=strtol(strb,&endptr,10); 
                   7278:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7279:          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);
                   7280:          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  7281:          return 1;
                   7282:        }
                   7283:       }
                   7284:       if(lval <-1 || lval >1){
1.141     brouard  7285:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7286:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7287:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7288:  For example, for multinomial values like 1, 2 and 3,\n \
                   7289:  build V1=0 V2=0 for the reference value (1),\n \
                   7290:         V1=1 V2=0 for (2) \n \
                   7291:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7292:  output of IMaCh is often meaningless.\n \
                   7293:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  7294:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7295:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7296:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7297:  For example, for multinomial values like 1, 2 and 3,\n \
                   7298:  build V1=0 V2=0 for the reference value (1),\n \
                   7299:         V1=1 V2=0 for (2) \n \
                   7300:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7301:  output of IMaCh is often meaningless.\n \
                   7302:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   7303:        return 1;
                   7304:       }
                   7305:       covar[j][i]=(double)(lval);
                   7306:       strcpy(line,stra);
                   7307:     }  
                   7308:     lstra=strlen(stra);
                   7309:      
                   7310:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7311:       stratrunc = &(stra[lstra-9]);
                   7312:       num[i]=atol(stratrunc);
                   7313:     }
                   7314:     else
                   7315:       num[i]=atol(stra);
                   7316:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7317:       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;}*/
                   7318:     
                   7319:     i=i+1;
                   7320:   } /* End loop reading  data */
1.126     brouard  7321: 
1.136     brouard  7322:   *imax=i-1; /* Number of individuals */
                   7323:   fclose(fic);
                   7324:  
                   7325:   return (0);
1.164     brouard  7326:   /* endread: */
1.136     brouard  7327:     printf("Exiting readdata: ");
                   7328:     fclose(fic);
                   7329:     return (1);
1.126     brouard  7330: 
                   7331: 
                   7332: 
1.136     brouard  7333: }
1.145     brouard  7334: void removespace(char *str) {
                   7335:   char *p1 = str, *p2 = str;
                   7336:   do
                   7337:     while (*p2 == ' ')
                   7338:       p2++;
1.169     brouard  7339:   while (*p1++ == *p2++);
1.145     brouard  7340: }
                   7341: 
                   7342: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  7343:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   7344:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   7345:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   7346:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  7347:    * - cptcovage number of covariates with age*products =2
                   7348:    * - cptcovs number of simple covariates
                   7349:    * - 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
                   7350:    *     which is a new column after the 9 (ncovcol) variables. 
                   7351:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   7352:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   7353:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   7354:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   7355:  */
1.136     brouard  7356: {
1.145     brouard  7357:   int i, j, k, ks;
1.164     brouard  7358:   int  j1, k1, k2;
1.136     brouard  7359:   char modelsav[80];
1.145     brouard  7360:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7361:   char *strpt;
1.136     brouard  7362: 
1.145     brouard  7363:   /*removespace(model);*/
1.136     brouard  7364:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7365:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7366:     if (strstr(model,"AGE") !=0){
1.192     brouard  7367:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7368:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7369:       return 1;
                   7370:     }
1.141     brouard  7371:     if (strstr(model,"v") !=0){
                   7372:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7373:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7374:       return 1;
                   7375:     }
1.187     brouard  7376:     strcpy(modelsav,model); 
                   7377:     if ((strpt=strstr(model,"age*age")) !=0){
                   7378:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7379:       if(strpt != model){
                   7380:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7381:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7382:  corresponding column of parameters.\n",model);
                   7383:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7384:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7385:  corresponding column of parameters.\n",model); fflush(ficlog);
                   7386:       return 1;
                   7387:     }
                   7388: 
                   7389:       nagesqr=1;
                   7390:       if (strstr(model,"+age*age") !=0)
                   7391:        substrchaine(modelsav, model, "+age*age");
                   7392:       else if (strstr(model,"age*age+") !=0)
                   7393:        substrchaine(modelsav, model, "age*age+");
                   7394:       else 
                   7395:        substrchaine(modelsav, model, "age*age");
                   7396:     }else
                   7397:       nagesqr=0;
                   7398:     if (strlen(modelsav) >1){
                   7399:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7400:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   7401:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   7402:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   7403:                   * cst, age and age*age 
                   7404:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   7405:                   /* including age products which are counted in cptcovage.
                   7406:                  * but the covariates which are products must be treated 
                   7407:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   7408:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7409:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7410: 
                   7411:     
                   7412:       /*   Design
                   7413:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7414:        *  <          ncovcol=8                >
                   7415:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7416:        *   k=  1    2      3       4     5       6      7        8
                   7417:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7418:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   7419:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   7420:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   7421:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7422:        *  Tage[++cptcovage]=k
                   7423:        *       if products, new covar are created after ncovcol with k1
                   7424:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7425:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7426:        *  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
                   7427:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7428:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7429:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7430:        *  <          ncovcol=8                >
                   7431:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7432:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7433:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7434:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7435:        * p Tprod[1]@2={                         6, 5}
                   7436:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7437:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7438:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7439:        *How to reorganize?
                   7440:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7441:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7442:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7443:        * Struct []
                   7444:        */
1.145     brouard  7445: 
1.187     brouard  7446:       /* This loop fills the array Tvar from the string 'model'.*/
                   7447:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7448:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7449:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7450:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7451:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7452:       /*       k=1 Tvar[1]=2 (from V2) */
                   7453:       /*       k=5 Tvar[5] */
                   7454:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7455:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7456:       /*       } */
1.198     brouard  7457:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7458:       /*
                   7459:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7460:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7461:         Tvar[k]=0;
1.187     brouard  7462:       cptcovage=0;
                   7463:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   7464:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   7465:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   7466:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   7467:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   7468:        /*scanf("%d",i);*/
                   7469:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   7470:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   7471:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   7472:            /* covar is not filled and then is empty */
                   7473:            cptcovprod--;
                   7474:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   7475:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   7476:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   7477:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7478:            /*printf("stre=%s ", stre);*/
                   7479:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   7480:            cptcovprod--;
                   7481:            cutl(stre,strb,strc,'V');
                   7482:            Tvar[k]=atoi(stre);
                   7483:            cptcovage++;
                   7484:            Tage[cptcovage]=k;
                   7485:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   7486:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   7487:            cptcovn++;
                   7488:            cptcovprodnoage++;k1++;
                   7489:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   7490:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   7491:                                   because this model-covariate is a construction we invent a new column
                   7492:                                   ncovcol + k1
                   7493:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   7494:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   7495:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   7496:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   7497:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   7498:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   7499:            k2=k2+2;
                   7500:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   7501:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   7502:            for (i=1; i<=lastobs;i++){
                   7503:              /* Computes the new covariate which is a product of
                   7504:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   7505:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   7506:            }
                   7507:          } /* End age is not in the model */
                   7508:        } /* End if model includes a product */
                   7509:        else { /* no more sum */
                   7510:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   7511:          /*  scanf("%d",i);*/
                   7512:          cutl(strd,strc,strb,'V');
                   7513:          ks++; /**< Number of simple covariates */
1.145     brouard  7514:          cptcovn++;
1.187     brouard  7515:          Tvar[k]=atoi(strd);
                   7516:        }
                   7517:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   7518:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   7519:          scanf("%d",i);*/
                   7520:       } /* end of loop + on total covariates */
                   7521:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7522:   } /* end if strlen(model == 0) */
1.136     brouard  7523:   
                   7524:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7525:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7526: 
                   7527:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   7528:   printf("cptcovprod=%d ", cptcovprod);
                   7529:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   7530: 
                   7531:   scanf("%d ",i);*/
                   7532: 
                   7533: 
1.137     brouard  7534:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7535:   /*endread:*/
1.136     brouard  7536:     printf("Exiting decodemodel: ");
                   7537:     return (1);
                   7538: }
                   7539: 
1.169     brouard  7540: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7541: {
                   7542:   int i, m;
1.218     brouard  7543:   int firstone=0;
                   7544:   
1.136     brouard  7545:   for (i=1; i<=imx; i++) {
                   7546:     for(m=2; (m<= maxwav); m++) {
                   7547:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7548:        anint[m][i]=9999;
1.216     brouard  7549:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7550:          s[m][i]=-1;
1.136     brouard  7551:       }
                   7552:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7553:        *nberr = *nberr + 1;
1.218     brouard  7554:        if(firstone == 0){
                   7555:          firstone=1;
                   7556:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   7557:        }
                   7558:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
1.136     brouard  7559:        s[m][i]=-1;
                   7560:       }
                   7561:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7562:        (*nberr)++;
1.136     brouard  7563:        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]); 
                   7564:        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]); 
                   7565:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7566:       }
                   7567:     }
                   7568:   }
                   7569: 
                   7570:   for (i=1; i<=imx; i++)  {
                   7571:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7572:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7573:       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  7574:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7575:          if(agedc[i]>0){
                   7576:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7577:              agev[m][i]=agedc[i];
1.214     brouard  7578:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7579:            }else {
1.136     brouard  7580:              if ((int)andc[i]!=9999){
                   7581:                nbwarn++;
                   7582:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7583:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7584:                agev[m][i]=-1;
                   7585:              }
                   7586:            }
1.169     brouard  7587:          } /* agedc > 0 */
1.214     brouard  7588:        } /* end if */
1.136     brouard  7589:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7590:                                 years but with the precision of a month */
                   7591:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7592:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7593:            agev[m][i]=1;
                   7594:          else if(agev[m][i] < *agemin){ 
                   7595:            *agemin=agev[m][i];
                   7596:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7597:          }
                   7598:          else if(agev[m][i] >*agemax){
                   7599:            *agemax=agev[m][i];
1.156     brouard  7600:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7601:          }
                   7602:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7603:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7604:        } /* en if 9*/
1.136     brouard  7605:        else { /* =9 */
1.214     brouard  7606:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7607:          agev[m][i]=1;
                   7608:          s[m][i]=-1;
                   7609:        }
                   7610:       }
1.214     brouard  7611:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7612:        agev[m][i]=1;
1.214     brouard  7613:       else{
                   7614:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7615:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7616:        agev[m][i]=0;
                   7617:       }
                   7618:     } /* End for lastpass */
                   7619:   }
1.136     brouard  7620:     
                   7621:   for (i=1; i<=imx; i++)  {
                   7622:     for(m=firstpass; (m<=lastpass); m++){
                   7623:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7624:        (*nberr)++;
1.136     brouard  7625:        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);     
                   7626:        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);     
                   7627:        return 1;
                   7628:       }
                   7629:     }
                   7630:   }
                   7631: 
                   7632:   /*for (i=1; i<=imx; i++){
                   7633:   for (m=firstpass; (m<lastpass); m++){
                   7634:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7635: }
                   7636: 
                   7637: }*/
                   7638: 
                   7639: 
1.139     brouard  7640:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7641:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7642: 
                   7643:   return (0);
1.164     brouard  7644:  /* endread:*/
1.136     brouard  7645:     printf("Exiting calandcheckages: ");
                   7646:     return (1);
                   7647: }
                   7648: 
1.172     brouard  7649: #if defined(_MSC_VER)
                   7650: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7651: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7652: //#include "stdafx.h"
                   7653: //#include <stdio.h>
                   7654: //#include <tchar.h>
                   7655: //#include <windows.h>
                   7656: //#include <iostream>
                   7657: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7658: 
                   7659: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7660: 
                   7661: BOOL IsWow64()
                   7662: {
                   7663:        BOOL bIsWow64 = FALSE;
                   7664: 
                   7665:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7666:        //  (HANDLE, PBOOL);
                   7667: 
                   7668:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7669: 
                   7670:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7671:        const char funcName[] = "IsWow64Process";
                   7672:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7673:                GetProcAddress(module, funcName);
                   7674: 
                   7675:        if (NULL != fnIsWow64Process)
                   7676:        {
                   7677:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7678:                        &bIsWow64))
                   7679:                        //throw std::exception("Unknown error");
                   7680:                        printf("Unknown error\n");
                   7681:        }
                   7682:        return bIsWow64 != FALSE;
                   7683: }
                   7684: #endif
1.177     brouard  7685: 
1.191     brouard  7686: void syscompilerinfo(int logged)
1.167     brouard  7687:  {
                   7688:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7689:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7690:    /* /GS /W3 /Gy
                   7691:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7692:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7693:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7694:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7695:    */ 
                   7696:    /* 64 bits */
1.185     brouard  7697:    /*
                   7698:      /GS /W3 /Gy
                   7699:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7700:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7701:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7702:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7703:    /* Optimization are useless and O3 is slower than O2 */
                   7704:    /*
                   7705:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7706:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7707:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7708:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7709:    */
1.186     brouard  7710:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  7711:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7712:       /PDB:"visual studio
                   7713:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7714:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7715:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7716:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7717:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7718:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7719:       uiAccess='false'"
                   7720:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7721:       /NOLOGO /TLBID:1
                   7722:    */
1.177     brouard  7723: #if defined __INTEL_COMPILER
1.178     brouard  7724: #if defined(__GNUC__)
                   7725:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7726: #endif
1.177     brouard  7727: #elif defined(__GNUC__) 
1.179     brouard  7728: #ifndef  __APPLE__
1.174     brouard  7729: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  7730: #endif
1.177     brouard  7731:    struct utsname sysInfo;
1.178     brouard  7732:    int cross = CROSS;
                   7733:    if (cross){
                   7734:           printf("Cross-");
1.191     brouard  7735:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  7736:    }
1.174     brouard  7737: #endif
                   7738: 
1.171     brouard  7739: #include <stdint.h>
1.178     brouard  7740: 
1.191     brouard  7741:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  7742: #if defined(__clang__)
1.191     brouard  7743:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  7744: #endif
                   7745: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  7746:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  7747: #endif
                   7748: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  7749:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  7750: #endif
                   7751: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  7752:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  7753: #endif
                   7754: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  7755:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  7756: #endif
                   7757: #if defined(_MSC_VER)
1.191     brouard  7758:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  7759: #endif
                   7760: #if defined(__PGI)
1.191     brouard  7761:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  7762: #endif
                   7763: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  7764:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  7765: #endif
1.191     brouard  7766:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  7767:    
1.167     brouard  7768: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7769: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7770:     // Windows (x64 and x86)
1.191     brouard  7771:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  7772: #elif __unix__ // all unices, not all compilers
                   7773:     // Unix
1.191     brouard  7774:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  7775: #elif __linux__
                   7776:     // linux
1.191     brouard  7777:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  7778: #elif __APPLE__
1.174     brouard  7779:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  7780:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  7781: #endif
                   7782: 
                   7783: /*  __MINGW32__          */
                   7784: /*  __CYGWIN__  */
                   7785: /* __MINGW64__  */
                   7786: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7787: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7788: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7789: /* _WIN64  // Defined for applications for Win64. */
                   7790: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7791: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  7792: 
1.167     brouard  7793: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  7794:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  7795: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  7796:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  7797: #else
1.191     brouard  7798:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  7799: #endif
                   7800: 
1.169     brouard  7801: #if defined(__GNUC__)
                   7802: # if defined(__GNUC_PATCHLEVEL__)
                   7803: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7804:                             + __GNUC_MINOR__ * 100 \
                   7805:                             + __GNUC_PATCHLEVEL__)
                   7806: # else
                   7807: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7808:                             + __GNUC_MINOR__ * 100)
                   7809: # endif
1.174     brouard  7810:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  7811:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  7812: 
                   7813:    if (uname(&sysInfo) != -1) {
                   7814:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  7815:         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  7816:    }
                   7817:    else
                   7818:       perror("uname() error");
1.179     brouard  7819:    //#ifndef __INTEL_COMPILER 
                   7820: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  7821:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  7822:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  7823: #endif
1.169     brouard  7824: #endif
1.172     brouard  7825: 
                   7826:    //   void main()
                   7827:    //   {
1.169     brouard  7828: #if defined(_MSC_VER)
1.174     brouard  7829:    if (IsWow64()){
1.191     brouard  7830:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7831:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  7832:    }
                   7833:    else{
1.191     brouard  7834:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7835:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  7836:    }
1.172     brouard  7837:    //     printf("\nPress Enter to continue...");
                   7838:    //     getchar();
                   7839:    //   }
                   7840: 
1.169     brouard  7841: #endif
                   7842:    
1.167     brouard  7843: 
1.219     brouard  7844: }
1.136     brouard  7845: 
1.219     brouard  7846: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  7847:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7848:   int i, j, k, i1 ;
1.202     brouard  7849:   /* double ftolpl = 1.e-10; */
1.180     brouard  7850:   double age, agebase, agelim;
1.203     brouard  7851:   double tot;
1.180     brouard  7852: 
1.202     brouard  7853:   strcpy(filerespl,"PL_");
                   7854:   strcat(filerespl,fileresu);
                   7855:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7856:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7857:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7858:   }
                   7859:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7860:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7861:   pstamp(ficrespl);
1.203     brouard  7862:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  7863:   fprintf(ficrespl,"#Age ");
                   7864:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7865:   fprintf(ficrespl,"\n");
1.180     brouard  7866:   
1.219     brouard  7867:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  7868: 
1.219     brouard  7869:   agebase=ageminpar;
                   7870:   agelim=agemaxpar;
1.180     brouard  7871: 
1.219     brouard  7872:   i1=pow(2,cptcoveff);
                   7873:   if (cptcovn < 1){i1=1;}
1.180     brouard  7874: 
1.220     brouard  7875:   for(k=1; k<=i1;k++){
                   7876:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  7877:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  7878:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  7879:     /* k=k+1; */
1.219     brouard  7880:     /* to clean */
                   7881:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   7882:     fprintf(ficrespl,"#******");
                   7883:     printf("#******");
                   7884:     fprintf(ficlog,"#******");
                   7885:     for(j=1;j<=cptcoveff;j++) {
                   7886:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7887:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7888:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7889:     }
                   7890:     fprintf(ficrespl,"******\n");
                   7891:     printf("******\n");
                   7892:     fprintf(ficlog,"******\n");
1.220     brouard  7893:                if(invalidvarcomb[k]){
                   7894:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   7895:                                                fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
                   7896:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   7897:                                                continue;
                   7898:                }
1.219     brouard  7899: 
                   7900:     fprintf(ficrespl,"#Age ");
                   7901:     for(j=1;j<=cptcoveff;j++) {
                   7902:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7903:     }
                   7904:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   7905:     fprintf(ficrespl,"Total Years_to_converge\n");
                   7906:        
                   7907:     for (age=agebase; age<=agelim; age++){
                   7908:       /* for (age=agebase; age<=agebase; age++){ */
                   7909:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   7910:       fprintf(ficrespl,"%.0f ",age );
                   7911:       for(j=1;j<=cptcoveff;j++)
1.220     brouard  7912:                                                        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  7913:       tot=0.;
                   7914:       for(i=1; i<=nlstate;i++){
1.220     brouard  7915:                                                        tot +=  prlim[i][i];
                   7916:                                                        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  7917:       }
                   7918:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   7919:     } /* Age */
                   7920:     /* was end of cptcod */
                   7921:   } /* cptcov */
                   7922:   return 0;
1.180     brouard  7923: }
                   7924: 
1.218     brouard  7925: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
                   7926:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   7927:        
                   7928:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   7929:    * at any age between ageminpar and agemaxpar
                   7930:         */
1.217     brouard  7931:   int i, j, k, i1 ;
                   7932:   /* double ftolpl = 1.e-10; */
                   7933:   double age, agebase, agelim;
                   7934:   double tot;
1.218     brouard  7935:   /* double ***mobaverage; */
                   7936:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  7937: 
                   7938:   strcpy(fileresplb,"PLB_");
                   7939:   strcat(fileresplb,fileresu);
                   7940:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   7941:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7942:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   7943:   }
                   7944:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7945:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   7946:   pstamp(ficresplb);
                   7947:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   7948:   fprintf(ficresplb,"#Age ");
                   7949:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   7950:   fprintf(ficresplb,"\n");
                   7951:   
1.218     brouard  7952:   
                   7953:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   7954:   
                   7955:   agebase=ageminpar;
                   7956:   agelim=agemaxpar;
                   7957:   
                   7958:   
                   7959:   i1=pow(2,cptcoveff);
                   7960:   if (cptcovn < 1){i1=1;}
1.220     brouard  7961: 
                   7962:        for(k=1; k<=i1;k++){ 
                   7963:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.217     brouard  7964:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.218     brouard  7965:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  7966:     /* k=k+1; */
1.218     brouard  7967:     /* to clean */
                   7968:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   7969:     fprintf(ficresplb,"#******");
                   7970:     printf("#******");
                   7971:     fprintf(ficlog,"#******");
                   7972:     for(j=1;j<=cptcoveff;j++) {
                   7973:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7974:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7975:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7976:     }
                   7977:     fprintf(ficresplb,"******\n");
                   7978:     printf("******\n");
                   7979:     fprintf(ficlog,"******\n");
1.220     brouard  7980:                if(invalidvarcomb[k]){
                   7981:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   7982:                                                fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   7983:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   7984:                                                continue;
                   7985:                }
1.218     brouard  7986:     
                   7987:     fprintf(ficresplb,"#Age ");
                   7988:     for(j=1;j<=cptcoveff;j++) {
                   7989:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7990:     }
                   7991:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   7992:     fprintf(ficresplb,"Total Years_to_converge\n");
                   7993:     
                   7994:     
                   7995:     for (age=agebase; age<=agelim; age++){
                   7996:       /* for (age=agebase; age<=agebase; age++){ */
                   7997:       if(mobilavproj > 0){
                   7998:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   7999:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.219     brouard  8000:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8001:       }else if (mobilavproj == 0){
1.219     brouard  8002:                                printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   8003:                                fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   8004:                                exit(1);
1.218     brouard  8005:       }else{
1.219     brouard  8006:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8007:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8008:       }
                   8009:       fprintf(ficresplb,"%.0f ",age );
                   8010:       for(j=1;j<=cptcoveff;j++)
1.219     brouard  8011:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  8012:       tot=0.;
                   8013:       for(i=1; i<=nlstate;i++){
1.219     brouard  8014:                                tot +=  bprlim[i][i];
                   8015:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  8016:       }
                   8017:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8018:     } /* Age */
                   8019:     /* was end of cptcod */
                   8020:   } /* cptcov */
                   8021:   
                   8022:   /* hBijx(p, bage, fage); */
                   8023:   /* fclose(ficrespijb); */
                   8024:   
                   8025:   return 0;
1.217     brouard  8026: }
1.218     brouard  8027:  
1.180     brouard  8028: int hPijx(double *p, int bage, int fage){
                   8029:     /*------------- h Pij x at various ages ------------*/
                   8030: 
                   8031:   int stepsize;
                   8032:   int agelim;
                   8033:   int hstepm;
                   8034:   int nhstepm;
                   8035:   int h, i, i1, j, k;
                   8036: 
                   8037:   double agedeb;
                   8038:   double ***p3mat;
                   8039: 
1.201     brouard  8040:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  8041:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8042:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8043:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8044:     }
                   8045:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8046:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8047:   
                   8048:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8049:     /*if (stepm<=24) stepsize=2;*/
                   8050: 
                   8051:     agelim=AGESUP;
                   8052:     hstepm=stepsize*YEARM; /* Every year of age */
                   8053:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  8054:                
1.180     brouard  8055:     /* hstepm=1;   aff par mois*/
                   8056:     pstamp(ficrespij);
                   8057:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   8058:     i1= pow(2,cptcoveff);
1.218     brouard  8059:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8060:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8061:                /*      k=k+1;  */
1.183     brouard  8062:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8063:       fprintf(ficrespij,"\n#****** ");
                   8064:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  8065:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  8066:       fprintf(ficrespij,"******\n");
                   8067:       
                   8068:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8069:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8070:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8071:        
                   8072:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  8073:        
1.183     brouard  8074:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8075:        oldm=oldms;savm=savms;
                   8076:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8077:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8078:        for(i=1; i<=nlstate;i++)
                   8079:          for(j=1; j<=nlstate+ndeath;j++)
                   8080:            fprintf(ficrespij," %1d-%1d",i,j);
                   8081:        fprintf(ficrespij,"\n");
                   8082:        for (h=0; h<=nhstepm; h++){
                   8083:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8084:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  8085:          for(i=1; i<=nlstate;i++)
                   8086:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  8087:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  8088:          fprintf(ficrespij,"\n");
                   8089:        }
1.183     brouard  8090:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8091:        fprintf(ficrespij,"\n");
                   8092:       }
1.180     brouard  8093:       /*}*/
                   8094:     }
1.218     brouard  8095:     return 0;
1.180     brouard  8096: }
1.218     brouard  8097:  
                   8098:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  8099:     /*------------- h Bij x at various ages ------------*/
                   8100: 
                   8101:   int stepsize;
1.218     brouard  8102:   /* int agelim; */
                   8103:        int ageminl;
1.217     brouard  8104:   int hstepm;
                   8105:   int nhstepm;
                   8106:   int h, i, i1, j, k;
1.218     brouard  8107:        
1.217     brouard  8108:   double agedeb;
                   8109:   double ***p3mat;
1.218     brouard  8110:        
                   8111:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8112:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8113:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8114:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8115:   }
                   8116:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8117:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8118:   
                   8119:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8120:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  8121:   
1.218     brouard  8122:   /* agelim=AGESUP; */
                   8123:   ageminl=30;
                   8124:   hstepm=stepsize*YEARM; /* Every year of age */
                   8125:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8126:   
                   8127:   /* hstepm=1;   aff par mois*/
                   8128:   pstamp(ficrespijb);
                   8129:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
                   8130:   i1= pow(2,cptcoveff);
                   8131:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8132:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8133:   /*   k=k+1;  */
                   8134:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8135:     fprintf(ficrespijb,"\n#****** ");
                   8136:     for(j=1;j<=cptcoveff;j++)
                   8137:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8138:     fprintf(ficrespijb,"******\n");
1.222   ! brouard  8139:     if(invalidvarcomb[k]){
        !          8140:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
        !          8141:       continue;
        !          8142:     }
1.218     brouard  8143:     
                   8144:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8145:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8146:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8147:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8148:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8149:       
                   8150:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8151:       
                   8152:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8153:       /* oldm=oldms;savm=savms; */
                   8154:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8155:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8156:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8157:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8158:       for(i=1; i<=nlstate;i++)
                   8159:        for(j=1; j<=nlstate+ndeath;j++)
                   8160:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8161:       fprintf(ficrespijb,"\n");
                   8162:       for (h=0; h<=nhstepm; h++){
                   8163:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8164:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8165:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8166:        for(i=1; i<=nlstate;i++)
                   8167:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8168:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8169:        fprintf(ficrespijb,"\n");
                   8170:       }
1.218     brouard  8171:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8172:       fprintf(ficrespijb,"\n");
1.217     brouard  8173:     }
1.218     brouard  8174:     /*}*/
                   8175:   }
                   8176:   return 0;
                   8177:  } /*  hBijx */
1.217     brouard  8178: 
1.180     brouard  8179: 
1.136     brouard  8180: /***********************************************/
                   8181: /**************** Main Program *****************/
                   8182: /***********************************************/
                   8183: 
                   8184: int main(int argc, char *argv[])
                   8185: {
                   8186: #ifdef GSL
                   8187:   const gsl_multimin_fminimizer_type *T;
                   8188:   size_t iteri = 0, it;
                   8189:   int rval = GSL_CONTINUE;
                   8190:   int status = GSL_SUCCESS;
                   8191:   double ssval;
                   8192: #endif
                   8193:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8194:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8195:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8196:   int jj, ll, li, lj, lk;
1.136     brouard  8197:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8198:   int num_filled;
1.136     brouard  8199:   int itimes;
                   8200:   int NDIM=2;
                   8201:   int vpopbased=0;
                   8202: 
1.164     brouard  8203:   char ca[32], cb[32];
1.136     brouard  8204:   /*  FILE *fichtm; *//* Html File */
                   8205:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8206:   struct stat info;
1.191     brouard  8207:   double agedeb=0.;
1.194     brouard  8208: 
                   8209:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  8210:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  8211: 
1.165     brouard  8212:   double fret;
1.191     brouard  8213:   double dum=0.; /* Dummy variable */
1.136     brouard  8214:   double ***p3mat;
1.218     brouard  8215:   /* double ***mobaverage; */
1.164     brouard  8216: 
                   8217:   char line[MAXLINE];
1.197     brouard  8218:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8219: 
                   8220:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  8221:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  8222:   char *tok, *val; /* pathtot */
1.136     brouard  8223:   int firstobs=1, lastobs=10;
1.195     brouard  8224:   int c,  h , cpt, c2;
1.191     brouard  8225:   int jl=0;
                   8226:   int i1, j1, jk, stepsize=0;
1.194     brouard  8227:   int count=0;
                   8228: 
1.164     brouard  8229:   int *tab; 
1.136     brouard  8230:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  8231:   int backcast=0;
1.136     brouard  8232:   int mobilav=0,popforecast=0;
1.191     brouard  8233:   int hstepm=0, nhstepm=0;
1.136     brouard  8234:   int agemortsup;
                   8235:   float  sumlpop=0.;
                   8236:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8237:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8238: 
1.191     brouard  8239:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  8240:   double ftolpl=FTOL;
                   8241:   double **prlim;
1.217     brouard  8242:   double **bprlim;
1.136     brouard  8243:   double ***param; /* Matrix of parameters */
                   8244:   double  *p;
                   8245:   double **matcov; /* Matrix of covariance */
1.203     brouard  8246:   double **hess; /* Hessian matrix */
1.136     brouard  8247:   double ***delti3; /* Scale */
                   8248:   double *delti; /* Scale */
                   8249:   double ***eij, ***vareij;
                   8250:   double **varpl; /* Variances of prevalence limits by age */
                   8251:   double *epj, vepp;
1.164     brouard  8252: 
1.136     brouard  8253:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  8254:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8255: 
1.136     brouard  8256:   double **ximort;
1.145     brouard  8257:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  8258:   int *dcwave;
                   8259: 
1.164     brouard  8260:   char z[1]="c";
1.136     brouard  8261: 
                   8262:   /*char  *strt;*/
                   8263:   char strtend[80];
1.126     brouard  8264: 
1.164     brouard  8265: 
1.126     brouard  8266: /*   setlocale (LC_ALL, ""); */
                   8267: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8268: /*   textdomain (PACKAGE); */
                   8269: /*   setlocale (LC_CTYPE, ""); */
                   8270: /*   setlocale (LC_MESSAGES, ""); */
                   8271: 
                   8272:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  8273:   rstart_time = time(NULL);  
                   8274:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8275:   start_time = *localtime(&rstart_time);
1.126     brouard  8276:   curr_time=start_time;
1.157     brouard  8277:   /*tml = *localtime(&start_time.tm_sec);*/
                   8278:   /* strcpy(strstart,asctime(&tml)); */
                   8279:   strcpy(strstart,asctime(&start_time));
1.126     brouard  8280: 
                   8281: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  8282: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8283: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  8284: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8285: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8286: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  8287: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  8288: /*   strt=asctime(&tmg); */
                   8289: /*   printf("Time(after) =%s",strstart);  */
                   8290: /*  (void) time (&time_value);
                   8291: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8292: *  tm = *localtime(&time_value);
                   8293: *  strstart=asctime(&tm);
                   8294: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8295: */
                   8296: 
                   8297:   nberr=0; /* Number of errors and warnings */
                   8298:   nbwarn=0;
1.184     brouard  8299: #ifdef WIN32
                   8300:   _getcwd(pathcd, size);
                   8301: #else
1.126     brouard  8302:   getcwd(pathcd, size);
1.184     brouard  8303: #endif
1.191     brouard  8304:   syscompilerinfo(0);
1.196     brouard  8305:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  8306:   if(argc <=1){
                   8307:     printf("\nEnter the parameter file name: ");
1.205     brouard  8308:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8309:       printf("ERROR Empty parameter file name\n");
                   8310:       goto end;
                   8311:     }
1.126     brouard  8312:     i=strlen(pathr);
                   8313:     if(pathr[i-1]=='\n')
                   8314:       pathr[i-1]='\0';
1.156     brouard  8315:     i=strlen(pathr);
1.205     brouard  8316:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  8317:       pathr[i-1]='\0';
1.205     brouard  8318:     }
                   8319:     i=strlen(pathr);
                   8320:     if( i==0 ){
                   8321:       printf("ERROR Empty parameter file name\n");
                   8322:       goto end;
                   8323:     }
                   8324:     for (tok = pathr; tok != NULL; ){
1.126     brouard  8325:       printf("Pathr |%s|\n",pathr);
                   8326:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8327:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8328:       strcpy (pathtot, val);
                   8329:       if(pathr[0] == '\0') break; /* Dirty */
                   8330:     }
                   8331:   }
                   8332:   else{
                   8333:     strcpy(pathtot,argv[1]);
                   8334:   }
                   8335:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8336:   /*cygwin_split_path(pathtot,path,optionfile);
                   8337:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8338:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8339: 
                   8340:   /* Split argv[0], imach program to get pathimach */
                   8341:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8342:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8343:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8344:  /*   strcpy(pathimach,argv[0]); */
                   8345:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8346:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8347:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  8348: #ifdef WIN32
                   8349:   _chdir(path); /* Can be a relative path */
                   8350:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8351: #else
1.126     brouard  8352:   chdir(path); /* Can be a relative path */
1.184     brouard  8353:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8354: #endif
                   8355:   printf("Current directory %s!\n",pathcd);
1.126     brouard  8356:   strcpy(command,"mkdir ");
                   8357:   strcat(command,optionfilefiname);
                   8358:   if((outcmd=system(command)) != 0){
1.169     brouard  8359:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  8360:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8361:     /* fclose(ficlog); */
                   8362: /*     exit(1); */
                   8363:   }
                   8364: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8365: /*     perror("mkdir"); */
                   8366: /*   } */
                   8367: 
                   8368:   /*-------- arguments in the command line --------*/
                   8369: 
1.186     brouard  8370:   /* Main Log file */
1.126     brouard  8371:   strcat(filelog, optionfilefiname);
                   8372:   strcat(filelog,".log");    /* */
                   8373:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8374:     printf("Problem with logfile %s\n",filelog);
                   8375:     goto end;
                   8376:   }
                   8377:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  8378:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  8379:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8380:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8381:  path=%s \n\
                   8382:  optionfile=%s\n\
                   8383:  optionfilext=%s\n\
1.156     brouard  8384:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  8385: 
1.197     brouard  8386:   syscompilerinfo(1);
1.167     brouard  8387: 
1.126     brouard  8388:   printf("Local time (at start):%s",strstart);
                   8389:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8390:   fflush(ficlog);
                   8391: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  8392: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  8393: 
                   8394:   /* */
                   8395:   strcpy(fileres,"r");
                   8396:   strcat(fileres, optionfilefiname);
1.201     brouard  8397:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  8398:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  8399:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  8400: 
1.186     brouard  8401:   /* Main ---------arguments file --------*/
1.126     brouard  8402: 
                   8403:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  8404:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8405:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  8406:     fflush(ficlog);
1.149     brouard  8407:     /* goto end; */
                   8408:     exit(70); 
1.126     brouard  8409:   }
                   8410: 
                   8411: 
                   8412: 
                   8413:   strcpy(filereso,"o");
1.201     brouard  8414:   strcat(filereso,fileresu);
1.126     brouard  8415:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8416:     printf("Problem with Output resultfile: %s\n", filereso);
                   8417:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8418:     fflush(ficlog);
                   8419:     goto end;
                   8420:   }
                   8421: 
                   8422:   /* Reads comments: lines beginning with '#' */
                   8423:   numlinepar=0;
1.197     brouard  8424: 
                   8425:     /* First parameter line */
                   8426:   while(fgets(line, MAXLINE, ficpar)) {
                   8427:     /* If line starts with a # it is a comment */
                   8428:     if (line[0] == '#') {
                   8429:       numlinepar++;
                   8430:       fputs(line,stdout);
                   8431:       fputs(line,ficparo);
                   8432:       fputs(line,ficlog);
                   8433:       continue;
                   8434:     }else
                   8435:       break;
                   8436:   }
                   8437:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8438:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8439:     if (num_filled != 5) {
                   8440:       printf("Should be 5 parameters\n");
                   8441:     }
1.126     brouard  8442:     numlinepar++;
1.197     brouard  8443:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8444:   }
                   8445:   /* Second parameter line */
                   8446:   while(fgets(line, MAXLINE, ficpar)) {
                   8447:     /* If line starts with a # it is a comment */
                   8448:     if (line[0] == '#') {
                   8449:       numlinepar++;
                   8450:       fputs(line,stdout);
                   8451:       fputs(line,ficparo);
                   8452:       fputs(line,ficlog);
                   8453:       continue;
                   8454:     }else
                   8455:       break;
                   8456:   }
                   8457:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   8458:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8459:     if (num_filled != 8) {
1.209     brouard  8460:       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");
                   8461:       printf("but line=%s\n",line);
1.197     brouard  8462:     }
                   8463:     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  8464:   }
1.203     brouard  8465:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8466:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8467:   /* Third parameter line */
                   8468:   while(fgets(line, MAXLINE, ficpar)) {
                   8469:     /* If line starts with a # it is a comment */
                   8470:     if (line[0] == '#') {
                   8471:       numlinepar++;
                   8472:       fputs(line,stdout);
                   8473:       fputs(line,ficparo);
                   8474:       fputs(line,ficlog);
                   8475:       continue;
                   8476:     }else
                   8477:       break;
                   8478:   }
1.201     brouard  8479:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8480:     if (num_filled == 0)
                   8481:             model[0]='\0';
                   8482:     else if (num_filled != 1){
1.197     brouard  8483:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8484:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8485:       model[0]='\0';
                   8486:       goto end;
                   8487:     }
                   8488:     else{
                   8489:       if (model[0]=='+'){
                   8490:        for(i=1; i<=strlen(model);i++)
                   8491:          modeltemp[i-1]=model[i];
1.201     brouard  8492:        strcpy(model,modeltemp); 
1.197     brouard  8493:       }
                   8494:     }
1.199     brouard  8495:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8496:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8497:   }
                   8498:   /* 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); */
                   8499:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8500:   /* 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  8501:   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);
                   8502:   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  8503:   fflush(ficlog);
1.190     brouard  8504:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8505:   if(model[0]=='#'){
1.187     brouard  8506:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8507:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8508:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8509:     if(mle != -1){
                   8510:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8511:       exit(1);
                   8512:     }
                   8513:   }
1.126     brouard  8514:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8515:     ungetc(c,ficpar);
                   8516:     fgets(line, MAXLINE, ficpar);
                   8517:     numlinepar++;
1.195     brouard  8518:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8519:       z[0]=line[1];
                   8520:     }
                   8521:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8522:     fputs(line, stdout);
                   8523:     //puts(line);
1.126     brouard  8524:     fputs(line,ficparo);
                   8525:     fputs(line,ficlog);
                   8526:   }
                   8527:   ungetc(c,ficpar);
                   8528: 
                   8529:    
1.145     brouard  8530:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  8531:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8532:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8533:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8534:   */
                   8535:   if (strlen(model)>1) 
1.187     brouard  8536:     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  8537:   else
1.187     brouard  8538:     ncovmodel=2; /* Constant and age */
1.133     brouard  8539:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8540:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8541:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8542:     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);
                   8543:     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);
                   8544:     fflush(stdout);
                   8545:     fclose (ficlog);
                   8546:     goto end;
                   8547:   }
1.126     brouard  8548:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8549:   delti=delti3[1][1];
                   8550:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8551:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8552:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8553:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8554:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8555:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8556:     fclose (ficparo);
                   8557:     fclose (ficlog);
                   8558:     goto end;
                   8559:     exit(0);
1.220     brouard  8560:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  8561:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8562:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8563:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8564:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8565:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8566:     hess=matrix(1,npar,1,npar);
1.220     brouard  8567:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  8568:     /* Read guessed parameters */
1.126     brouard  8569:     /* Reads comments: lines beginning with '#' */
                   8570:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8571:       ungetc(c,ficpar);
                   8572:       fgets(line, MAXLINE, ficpar);
                   8573:       numlinepar++;
1.141     brouard  8574:       fputs(line,stdout);
1.126     brouard  8575:       fputs(line,ficparo);
                   8576:       fputs(line,ficlog);
                   8577:     }
                   8578:     ungetc(c,ficpar);
                   8579:     
                   8580:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8581:     for(i=1; i <=nlstate; i++){
1.220     brouard  8582:                        j=0;
1.126     brouard  8583:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.220     brouard  8584:                                if(jj==i) continue;
                   8585:                                j++;
                   8586:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8587:                                if ((i1 != i) || (j1 != jj)){
                   8588:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  8589: It might be a problem of design; if ncovcol and the model are correct\n \
                   8590: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.220     brouard  8591:                                        exit(1);
                   8592:                                }
                   8593:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8594:                                if(mle==1)
                   8595:                                        printf("%1d%1d",i,jj);
                   8596:                                fprintf(ficlog,"%1d%1d",i,jj);
                   8597:                                for(k=1; k<=ncovmodel;k++){
                   8598:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   8599:                                        if(mle==1){
                   8600:                                                printf(" %lf",param[i][j][k]);
                   8601:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8602:                                        }
                   8603:                                        else
                   8604:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8605:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   8606:                                }
                   8607:                                fscanf(ficpar,"\n");
                   8608:                                numlinepar++;
                   8609:                                if(mle==1)
                   8610:                                        printf("\n");
                   8611:                                fprintf(ficlog,"\n");
                   8612:                                fprintf(ficparo,"\n");
1.126     brouard  8613:       }
                   8614:     }  
                   8615:     fflush(ficlog);
                   8616: 
1.145     brouard  8617:     /* Reads scales values */
1.126     brouard  8618:     p=param[1][1];
                   8619:     
                   8620:     /* Reads comments: lines beginning with '#' */
                   8621:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8622:       ungetc(c,ficpar);
                   8623:       fgets(line, MAXLINE, ficpar);
                   8624:       numlinepar++;
1.141     brouard  8625:       fputs(line,stdout);
1.126     brouard  8626:       fputs(line,ficparo);
                   8627:       fputs(line,ficlog);
                   8628:     }
                   8629:     ungetc(c,ficpar);
                   8630: 
                   8631:     for(i=1; i <=nlstate; i++){
                   8632:       for(j=1; j <=nlstate+ndeath-1; j++){
1.220     brouard  8633:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8634:                                if ( (i1-i) * (j1-j) != 0){
                   8635:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8636:                                        exit(1);
                   8637:                                }
                   8638:                                printf("%1d%1d",i,j);
                   8639:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8640:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   8641:                                for(k=1; k<=ncovmodel;k++){
                   8642:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8643:                                        printf(" %le",delti3[i][j][k]);
                   8644:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   8645:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   8646:                                }
                   8647:                                fscanf(ficpar,"\n");
                   8648:                                numlinepar++;
                   8649:                                printf("\n");
                   8650:                                fprintf(ficparo,"\n");
                   8651:                                fprintf(ficlog,"\n");
1.126     brouard  8652:       }
                   8653:     }
                   8654:     fflush(ficlog);
1.220     brouard  8655:                
1.145     brouard  8656:     /* Reads covariance matrix */
1.126     brouard  8657:     delti=delti3[1][1];
1.220     brouard  8658:                
                   8659:                
1.126     brouard  8660:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
1.220     brouard  8661:                
1.126     brouard  8662:     /* Reads comments: lines beginning with '#' */
                   8663:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8664:       ungetc(c,ficpar);
                   8665:       fgets(line, MAXLINE, ficpar);
                   8666:       numlinepar++;
1.141     brouard  8667:       fputs(line,stdout);
1.126     brouard  8668:       fputs(line,ficparo);
                   8669:       fputs(line,ficlog);
                   8670:     }
                   8671:     ungetc(c,ficpar);
1.220     brouard  8672:                
1.126     brouard  8673:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8674:     hess=matrix(1,npar,1,npar);
1.131     brouard  8675:     for(i=1; i <=npar; i++)
                   8676:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  8677:                
1.194     brouard  8678:     /* Scans npar lines */
1.126     brouard  8679:     for(i=1; i <=npar; i++){
1.194     brouard  8680:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8681:       if(count != 3){
1.220     brouard  8682:                                printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8683: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8684: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8685:                                fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8686: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8687: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8688:                                exit(1);
                   8689:       }else{
                   8690:                                if(mle==1)
                   8691:                                        printf("%1d%1d%1d",i1,j1,jk);
                   8692:                        }
1.194     brouard  8693:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8694:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  8695:       for(j=1; j <=i; j++){
1.220     brouard  8696:                                fscanf(ficpar," %le",&matcov[i][j]);
                   8697:                                if(mle==1){
                   8698:                                        printf(" %.5le",matcov[i][j]);
                   8699:                                }
                   8700:                                fprintf(ficlog," %.5le",matcov[i][j]);
                   8701:                                fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  8702:       }
                   8703:       fscanf(ficpar,"\n");
                   8704:       numlinepar++;
                   8705:       if(mle==1)
1.220     brouard  8706:                                printf("\n");
1.126     brouard  8707:       fprintf(ficlog,"\n");
                   8708:       fprintf(ficparo,"\n");
                   8709:     }
1.194     brouard  8710:     /* End of read covariance matrix npar lines */
1.126     brouard  8711:     for(i=1; i <=npar; i++)
                   8712:       for(j=i+1;j<=npar;j++)
1.220     brouard  8713:                                matcov[i][j]=matcov[j][i];
1.126     brouard  8714:     
                   8715:     if(mle==1)
                   8716:       printf("\n");
                   8717:     fprintf(ficlog,"\n");
                   8718:     
                   8719:     fflush(ficlog);
                   8720:     
                   8721:     /*-------- Rewriting parameter file ----------*/
                   8722:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8723:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8724:     strcat(rfileres,".");    /* */
                   8725:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8726:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  8727:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8728:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  8729:     }
                   8730:     fprintf(ficres,"#%s\n",version);
                   8731:   }    /* End of mle != -3 */
1.218     brouard  8732:   
1.186     brouard  8733:   /*  Main data
                   8734:    */
1.126     brouard  8735:   n= lastobs;
                   8736:   num=lvector(1,n);
                   8737:   moisnais=vector(1,n);
                   8738:   annais=vector(1,n);
                   8739:   moisdc=vector(1,n);
                   8740:   andc=vector(1,n);
1.220     brouard  8741:   weight=vector(1,n);
1.126     brouard  8742:   agedc=vector(1,n);
                   8743:   cod=ivector(1,n);
1.220     brouard  8744:   for(i=1;i<=n;i++){
                   8745:                num[i]=0;
                   8746:                moisnais[i]=0;
                   8747:                annais[i]=0;
                   8748:                moisdc[i]=0;
                   8749:                andc[i]=0;
                   8750:                agedc[i]=0;
                   8751:                cod[i]=0;
                   8752:                weight[i]=1.0; /* Equal weights, 1 by default */
                   8753:        }
1.126     brouard  8754:   mint=matrix(1,maxwav,1,n);
                   8755:   anint=matrix(1,maxwav,1,n);
1.131     brouard  8756:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  8757:   tab=ivector(1,NCOVMAX);
1.144     brouard  8758:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  8759:   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  8760: 
1.136     brouard  8761:   /* Reads data from file datafile */
                   8762:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8763:     goto end;
                   8764: 
                   8765:   /* Calculation of the number of parameters from char model */
1.137     brouard  8766:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8767:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8768:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8769:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8770:        k=1 Tvar[1]=2 (from V2)
                   8771:     */
                   8772:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8773:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8774:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8775:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8776:   */
                   8777:   /* For model-covariate k tells which data-covariate to use but
                   8778:     because this model-covariate is a construction we invent a new column
                   8779:     ncovcol + k1
                   8780:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8781:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  8782:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  8783:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8784:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8785:   */
1.145     brouard  8786:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8787:   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  8788:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8789:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  8790:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  8791:                         4 covariates (3 plus signs)
                   8792:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8793:                      */  
1.136     brouard  8794: 
1.186     brouard  8795: /* Main decodemodel */
                   8796: 
1.187     brouard  8797: 
1.136     brouard  8798:   if(decodemodel(model, lastobs) == 1)
                   8799:     goto end;
                   8800: 
1.137     brouard  8801:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8802:     nbwarn++;
                   8803:     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); 
                   8804:     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); 
                   8805:   }
1.136     brouard  8806:     /*  if(mle==1){*/
1.137     brouard  8807:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8808:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  8809:   }
                   8810: 
                   8811:     /*-calculation of age at interview from date of interview and age at death -*/
                   8812:   agev=matrix(1,maxwav,1,imx);
                   8813: 
                   8814:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8815:     goto end;
                   8816: 
1.126     brouard  8817: 
1.136     brouard  8818:   agegomp=(int)agemin;
                   8819:   free_vector(moisnais,1,n);
                   8820:   free_vector(annais,1,n);
1.126     brouard  8821:   /* free_matrix(mint,1,maxwav,1,n);
                   8822:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  8823:   /* free_vector(moisdc,1,n); */
                   8824:   /* free_vector(andc,1,n); */
1.145     brouard  8825:   /* */
                   8826:   
1.126     brouard  8827:   wav=ivector(1,imx);
1.214     brouard  8828:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8829:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8830:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8831:   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.*/
                   8832:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8833:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  8834:    
                   8835:   /* Concatenates waves */
1.214     brouard  8836:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8837:      Death is a valid wave (if date is known).
                   8838:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8839:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8840:      and mw[mi+1][i]. dh depends on stepm.
                   8841:   */
                   8842: 
1.126     brouard  8843:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  8844:   /* */
                   8845:  
1.215     brouard  8846:   free_vector(moisdc,1,n);
                   8847:   free_vector(andc,1,n);
                   8848: 
1.126     brouard  8849:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8850:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8851:   ncodemax[1]=1;
1.145     brouard  8852:   Ndum =ivector(-1,NCOVMAX);  
1.220     brouard  8853:        cptcoveff=0;
                   8854:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   8855:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   8856:        }
                   8857:        
                   8858:        ncovcombmax=pow(2,cptcoveff);
                   8859:        invalidvarcomb=ivector(1, ncovcombmax); 
                   8860:        for(i=1;i<ncovcombmax;i++)
                   8861:                invalidvarcomb[i]=0;
                   8862: 
1.211     brouard  8863:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  8864:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  8865:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  8866: 
1.200     brouard  8867:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  8868:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  8869:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  8870:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8871:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   8872:    * (currently 0 or 1) in the data.
                   8873:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   8874:    * corresponding modality (h,j).
                   8875:    */
                   8876: 
1.145     brouard  8877:   h=0;
                   8878:   /*if (cptcovn > 0) */
1.126     brouard  8879:   m=pow(2,cptcoveff);
                   8880:  
1.144     brouard  8881:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  8882:           * For k=4 covariates, h goes from 1 to m=2**k
                   8883:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   8884:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  8885:           *     h\k   1     2     3     4
1.143     brouard  8886:           *______________________________  
                   8887:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   8888:           *     2     2     1     1     1
                   8889:           *     3 i=2 1     2     1     1
                   8890:           *     4     2     2     1     1
                   8891:           *     5 i=3 1 i=2 1     2     1
                   8892:           *     6     2     1     2     1
                   8893:           *     7 i=4 1     2     2     1
                   8894:           *     8     2     2     2     1
1.197     brouard  8895:           *     9 i=5 1 i=3 1 i=2 1     2
                   8896:           *    10     2     1     1     2
                   8897:           *    11 i=6 1     2     1     2
                   8898:           *    12     2     2     1     2
                   8899:           *    13 i=7 1 i=4 1     2     2    
                   8900:           *    14     2     1     2     2
                   8901:           *    15 i=8 1     2     2     2
                   8902:           *    16     2     2     2     2
1.143     brouard  8903:           */
1.212     brouard  8904:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  8905:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   8906:      * and the value of each covariate?
                   8907:      * V1=1, V2=1, V3=2, V4=1 ?
                   8908:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   8909:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   8910:      * In order to get the real value in the data, we use nbcode
                   8911:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   8912:      * We are keeping this crazy system in order to be able (in the future?) 
                   8913:      * to have more than 2 values (0 or 1) for a covariate.
                   8914:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   8915:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   8916:      *              bbbbbbbb
                   8917:      *              76543210     
                   8918:      *   h-1        00000101 (6-1=5)
1.219     brouard  8919:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  8920:      *           &
                   8921:      *     1        00000001 (1)
1.219     brouard  8922:      *              00000000        = 1 & ((h-1) >> (k-1))
                   8923:      *          +1= 00000001 =1 
1.211     brouard  8924:      *
                   8925:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   8926:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   8927:      *    >>k'            11
                   8928:      *          &   00000001
                   8929:      *            = 00000001
                   8930:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   8931:      * Reverse h=6 and m=16?
                   8932:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   8933:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   8934:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   8935:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   8936:      * V3=decodtabm(14,3,2**4)=2
                   8937:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   8938:      *(h-1) >> (j-1)    0011 =13 >> 2
                   8939:      *          &1 000000001
                   8940:      *           = 000000001
                   8941:      *         +1= 000000010 =2
                   8942:      *                  2211
                   8943:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   8944:      *                  V3=2
1.220     brouard  8945:                 * codtabm and decodtabm are identical
1.211     brouard  8946:      */
                   8947: 
1.145     brouard  8948: 
                   8949:  free_ivector(Ndum,-1,NCOVMAX);
                   8950: 
                   8951: 
1.126     brouard  8952:     
1.186     brouard  8953:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  8954:   strcpy(optionfilegnuplot,optionfilefiname);
                   8955:   if(mle==-3)
1.201     brouard  8956:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  8957:   strcat(optionfilegnuplot,".gp");
                   8958: 
                   8959:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   8960:     printf("Problem with file %s",optionfilegnuplot);
                   8961:   }
                   8962:   else{
1.204     brouard  8963:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  8964:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  8965:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   8966:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  8967:   }
                   8968:   /*  fclose(ficgp);*/
1.186     brouard  8969: 
                   8970: 
                   8971:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  8972: 
                   8973:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   8974:   if(mle==-3)
1.201     brouard  8975:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  8976:   strcat(optionfilehtm,".htm");
                   8977:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  8978:     printf("Problem with %s \n",optionfilehtm);
                   8979:     exit(0);
1.126     brouard  8980:   }
                   8981: 
                   8982:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   8983:   strcat(optionfilehtmcov,"-cov.htm");
                   8984:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   8985:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   8986:   }
                   8987:   else{
                   8988:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   8989: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8990: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  8991:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   8992:   }
                   8993: 
1.213     brouard  8994:   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  8995: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   8996: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  8997: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  8998: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  8999: \n\
                   9000: <hr  size=\"2\" color=\"#EC5E5E\">\
                   9001:  <ul><li><h4>Parameter files</h4>\n\
                   9002:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   9003:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   9004:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   9005:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   9006:  - Date and time at start: %s</ul>\n",\
                   9007:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   9008:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   9009:          fileres,fileres,\
                   9010:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   9011:   fflush(fichtm);
                   9012: 
                   9013:   strcpy(pathr,path);
                   9014:   strcat(pathr,optionfilefiname);
1.184     brouard  9015: #ifdef WIN32
                   9016:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9017: #else
1.126     brouard  9018:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  9019: #endif
                   9020:          
1.126     brouard  9021:   
1.220     brouard  9022:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9023:                 and for any valid combination of covariates
1.126     brouard  9024:      and prints on file fileres'p'. */
1.220     brouard  9025:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,   \
1.214     brouard  9026:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  9027: 
                   9028:   fprintf(fichtm,"\n");
                   9029:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9030: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9031: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9032:          imx,agemin,agemax,jmin,jmax,jmean);
                   9033:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  9034:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9035:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9036:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9037:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  9038: 
1.126     brouard  9039:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9040:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9041:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9042: 
                   9043:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  9044:   /* For mortality only */
1.126     brouard  9045:   if (mle==-3){
1.136     brouard  9046:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  9047:                for(i=1;i<=NDIM;i++)
                   9048:                        for(j=1;j<=NDIM;j++)
                   9049:                                ximort[i][j]=0.;
1.186     brouard  9050:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  9051:     cens=ivector(1,n);
                   9052:     ageexmed=vector(1,n);
                   9053:     agecens=vector(1,n);
                   9054:     dcwave=ivector(1,n);
                   9055:  
                   9056:     for (i=1; i<=imx; i++){
                   9057:       dcwave[i]=-1;
                   9058:       for (m=firstpass; m<=lastpass; m++)
1.218     brouard  9059:                                if (s[m][i]>nlstate) {
                   9060:                                        dcwave[i]=m;
                   9061:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9062:                                        break;
                   9063:                                }
1.126     brouard  9064:     }
1.218     brouard  9065:                
1.126     brouard  9066:     for (i=1; i<=imx; i++) {
                   9067:       if (wav[i]>0){
1.218     brouard  9068:                                ageexmed[i]=agev[mw[1][i]][i];
                   9069:                                j=wav[i];
                   9070:                                agecens[i]=1.; 
                   9071:                                
                   9072:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   9073:                                        agecens[i]=agev[mw[j][i]][i];
                   9074:                                        cens[i]= 1;
                   9075:                                }else if (ageexmed[i]< 1) 
                   9076:                                        cens[i]= -1;
                   9077:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9078:                                        cens[i]=0 ;
1.126     brouard  9079:       }
                   9080:       else cens[i]=-1;
                   9081:     }
                   9082:     
                   9083:     for (i=1;i<=NDIM;i++) {
                   9084:       for (j=1;j<=NDIM;j++)
1.218     brouard  9085:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  9086:     }
                   9087:     
1.145     brouard  9088:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  9089:     /*printf("%lf %lf", p[1], p[2]);*/
                   9090:     
                   9091:     
1.136     brouard  9092: #ifdef GSL
                   9093:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  9094: #else
1.126     brouard  9095:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  9096: #endif
1.201     brouard  9097:     strcpy(filerespow,"POW-MORT_"); 
                   9098:     strcat(filerespow,fileresu);
1.126     brouard  9099:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9100:       printf("Problem with resultfile: %s\n", filerespow);
                   9101:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9102:     }
1.136     brouard  9103: #ifdef GSL
                   9104:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  9105: #else
1.126     brouard  9106:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  9107: #endif
1.126     brouard  9108:     /*  for (i=1;i<=nlstate;i++)
                   9109:        for(j=1;j<=nlstate+ndeath;j++)
                   9110:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9111:     */
                   9112:     fprintf(ficrespow,"\n");
1.136     brouard  9113: #ifdef GSL
                   9114:     /* gsl starts here */ 
                   9115:     T = gsl_multimin_fminimizer_nmsimplex;
                   9116:     gsl_multimin_fminimizer *sfm = NULL;
                   9117:     gsl_vector *ss, *x;
                   9118:     gsl_multimin_function minex_func;
                   9119: 
                   9120:     /* Initial vertex size vector */
                   9121:     ss = gsl_vector_alloc (NDIM);
                   9122:     
                   9123:     if (ss == NULL){
                   9124:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9125:     }
                   9126:     /* Set all step sizes to 1 */
                   9127:     gsl_vector_set_all (ss, 0.001);
                   9128: 
                   9129:     /* Starting point */
1.126     brouard  9130:     
1.136     brouard  9131:     x = gsl_vector_alloc (NDIM);
                   9132:     
                   9133:     if (x == NULL){
                   9134:       gsl_vector_free(ss);
                   9135:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9136:     }
                   9137:   
                   9138:     /* Initialize method and iterate */
                   9139:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9140:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9141:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9142:     gsl_vector_set(x, 0, p[1]);
                   9143:     gsl_vector_set(x, 1, p[2]);
                   9144: 
                   9145:     minex_func.f = &gompertz_f;
                   9146:     minex_func.n = NDIM;
                   9147:     minex_func.params = (void *)&p; /* ??? */
                   9148:     
                   9149:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9150:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9151:     
                   9152:     printf("Iterations beginning .....\n\n");
                   9153:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9154: 
                   9155:     iteri=0;
                   9156:     while (rval == GSL_CONTINUE){
                   9157:       iteri++;
                   9158:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9159:       
                   9160:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9161:       fflush(0);
                   9162:       
                   9163:       if (status) 
                   9164:         break;
                   9165:       
                   9166:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9167:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9168:       
                   9169:       if (rval == GSL_SUCCESS)
                   9170:         printf ("converged to a local maximum at\n");
                   9171:       
                   9172:       printf("%5d ", iteri);
                   9173:       for (it = 0; it < NDIM; it++){
                   9174:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9175:       }
                   9176:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9177:     }
                   9178:     
                   9179:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9180:     
                   9181:     gsl_vector_free(x); /* initial values */
                   9182:     gsl_vector_free(ss); /* inital step size */
                   9183:     for (it=0; it<NDIM; it++){
                   9184:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9185:       fprintf(ficrespow," %.12lf", p[it]);
                   9186:     }
                   9187:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9188: #endif
                   9189: #ifdef POWELL
                   9190:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9191: #endif  
1.126     brouard  9192:     fclose(ficrespow);
                   9193:     
1.203     brouard  9194:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  9195: 
                   9196:     for(i=1; i <=NDIM; i++)
                   9197:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  9198:                                matcov[i][j]=matcov[j][i];
1.126     brouard  9199:     
                   9200:     printf("\nCovariance matrix\n ");
1.203     brouard  9201:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  9202:     for(i=1; i <=NDIM; i++) {
                   9203:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  9204:                                printf("%f ",matcov[i][j]);
                   9205:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  9206:       }
1.203     brouard  9207:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  9208:     }
                   9209:     
                   9210:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  9211:     for (i=1;i<=NDIM;i++) {
1.126     brouard  9212:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  9213:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9214:     }
1.126     brouard  9215:     lsurv=vector(1,AGESUP);
                   9216:     lpop=vector(1,AGESUP);
                   9217:     tpop=vector(1,AGESUP);
                   9218:     lsurv[agegomp]=100000;
                   9219:     
                   9220:     for (k=agegomp;k<=AGESUP;k++) {
                   9221:       agemortsup=k;
                   9222:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9223:     }
                   9224:     
                   9225:     for (k=agegomp;k<agemortsup;k++)
                   9226:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9227:     
                   9228:     for (k=agegomp;k<agemortsup;k++){
                   9229:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9230:       sumlpop=sumlpop+lpop[k];
                   9231:     }
                   9232:     
                   9233:     tpop[agegomp]=sumlpop;
                   9234:     for (k=agegomp;k<(agemortsup-3);k++){
                   9235:       /*  tpop[k+1]=2;*/
                   9236:       tpop[k+1]=tpop[k]-lpop[k];
                   9237:     }
                   9238:     
                   9239:     
                   9240:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9241:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9242:       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]);
                   9243:     
                   9244:     
                   9245:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  9246:                ageminpar=50;
                   9247:                agemaxpar=100;
1.194     brouard  9248:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9249:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9250: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9251: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9252:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9253: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9254: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9255:     }else{
                   9256:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9257:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
1.201     brouard  9258:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  9259:                }
1.201     brouard  9260:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  9261:                     stepm, weightopt,\
                   9262:                     model,imx,p,matcov,agemortsup);
                   9263:     
                   9264:     free_vector(lsurv,1,AGESUP);
                   9265:     free_vector(lpop,1,AGESUP);
                   9266:     free_vector(tpop,1,AGESUP);
1.220     brouard  9267:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  9268:     free_ivector(cens,1,n);
                   9269:     free_vector(agecens,1,n);
                   9270:     free_ivector(dcwave,1,n);
1.220     brouard  9271: #ifdef GSL
1.136     brouard  9272: #endif
1.186     brouard  9273:   } /* Endof if mle==-3 mortality only */
1.205     brouard  9274:   /* Standard  */
                   9275:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9276:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9277:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  9278:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  9279:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9280:     for (k=1; k<=npar;k++)
                   9281:       printf(" %d %8.5f",k,p[k]);
                   9282:     printf("\n");
1.205     brouard  9283:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9284:       /* mlikeli uses func not funcone */
                   9285:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9286:     }
                   9287:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9288:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9289:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9290:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9291:     }
                   9292:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  9293:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9294:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9295:     for (k=1; k<=npar;k++)
                   9296:       printf(" %d %8.5f",k,p[k]);
                   9297:     printf("\n");
                   9298:     
                   9299:     /*--------- results files --------------*/
1.192     brouard  9300:     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  9301:     
                   9302:     
                   9303:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9304:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9305:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9306:     for(i=1,jk=1; i <=nlstate; i++){
                   9307:       for(k=1; k <=(nlstate+ndeath); k++){
1.220     brouard  9308:                                if (k != i) {
                   9309:                                        printf("%d%d ",i,k);
                   9310:                                        fprintf(ficlog,"%d%d ",i,k);
                   9311:                                        fprintf(ficres,"%1d%1d ",i,k);
                   9312:                                        for(j=1; j <=ncovmodel; j++){
                   9313:                                                printf("%12.7f ",p[jk]);
                   9314:                                                fprintf(ficlog,"%12.7f ",p[jk]);
                   9315:                                                fprintf(ficres,"%12.7f ",p[jk]);
                   9316:                                                jk++; 
                   9317:                                        }
                   9318:                                        printf("\n");
                   9319:                                        fprintf(ficlog,"\n");
                   9320:                                        fprintf(ficres,"\n");
                   9321:                                }
1.126     brouard  9322:       }
                   9323:     }
1.203     brouard  9324:     if(mle != 0){
                   9325:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  9326:       ftolhess=ftol; /* Usually correct */
1.203     brouard  9327:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9328:       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");
                   9329:       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");
                   9330:       for(i=1,jk=1; i <=nlstate; i++){
1.220     brouard  9331:                                for(k=1; k <=(nlstate+ndeath); k++){
                   9332:                                        if (k != i) {
                   9333:                                                printf("%d%d ",i,k);
                   9334:                                                fprintf(ficlog,"%d%d ",i,k);
                   9335:                                                for(j=1; j <=ncovmodel; j++){
                   9336:                                                        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]));
                   9337:                                                        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]));
                   9338:                                                        jk++; 
                   9339:                                                }
                   9340:                                                printf("\n");
                   9341:                                                fprintf(ficlog,"\n");
                   9342:                                        }
                   9343:                                }
1.193     brouard  9344:       }
1.203     brouard  9345:     } /* end of hesscov and Wald tests */
1.220     brouard  9346:                
1.203     brouard  9347:     /*  */
1.126     brouard  9348:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9349:     printf("# Scales (for hessian or gradient estimation)\n");
                   9350:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9351:     for(i=1,jk=1; i <=nlstate; i++){
                   9352:       for(j=1; j <=nlstate+ndeath; j++){
1.220     brouard  9353:                                if (j!=i) {
                   9354:                                        fprintf(ficres,"%1d%1d",i,j);
                   9355:                                        printf("%1d%1d",i,j);
                   9356:                                        fprintf(ficlog,"%1d%1d",i,j);
                   9357:                                        for(k=1; k<=ncovmodel;k++){
                   9358:                                                printf(" %.5e",delti[jk]);
                   9359:                                                fprintf(ficlog," %.5e",delti[jk]);
                   9360:                                                fprintf(ficres," %.5e",delti[jk]);
                   9361:                                                jk++;
                   9362:                                        }
                   9363:                                        printf("\n");
                   9364:                                        fprintf(ficlog,"\n");
                   9365:                                        fprintf(ficres,"\n");
                   9366:                                }
1.126     brouard  9367:       }
                   9368:     }
                   9369:     
                   9370:     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  9371:     if(mle >= 1) /* To big for the screen */
1.126     brouard  9372:       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");
                   9373:     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");
                   9374:     /* # 121 Var(a12)\n\ */
                   9375:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9376:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9377:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9378:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9379:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9380:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9381:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9382:     
                   9383:     
                   9384:     /* Just to have a covariance matrix which will be more understandable
                   9385:        even is we still don't want to manage dictionary of variables
                   9386:     */
                   9387:     for(itimes=1;itimes<=2;itimes++){
                   9388:       jj=0;
                   9389:       for(i=1; i <=nlstate; i++){
1.220     brouard  9390:                                for(j=1; j <=nlstate+ndeath; j++){
                   9391:                                        if(j==i) continue;
                   9392:                                        for(k=1; k<=ncovmodel;k++){
                   9393:                                                jj++;
                   9394:                                                ca[0]= k+'a'-1;ca[1]='\0';
                   9395:                                                if(itimes==1){
                   9396:                                                        if(mle>=1)
                   9397:                                                                printf("#%1d%1d%d",i,j,k);
                   9398:                                                        fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9399:                                                        fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9400:                                                }else{
                   9401:                                                        if(mle>=1)
                   9402:                                                                printf("%1d%1d%d",i,j,k);
                   9403:                                                        fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9404:                                                        fprintf(ficres,"%1d%1d%d",i,j,k);
                   9405:                                                }
                   9406:                                                ll=0;
                   9407:                                                for(li=1;li <=nlstate; li++){
                   9408:                                                        for(lj=1;lj <=nlstate+ndeath; lj++){
                   9409:                                                                if(lj==li) continue;
                   9410:                                                                for(lk=1;lk<=ncovmodel;lk++){
                   9411:                                                                        ll++;
                   9412:                                                                        if(ll<=jj){
                   9413:                                                                                cb[0]= lk +'a'-1;cb[1]='\0';
                   9414:                                                                                if(ll<jj){
                   9415:                                                                                        if(itimes==1){
                   9416:                                                                                                if(mle>=1)
                   9417:                                                                                                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9418:                                                                                                fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9419:                                                                                                fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9420:                                                                                        }else{
                   9421:                                                                                                if(mle>=1)
                   9422:                                                                                                        printf(" %.5e",matcov[jj][ll]); 
                   9423:                                                                                                fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9424:                                                                                                fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9425:                                                                                        }
                   9426:                                                                                }else{
                   9427:                                                                                        if(itimes==1){
                   9428:                                                                                                if(mle>=1)
                   9429:                                                                                                        printf(" Var(%s%1d%1d)",ca,i,j);
                   9430:                                                                                                fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9431:                                                                                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9432:                                                                                        }else{
                   9433:                                                                                                if(mle>=1)
                   9434:                                                                                                        printf(" %.7e",matcov[jj][ll]); 
                   9435:                                                                                                fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9436:                                                                                                fprintf(ficres," %.7e",matcov[jj][ll]); 
                   9437:                                                                                        }
                   9438:                                                                                }
                   9439:                                                                        }
                   9440:                                                                } /* end lk */
                   9441:                                                        } /* end lj */
                   9442:                                                } /* end li */
                   9443:                                                if(mle>=1)
                   9444:                                                        printf("\n");
                   9445:                                                fprintf(ficlog,"\n");
                   9446:                                                fprintf(ficres,"\n");
                   9447:                                                numlinepar++;
                   9448:                                        } /* end k*/
                   9449:                                } /*end j */
1.126     brouard  9450:       } /* end i */
                   9451:     } /* end itimes */
                   9452:     
                   9453:     fflush(ficlog);
                   9454:     fflush(ficres);
1.220     brouard  9455:                while(fgets(line, MAXLINE, ficpar)) {
                   9456:                        /* If line starts with a # it is a comment */
                   9457:                        if (line[0] == '#') {
                   9458:                                numlinepar++;
                   9459:                                fputs(line,stdout);
                   9460:                                fputs(line,ficparo);
                   9461:                                fputs(line,ficlog);
                   9462:                                continue;
                   9463:                        }else
                   9464:                                break;
                   9465:                }
                   9466:                
1.209     brouard  9467:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9468:     /*   ungetc(c,ficpar); */
                   9469:     /*   fgets(line, MAXLINE, ficpar); */
                   9470:     /*   fputs(line,stdout); */
                   9471:     /*   fputs(line,ficparo); */
                   9472:     /* } */
                   9473:     /* ungetc(c,ficpar); */
1.126     brouard  9474:     
                   9475:     estepm=0;
1.209     brouard  9476:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
1.220     brouard  9477:                        
                   9478:                        if (num_filled != 6) {
                   9479:                                printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   9480:                                fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   9481:                                goto end;
                   9482:                        }
                   9483:                        printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9484:                }
                   9485:                /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9486:                /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9487:                
1.209     brouard  9488:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9489:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9490:     if (fage <= 2) {
                   9491:       bage = ageminpar;
                   9492:       fage = agemaxpar;
                   9493:     }
                   9494:     
                   9495:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9496:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9497:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  9498:                
1.186     brouard  9499:     /* Other stuffs, more or less useful */    
1.126     brouard  9500:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9501:       ungetc(c,ficpar);
                   9502:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9503:       fputs(line,stdout);
1.126     brouard  9504:       fputs(line,ficparo);
                   9505:     }
                   9506:     ungetc(c,ficpar);
                   9507:     
                   9508:     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);
                   9509:     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);
                   9510:     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);
                   9511:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9512:     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);
                   9513:     
                   9514:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9515:       ungetc(c,ficpar);
                   9516:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9517:       fputs(line,stdout);
1.126     brouard  9518:       fputs(line,ficparo);
                   9519:     }
                   9520:     ungetc(c,ficpar);
                   9521:     
                   9522:     
                   9523:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9524:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9525:     
                   9526:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9527:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9528:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9529:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9530:     
                   9531:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9532:       ungetc(c,ficpar);
                   9533:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9534:       fputs(line,stdout);
1.126     brouard  9535:       fputs(line,ficparo);
                   9536:     }
                   9537:     ungetc(c,ficpar);
                   9538:     
                   9539:     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);
                   9540:     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);
                   9541:     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);
                   9542:     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);
                   9543:     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);
                   9544:     /* day and month of proj2 are not used but only year anproj2.*/
                   9545:     
1.217     brouard  9546:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9547:       ungetc(c,ficpar);
                   9548:       fgets(line, MAXLINE, ficpar);
                   9549:       fputs(line,stdout);
                   9550:       fputs(line,ficparo);
                   9551:     }
                   9552:     ungetc(c,ficpar);
                   9553:     
                   9554:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.219     brouard  9555:     fprintf(ficparo,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   9556:     fprintf(ficlog,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   9557:     fprintf(ficres,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.217     brouard  9558:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9559:     
                   9560:     
1.220     brouard  9561:                /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  9562:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9563:     
                   9564:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9565:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.220     brouard  9566:                        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9567: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9568: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9569:                        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9570: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9571: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9572:     }else{
1.218     brouard  9573:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  9574:     }
                   9575:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   9576:                                                                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   9577:                                                                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                   9578:                
                   9579:                /*------------ free_vector  -------------*/
                   9580:                /*  chdir(path); */
                   9581:                
1.215     brouard  9582:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9583:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9584:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9585:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9586:     free_lvector(num,1,n);
                   9587:     free_vector(agedc,1,n);
                   9588:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9589:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9590:     fclose(ficparo);
                   9591:     fclose(ficres);
1.220     brouard  9592:                
                   9593:                
1.186     brouard  9594:     /* Other results (useful)*/
1.220     brouard  9595:                
                   9596:                
1.126     brouard  9597:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9598:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9599:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9600:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9601:     fclose(ficrespl);
                   9602: 
                   9603:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9604:     /*#include "hpijx.h"*/
                   9605:     hPijx(p, bage, fage);
1.145     brouard  9606:     fclose(ficrespij);
1.126     brouard  9607: 
1.220     brouard  9608:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  9609:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  9610:     k=1;
1.126     brouard  9611:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9612: 
1.219     brouard  9613:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  9614:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9615:     for(i=1;i<=AGESUP;i++)
1.219     brouard  9616:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.218     brouard  9617:                                for(k=1;k<=ncovcombmax;k++)
                   9618:                                        probs[i][j][k]=0.;
1.219     brouard  9619:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9620:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   9621:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9622:                        for(i=1;i<=AGESUP;i++)
                   9623:                                for(j=1;j<=nlstate;j++)
                   9624:                                        for(k=1;k<=ncovcombmax;k++)
                   9625:                                                mobaverages[i][j][k]=0.;
                   9626:       mobaverage=mobaverages;
                   9627:       if (mobilav!=0) {
1.218     brouard  9628:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9629:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9630:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9631:                                }
1.219     brouard  9632:       }
                   9633:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   9634:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9635:       else if (mobilavproj !=0) {
1.218     brouard  9636:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9637:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9638:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9639:                                }
1.219     brouard  9640:       }
                   9641:     }/* end if moving average */
                   9642:                
1.126     brouard  9643:     /*---------- Forecasting ------------------*/
                   9644:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9645:     if(prevfcast==1){
                   9646:       /*    if(stepm ==1){*/
1.201     brouard  9647:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  9648:     }
1.217     brouard  9649:     if(backcast==1){
1.219     brouard  9650:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9651:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9652:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   9653: 
                   9654:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9655: 
                   9656:       bprlim=matrix(1,nlstate,1,nlstate);
                   9657:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   9658:       fclose(ficresplb);
                   9659: 
1.222   ! brouard  9660:       hBijx(p, bage, fage, mobaverage);
        !          9661:       fclose(ficrespijb);
1.219     brouard  9662:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9663: 
                   9664:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
                   9665:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   9666:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9667:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9668:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9669:     }
1.217     brouard  9670:     
1.186     brouard  9671:  
                   9672:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9673: 
1.215     brouard  9674:     free_ivector(wav,1,imx);
                   9675:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9676:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9677:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  9678:                
                   9679:                
1.127     brouard  9680:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  9681:                
1.201     brouard  9682:     strcpy(filerese,"E_");
                   9683:     strcat(filerese,fileresu);
1.126     brouard  9684:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9685:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9686:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9687:     }
1.208     brouard  9688:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9689:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  9690:                
1.145     brouard  9691:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.219     brouard  9692:       fprintf(ficreseij,"\n#****** ");
                   9693:       for(j=1;j<=cptcoveff;j++) {
1.220     brouard  9694:                                fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  9695:       }
                   9696:       fprintf(ficreseij,"******\n");
                   9697:       
                   9698:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9699:       oldm=oldms;savm=savms;
                   9700:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  9701:       
1.219     brouard  9702:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  9703:     }
                   9704:     fclose(ficreseij);
1.208     brouard  9705:     printf("done evsij\n");fflush(stdout);
                   9706:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  9707:                
1.127     brouard  9708:     /*---------- Health expectancies and variances ------------*/
1.218     brouard  9709:                
                   9710:                
1.201     brouard  9711:     strcpy(filerest,"T_");
                   9712:     strcat(filerest,fileresu);
1.127     brouard  9713:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9714:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9715:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9716:     }
1.208     brouard  9717:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9718:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  9719:                
1.126     brouard  9720: 
1.201     brouard  9721:     strcpy(fileresstde,"STDE_");
                   9722:     strcat(fileresstde,fileresu);
1.126     brouard  9723:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9724:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9725:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9726:     }
1.208     brouard  9727:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9728:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  9729: 
1.201     brouard  9730:     strcpy(filerescve,"CVE_");
                   9731:     strcat(filerescve,fileresu);
1.126     brouard  9732:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9733:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9734:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9735:     }
1.208     brouard  9736:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9737:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  9738: 
1.201     brouard  9739:     strcpy(fileresv,"V_");
                   9740:     strcat(fileresv,fileresu);
1.126     brouard  9741:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9742:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9743:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9744:     }
1.208     brouard  9745:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9746:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  9747: 
1.145     brouard  9748:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9749:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9750:           
                   9751:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  9752:       fprintf(ficrest,"\n#****** ");
                   9753:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9754:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9755:       fprintf(ficrest,"******\n");
                   9756:       
                   9757:       fprintf(ficresstdeij,"\n#****** ");
                   9758:       fprintf(ficrescveij,"\n#****** ");
                   9759:       for(j=1;j<=cptcoveff;j++) {
1.218     brouard  9760:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9761:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9762:       }
                   9763:       fprintf(ficresstdeij,"******\n");
                   9764:       fprintf(ficrescveij,"******\n");
                   9765:       
                   9766:       fprintf(ficresvij,"\n#****** ");
                   9767:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9768:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9769:       fprintf(ficresvij,"******\n");
                   9770:       
                   9771:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9772:       oldm=oldms;savm=savms;
                   9773:       printf(" cvevsij %d, ",k);
                   9774:       fprintf(ficlog, " cvevsij %d, ",k);
                   9775:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9776:       printf(" end cvevsij \n ");
                   9777:       fprintf(ficlog, " end cvevsij \n ");
                   9778:       
                   9779:       /*
                   9780:        */
                   9781:       /* goto endfree; */
                   9782:       
                   9783:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9784:       pstamp(ficrest);
                   9785:       
                   9786:       
                   9787:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.220     brouard  9788:                                oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   9789:                                cptcod= 0; /* To be deleted */
                   9790:                                printf("varevsij %d \n",vpopbased);
                   9791:                                fprintf(ficlog, "varevsij %d \n",vpopbased);
                   9792:                                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 */
                   9793:                                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 ");
                   9794:                                if(vpopbased==1)
                   9795:                                        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);
                   9796:                                else
                   9797:                                        fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   9798:                                fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   9799:                                for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   9800:                                fprintf(ficrest,"\n");
                   9801:                                /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   9802:                                epj=vector(1,nlstate+1);
                   9803:                                printf("Computing age specific period (stable) prevalences in each health state \n");
                   9804:                                fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   9805:                                for(age=bage; age <=fage ;age++){
                   9806:                                        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   9807:                                        if (vpopbased==1) {
                   9808:                                                if(mobilav ==0){
                   9809:                                                        for(i=1; i<=nlstate;i++)
                   9810:                                                                prlim[i][i]=probs[(int)age][i][k];
                   9811:                                                }else{ /* mobilav */ 
                   9812:                                                        for(i=1; i<=nlstate;i++)
                   9813:                                                                prlim[i][i]=mobaverage[(int)age][i][k];
                   9814:                                                }
                   9815:                                        }
1.219     brouard  9816:          
1.220     brouard  9817:                                        fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   9818:                                        /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   9819:                                        /* printf(" age %4.0f ",age); */
                   9820:                                        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   9821:                                                for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   9822:                                                        epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   9823:                                                        /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   9824:                                                        /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   9825:                                                }
                   9826:                                                epj[nlstate+1] +=epj[j];
                   9827:                                        }
                   9828:                                        /* printf(" age %4.0f \n",age); */
1.219     brouard  9829:          
1.220     brouard  9830:                                        for(i=1, vepp=0.;i <=nlstate;i++)
                   9831:                                                for(j=1;j <=nlstate;j++)
                   9832:                                                        vepp += vareij[i][j][(int)age];
                   9833:                                        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   9834:                                        for(j=1;j <=nlstate;j++){
                   9835:                                                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   9836:                                        }
                   9837:                                        fprintf(ficrest,"\n");
                   9838:                                }
1.208     brouard  9839:       } /* End vpopbased */
                   9840:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9841:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9842:       free_vector(epj,1,nlstate+1);
                   9843:       printf("done \n");fflush(stdout);
                   9844:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9845:       
1.145     brouard  9846:       /*}*/
1.208     brouard  9847:     } /* End k */
1.126     brouard  9848:     free_vector(weight,1,n);
1.145     brouard  9849:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  9850:     free_imatrix(s,1,maxwav+1,1,n);
                   9851:     free_matrix(anint,1,maxwav,1,n); 
                   9852:     free_matrix(mint,1,maxwav,1,n);
                   9853:     free_ivector(cod,1,n);
                   9854:     free_ivector(tab,1,NCOVMAX);
                   9855:     fclose(ficresstdeij);
                   9856:     fclose(ficrescveij);
                   9857:     fclose(ficresvij);
                   9858:     fclose(ficrest);
1.208     brouard  9859:     printf("done Health expectancies\n");fflush(stdout);
                   9860:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  9861:     fclose(ficpar);
                   9862:   
                   9863:     /*------- Variance of period (stable) prevalence------*/   
                   9864: 
1.201     brouard  9865:     strcpy(fileresvpl,"VPL_");
                   9866:     strcat(fileresvpl,fileresu);
1.126     brouard  9867:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9868:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9869:       exit(0);
                   9870:     }
1.208     brouard  9871:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9872:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  9873: 
1.145     brouard  9874:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9875:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9876:           
                   9877:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9878:        fprintf(ficresvpl,"\n#****** ");
1.218     brouard  9879:                        for(j=1;j<=cptcoveff;j++) 
                   9880:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9881:                        fprintf(ficresvpl,"******\n");
                   9882:       
                   9883:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9884:                        oldm=oldms;savm=savms;
                   9885:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   9886:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  9887:       /*}*/
1.126     brouard  9888:     }
1.218     brouard  9889:                
1.126     brouard  9890:     fclose(ficresvpl);
1.208     brouard  9891:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   9892:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  9893: 
                   9894:     /*---------- End : free ----------------*/
1.219     brouard  9895:     if (mobilav!=0 ||mobilavproj !=0)
                   9896:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
1.218     brouard  9897:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  9898:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9899:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  9900:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  9901:  /* endfree:*/
1.126     brouard  9902:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9903:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9904:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   9905:     free_matrix(covar,0,NCOVMAX,1,n);
                   9906:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  9907:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  9908:     /*free_vector(delti,1,npar);*/
                   9909:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9910:     free_matrix(agev,1,maxwav,1,imx);
                   9911:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   9912: 
1.145     brouard  9913:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  9914:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  9915:     free_ivector(Tvar,1,NCOVMAX);
                   9916:     free_ivector(Tprod,1,NCOVMAX);
                   9917:     free_ivector(Tvaraff,1,NCOVMAX);
1.220     brouard  9918:     free_ivector(invalidvarcomb,1,ncovcombmax);
1.145     brouard  9919:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  9920: 
                   9921:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  9922:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  9923:   fflush(fichtm);
                   9924:   fflush(ficgp);
                   9925:   
                   9926: 
                   9927:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  9928:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   9929:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
1.126     brouard  9930:   }else{
                   9931:     printf("End of Imach\n");
                   9932:     fprintf(ficlog,"End of Imach\n");
                   9933:   }
                   9934:   printf("See log file on %s\n",filelog);
                   9935:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  9936:   /*(void) gettimeofday(&end_time,&tzp);*/
                   9937:   rend_time = time(NULL);  
                   9938:   end_time = *localtime(&rend_time);
                   9939:   /* tml = *localtime(&end_time.tm_sec); */
                   9940:   strcpy(strtend,asctime(&end_time));
1.126     brouard  9941:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   9942:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  9943:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  9944: 
1.157     brouard  9945:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   9946:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   9947:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  9948:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   9949: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   9950:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9951:   fclose(fichtm);
                   9952:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   9953:   fclose(fichtmcov);
                   9954:   fclose(ficgp);
                   9955:   fclose(ficlog);
                   9956:   /*------ End -----------*/
                   9957: 
                   9958: 
                   9959:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  9960: #ifdef WIN32
                   9961:    if (_chdir(pathcd) != 0)
                   9962:           printf("Can't move to directory %s!\n",path);
                   9963:    if(_getcwd(pathcd,MAXLINE) > 0)
                   9964: #else
1.126     brouard  9965:    if(chdir(pathcd) != 0)
1.184     brouard  9966:           printf("Can't move to directory %s!\n", path);
                   9967:    if (getcwd(pathcd, MAXLINE) > 0)
                   9968: #endif 
1.126     brouard  9969:     printf("Current directory %s!\n",pathcd);
                   9970:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   9971:   sprintf(plotcmd,"gnuplot");
1.157     brouard  9972: #ifdef _WIN32
1.126     brouard  9973:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   9974: #endif
                   9975:   if(!stat(plotcmd,&info)){
1.158     brouard  9976:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9977:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  9978:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  9979:     }else
                   9980:       strcpy(pplotcmd,plotcmd);
1.157     brouard  9981: #ifdef __unix
1.126     brouard  9982:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   9983:     if(!stat(plotcmd,&info)){
1.158     brouard  9984:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9985:     }else
                   9986:       strcpy(pplotcmd,plotcmd);
                   9987: #endif
                   9988:   }else
                   9989:     strcpy(pplotcmd,plotcmd);
                   9990:   
                   9991:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  9992:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  9993: 
                   9994:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  9995:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  9996:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  9997:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  9998:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  9999:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  10000:   }
1.158     brouard  10001:   printf(" Successful, please wait...");
1.126     brouard  10002:   while (z[0] != 'q') {
                   10003:     /* chdir(path); */
1.154     brouard  10004:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  10005:     scanf("%s",z);
                   10006: /*     if (z[0] == 'c') system("./imach"); */
                   10007:     if (z[0] == 'e') {
1.158     brouard  10008: #ifdef __APPLE__
1.152     brouard  10009:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  10010: #elif __linux
                   10011:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  10012: #else
1.152     brouard  10013:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  10014: #endif
                   10015:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10016:       system(pplotcmd);
1.126     brouard  10017:     }
                   10018:     else if (z[0] == 'g') system(plotcmd);
                   10019:     else if (z[0] == 'q') exit(0);
                   10020:   }
                   10021:   end:
                   10022:   while (z[0] != 'q') {
1.195     brouard  10023:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  10024:     scanf("%s",z);
                   10025:   }
                   10026: }

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