File:  [Local Repository] / imach / src / imach.c
Revision 1.218: download - view: text, annotated - select for diffs
Fri Feb 12 11:29:23 2016 UTC (8 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: 0.99 Back projections

    1: /* $Id: imach.c,v 1.218 2016/02/12 11:29:23 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.218  2016/02/12 11:29:23  brouard
    5:   Summary: 0.99 Back projections
    6: 
    7:   Revision 1.217  2015/12/23 17:18:31  brouard
    8:   Summary: Experimental backcast
    9: 
   10:   Revision 1.216  2015/12/18 17:32:11  brouard
   11:   Summary: 0.98r4 Warning and status=-2
   12: 
   13:   Version 0.98r4 is now:
   14:    - displaying an error when status is -1, date of interview unknown and date of death known;
   15:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   16:   Older changes concerning s=-2, dating from 2005 have been supersed.
   17: 
   18:   Revision 1.215  2015/12/16 08:52:24  brouard
   19:   Summary: 0.98r4 working
   20: 
   21:   Revision 1.214  2015/12/16 06:57:54  brouard
   22:   Summary: temporary not working
   23: 
   24:   Revision 1.213  2015/12/11 18:22:17  brouard
   25:   Summary: 0.98r4
   26: 
   27:   Revision 1.212  2015/11/21 12:47:24  brouard
   28:   Summary: minor typo
   29: 
   30:   Revision 1.211  2015/11/21 12:41:11  brouard
   31:   Summary: 0.98r3 with some graph of projected cross-sectional
   32: 
   33:   Author: Nicolas Brouard
   34: 
   35:   Revision 1.210  2015/11/18 17:41:20  brouard
   36:   Summary: Start working on projected prevalences
   37: 
   38:   Revision 1.209  2015/11/17 22:12:03  brouard
   39:   Summary: Adding ftolpl parameter
   40:   Author: N Brouard
   41: 
   42:   We had difficulties to get smoothed confidence intervals. It was due
   43:   to the period prevalence which wasn't computed accurately. The inner
   44:   parameter ftolpl is now an outer parameter of the .imach parameter
   45:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   46:   computation are long.
   47: 
   48:   Revision 1.208  2015/11/17 14:31:57  brouard
   49:   Summary: temporary
   50: 
   51:   Revision 1.207  2015/10/27 17:36:57  brouard
   52:   *** empty log message ***
   53: 
   54:   Revision 1.206  2015/10/24 07:14:11  brouard
   55:   *** empty log message ***
   56: 
   57:   Revision 1.205  2015/10/23 15:50:53  brouard
   58:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   59: 
   60:   Revision 1.204  2015/10/01 16:20:26  brouard
   61:   Summary: Some new graphs of contribution to likelihood
   62: 
   63:   Revision 1.203  2015/09/30 17:45:14  brouard
   64:   Summary: looking at better estimation of the hessian
   65: 
   66:   Also a better criteria for convergence to the period prevalence And
   67:   therefore adding the number of years needed to converge. (The
   68:   prevalence in any alive state shold sum to one
   69: 
   70:   Revision 1.202  2015/09/22 19:45:16  brouard
   71:   Summary: Adding some overall graph on contribution to likelihood. Might change
   72: 
   73:   Revision 1.201  2015/09/15 17:34:58  brouard
   74:   Summary: 0.98r0
   75: 
   76:   - Some new graphs like suvival functions
   77:   - Some bugs fixed like model=1+age+V2.
   78: 
   79:   Revision 1.200  2015/09/09 16:53:55  brouard
   80:   Summary: Big bug thanks to Flavia
   81: 
   82:   Even model=1+age+V2. did not work anymore
   83: 
   84:   Revision 1.199  2015/09/07 14:09:23  brouard
   85:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
   86: 
   87:   Revision 1.198  2015/09/03 07:14:39  brouard
   88:   Summary: 0.98q5 Flavia
   89: 
   90:   Revision 1.197  2015/09/01 18:24:39  brouard
   91:   *** empty log message ***
   92: 
   93:   Revision 1.196  2015/08/18 23:17:52  brouard
   94:   Summary: 0.98q5
   95: 
   96:   Revision 1.195  2015/08/18 16:28:39  brouard
   97:   Summary: Adding a hack for testing purpose
   98: 
   99:   After reading the title, ftol and model lines, if the comment line has
  100:   a q, starting with #q, the answer at the end of the run is quit. It
  101:   permits to run test files in batch with ctest. The former workaround was
  102:   $ echo q | imach foo.imach
  103: 
  104:   Revision 1.194  2015/08/18 13:32:00  brouard
  105:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  106: 
  107:   Revision 1.193  2015/08/04 07:17:42  brouard
  108:   Summary: 0.98q4
  109: 
  110:   Revision 1.192  2015/07/16 16:49:02  brouard
  111:   Summary: Fixing some outputs
  112: 
  113:   Revision 1.191  2015/07/14 10:00:33  brouard
  114:   Summary: Some fixes
  115: 
  116:   Revision 1.190  2015/05/05 08:51:13  brouard
  117:   Summary: Adding digits in output parameters (7 digits instead of 6)
  118: 
  119:   Fix 1+age+.
  120: 
  121:   Revision 1.189  2015/04/30 14:45:16  brouard
  122:   Summary: 0.98q2
  123: 
  124:   Revision 1.188  2015/04/30 08:27:53  brouard
  125:   *** empty log message ***
  126: 
  127:   Revision 1.187  2015/04/29 09:11:15  brouard
  128:   *** empty log message ***
  129: 
  130:   Revision 1.186  2015/04/23 12:01:52  brouard
  131:   Summary: V1*age is working now, version 0.98q1
  132: 
  133:   Some codes had been disabled in order to simplify and Vn*age was
  134:   working in the optimization phase, ie, giving correct MLE parameters,
  135:   but, as usual, outputs were not correct and program core dumped.
  136: 
  137:   Revision 1.185  2015/03/11 13:26:42  brouard
  138:   Summary: Inclusion of compile and links command line for Intel Compiler
  139: 
  140:   Revision 1.184  2015/03/11 11:52:39  brouard
  141:   Summary: Back from Windows 8. Intel Compiler
  142: 
  143:   Revision 1.183  2015/03/10 20:34:32  brouard
  144:   Summary: 0.98q0, trying with directest, mnbrak fixed
  145: 
  146:   We use directest instead of original Powell test; probably no
  147:   incidence on the results, but better justifications;
  148:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  149:   wrong results.
  150: 
  151:   Revision 1.182  2015/02/12 08:19:57  brouard
  152:   Summary: Trying to keep directest which seems simpler and more general
  153:   Author: Nicolas Brouard
  154: 
  155:   Revision 1.181  2015/02/11 23:22:24  brouard
  156:   Summary: Comments on Powell added
  157: 
  158:   Author:
  159: 
  160:   Revision 1.180  2015/02/11 17:33:45  brouard
  161:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  162: 
  163:   Revision 1.179  2015/01/04 09:57:06  brouard
  164:   Summary: back to OS/X
  165: 
  166:   Revision 1.178  2015/01/04 09:35:48  brouard
  167:   *** empty log message ***
  168: 
  169:   Revision 1.177  2015/01/03 18:40:56  brouard
  170:   Summary: Still testing ilc32 on OSX
  171: 
  172:   Revision 1.176  2015/01/03 16:45:04  brouard
  173:   *** empty log message ***
  174: 
  175:   Revision 1.175  2015/01/03 16:33:42  brouard
  176:   *** empty log message ***
  177: 
  178:   Revision 1.174  2015/01/03 16:15:49  brouard
  179:   Summary: Still in cross-compilation
  180: 
  181:   Revision 1.173  2015/01/03 12:06:26  brouard
  182:   Summary: trying to detect cross-compilation
  183: 
  184:   Revision 1.172  2014/12/27 12:07:47  brouard
  185:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  186: 
  187:   Revision 1.171  2014/12/23 13:26:59  brouard
  188:   Summary: Back from Visual C
  189: 
  190:   Still problem with utsname.h on Windows
  191: 
  192:   Revision 1.170  2014/12/23 11:17:12  brouard
  193:   Summary: Cleaning some \%% back to %%
  194: 
  195:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  196: 
  197:   Revision 1.169  2014/12/22 23:08:31  brouard
  198:   Summary: 0.98p
  199: 
  200:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  201: 
  202:   Revision 1.168  2014/12/22 15:17:42  brouard
  203:   Summary: update
  204: 
  205:   Revision 1.167  2014/12/22 13:50:56  brouard
  206:   Summary: Testing uname and compiler version and if compiled 32 or 64
  207: 
  208:   Testing on Linux 64
  209: 
  210:   Revision 1.166  2014/12/22 11:40:47  brouard
  211:   *** empty log message ***
  212: 
  213:   Revision 1.165  2014/12/16 11:20:36  brouard
  214:   Summary: After compiling on Visual C
  215: 
  216:   * imach.c (Module): Merging 1.61 to 1.162
  217: 
  218:   Revision 1.164  2014/12/16 10:52:11  brouard
  219:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  220: 
  221:   * imach.c (Module): Merging 1.61 to 1.162
  222: 
  223:   Revision 1.163  2014/12/16 10:30:11  brouard
  224:   * imach.c (Module): Merging 1.61 to 1.162
  225: 
  226:   Revision 1.162  2014/09/25 11:43:39  brouard
  227:   Summary: temporary backup 0.99!
  228: 
  229:   Revision 1.1  2014/09/16 11:06:58  brouard
  230:   Summary: With some code (wrong) for nlopt
  231: 
  232:   Author:
  233: 
  234:   Revision 1.161  2014/09/15 20:41:41  brouard
  235:   Summary: Problem with macro SQR on Intel compiler
  236: 
  237:   Revision 1.160  2014/09/02 09:24:05  brouard
  238:   *** empty log message ***
  239: 
  240:   Revision 1.159  2014/09/01 10:34:10  brouard
  241:   Summary: WIN32
  242:   Author: Brouard
  243: 
  244:   Revision 1.158  2014/08/27 17:11:51  brouard
  245:   *** empty log message ***
  246: 
  247:   Revision 1.157  2014/08/27 16:26:55  brouard
  248:   Summary: Preparing windows Visual studio version
  249:   Author: Brouard
  250: 
  251:   In order to compile on Visual studio, time.h is now correct and time_t
  252:   and tm struct should be used. difftime should be used but sometimes I
  253:   just make the differences in raw time format (time(&now).
  254:   Trying to suppress #ifdef LINUX
  255:   Add xdg-open for __linux in order to open default browser.
  256: 
  257:   Revision 1.156  2014/08/25 20:10:10  brouard
  258:   *** empty log message ***
  259: 
  260:   Revision 1.155  2014/08/25 18:32:34  brouard
  261:   Summary: New compile, minor changes
  262:   Author: Brouard
  263: 
  264:   Revision 1.154  2014/06/20 17:32:08  brouard
  265:   Summary: Outputs now all graphs of convergence to period prevalence
  266: 
  267:   Revision 1.153  2014/06/20 16:45:46  brouard
  268:   Summary: If 3 live state, convergence to period prevalence on same graph
  269:   Author: Brouard
  270: 
  271:   Revision 1.152  2014/06/18 17:54:09  brouard
  272:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  273: 
  274:   Revision 1.151  2014/06/18 16:43:30  brouard
  275:   *** empty log message ***
  276: 
  277:   Revision 1.150  2014/06/18 16:42:35  brouard
  278:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  279:   Author: brouard
  280: 
  281:   Revision 1.149  2014/06/18 15:51:14  brouard
  282:   Summary: Some fixes in parameter files errors
  283:   Author: Nicolas Brouard
  284: 
  285:   Revision 1.148  2014/06/17 17:38:48  brouard
  286:   Summary: Nothing new
  287:   Author: Brouard
  288: 
  289:   Just a new packaging for OS/X version 0.98nS
  290: 
  291:   Revision 1.147  2014/06/16 10:33:11  brouard
  292:   *** empty log message ***
  293: 
  294:   Revision 1.146  2014/06/16 10:20:28  brouard
  295:   Summary: Merge
  296:   Author: Brouard
  297: 
  298:   Merge, before building revised version.
  299: 
  300:   Revision 1.145  2014/06/10 21:23:15  brouard
  301:   Summary: Debugging with valgrind
  302:   Author: Nicolas Brouard
  303: 
  304:   Lot of changes in order to output the results with some covariates
  305:   After the Edimburgh REVES conference 2014, it seems mandatory to
  306:   improve the code.
  307:   No more memory valgrind error but a lot has to be done in order to
  308:   continue the work of splitting the code into subroutines.
  309:   Also, decodemodel has been improved. Tricode is still not
  310:   optimal. nbcode should be improved. Documentation has been added in
  311:   the source code.
  312: 
  313:   Revision 1.143  2014/01/26 09:45:38  brouard
  314:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  315: 
  316:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  317:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  318: 
  319:   Revision 1.142  2014/01/26 03:57:36  brouard
  320:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  321: 
  322:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  323: 
  324:   Revision 1.141  2014/01/26 02:42:01  brouard
  325:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  326: 
  327:   Revision 1.140  2011/09/02 10:37:54  brouard
  328:   Summary: times.h is ok with mingw32 now.
  329: 
  330:   Revision 1.139  2010/06/14 07:50:17  brouard
  331:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  332:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  333: 
  334:   Revision 1.138  2010/04/30 18:19:40  brouard
  335:   *** empty log message ***
  336: 
  337:   Revision 1.137  2010/04/29 18:11:38  brouard
  338:   (Module): Checking covariates for more complex models
  339:   than V1+V2. A lot of change to be done. Unstable.
  340: 
  341:   Revision 1.136  2010/04/26 20:30:53  brouard
  342:   (Module): merging some libgsl code. Fixing computation
  343:   of likelione (using inter/intrapolation if mle = 0) in order to
  344:   get same likelihood as if mle=1.
  345:   Some cleaning of code and comments added.
  346: 
  347:   Revision 1.135  2009/10/29 15:33:14  brouard
  348:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  349: 
  350:   Revision 1.134  2009/10/29 13:18:53  brouard
  351:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  352: 
  353:   Revision 1.133  2009/07/06 10:21:25  brouard
  354:   just nforces
  355: 
  356:   Revision 1.132  2009/07/06 08:22:05  brouard
  357:   Many tings
  358: 
  359:   Revision 1.131  2009/06/20 16:22:47  brouard
  360:   Some dimensions resccaled
  361: 
  362:   Revision 1.130  2009/05/26 06:44:34  brouard
  363:   (Module): Max Covariate is now set to 20 instead of 8. A
  364:   lot of cleaning with variables initialized to 0. Trying to make
  365:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  366: 
  367:   Revision 1.129  2007/08/31 13:49:27  lievre
  368:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  369: 
  370:   Revision 1.128  2006/06/30 13:02:05  brouard
  371:   (Module): Clarifications on computing e.j
  372: 
  373:   Revision 1.127  2006/04/28 18:11:50  brouard
  374:   (Module): Yes the sum of survivors was wrong since
  375:   imach-114 because nhstepm was no more computed in the age
  376:   loop. Now we define nhstepma in the age loop.
  377:   (Module): In order to speed up (in case of numerous covariates) we
  378:   compute health expectancies (without variances) in a first step
  379:   and then all the health expectancies with variances or standard
  380:   deviation (needs data from the Hessian matrices) which slows the
  381:   computation.
  382:   In the future we should be able to stop the program is only health
  383:   expectancies and graph are needed without standard deviations.
  384: 
  385:   Revision 1.126  2006/04/28 17:23:28  brouard
  386:   (Module): Yes the sum of survivors was wrong since
  387:   imach-114 because nhstepm was no more computed in the age
  388:   loop. Now we define nhstepma in the age loop.
  389:   Version 0.98h
  390: 
  391:   Revision 1.125  2006/04/04 15:20:31  lievre
  392:   Errors in calculation of health expectancies. Age was not initialized.
  393:   Forecasting file added.
  394: 
  395:   Revision 1.124  2006/03/22 17:13:53  lievre
  396:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  397:   The log-likelihood is printed in the log file
  398: 
  399:   Revision 1.123  2006/03/20 10:52:43  brouard
  400:   * imach.c (Module): <title> changed, corresponds to .htm file
  401:   name. <head> headers where missing.
  402: 
  403:   * imach.c (Module): Weights can have a decimal point as for
  404:   English (a comma might work with a correct LC_NUMERIC environment,
  405:   otherwise the weight is truncated).
  406:   Modification of warning when the covariates values are not 0 or
  407:   1.
  408:   Version 0.98g
  409: 
  410:   Revision 1.122  2006/03/20 09:45:41  brouard
  411:   (Module): Weights can have a decimal point as for
  412:   English (a comma might work with a correct LC_NUMERIC environment,
  413:   otherwise the weight is truncated).
  414:   Modification of warning when the covariates values are not 0 or
  415:   1.
  416:   Version 0.98g
  417: 
  418:   Revision 1.121  2006/03/16 17:45:01  lievre
  419:   * imach.c (Module): Comments concerning covariates added
  420: 
  421:   * imach.c (Module): refinements in the computation of lli if
  422:   status=-2 in order to have more reliable computation if stepm is
  423:   not 1 month. Version 0.98f
  424: 
  425:   Revision 1.120  2006/03/16 15:10:38  lievre
  426:   (Module): refinements in the computation of lli if
  427:   status=-2 in order to have more reliable computation if stepm is
  428:   not 1 month. Version 0.98f
  429: 
  430:   Revision 1.119  2006/03/15 17:42:26  brouard
  431:   (Module): Bug if status = -2, the loglikelihood was
  432:   computed as likelihood omitting the logarithm. Version O.98e
  433: 
  434:   Revision 1.118  2006/03/14 18:20:07  brouard
  435:   (Module): varevsij Comments added explaining the second
  436:   table of variances if popbased=1 .
  437:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  438:   (Module): Function pstamp added
  439:   (Module): Version 0.98d
  440: 
  441:   Revision 1.117  2006/03/14 17:16:22  brouard
  442:   (Module): varevsij Comments added explaining the second
  443:   table of variances if popbased=1 .
  444:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  445:   (Module): Function pstamp added
  446:   (Module): Version 0.98d
  447: 
  448:   Revision 1.116  2006/03/06 10:29:27  brouard
  449:   (Module): Variance-covariance wrong links and
  450:   varian-covariance of ej. is needed (Saito).
  451: 
  452:   Revision 1.115  2006/02/27 12:17:45  brouard
  453:   (Module): One freematrix added in mlikeli! 0.98c
  454: 
  455:   Revision 1.114  2006/02/26 12:57:58  brouard
  456:   (Module): Some improvements in processing parameter
  457:   filename with strsep.
  458: 
  459:   Revision 1.113  2006/02/24 14:20:24  brouard
  460:   (Module): Memory leaks checks with valgrind and:
  461:   datafile was not closed, some imatrix were not freed and on matrix
  462:   allocation too.
  463: 
  464:   Revision 1.112  2006/01/30 09:55:26  brouard
  465:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  466: 
  467:   Revision 1.111  2006/01/25 20:38:18  brouard
  468:   (Module): Lots of cleaning and bugs added (Gompertz)
  469:   (Module): Comments can be added in data file. Missing date values
  470:   can be a simple dot '.'.
  471: 
  472:   Revision 1.110  2006/01/25 00:51:50  brouard
  473:   (Module): Lots of cleaning and bugs added (Gompertz)
  474: 
  475:   Revision 1.109  2006/01/24 19:37:15  brouard
  476:   (Module): Comments (lines starting with a #) are allowed in data.
  477: 
  478:   Revision 1.108  2006/01/19 18:05:42  lievre
  479:   Gnuplot problem appeared...
  480:   To be fixed
  481: 
  482:   Revision 1.107  2006/01/19 16:20:37  brouard
  483:   Test existence of gnuplot in imach path
  484: 
  485:   Revision 1.106  2006/01/19 13:24:36  brouard
  486:   Some cleaning and links added in html output
  487: 
  488:   Revision 1.105  2006/01/05 20:23:19  lievre
  489:   *** empty log message ***
  490: 
  491:   Revision 1.104  2005/09/30 16:11:43  lievre
  492:   (Module): sump fixed, loop imx fixed, and simplifications.
  493:   (Module): If the status is missing at the last wave but we know
  494:   that the person is alive, then we can code his/her status as -2
  495:   (instead of missing=-1 in earlier versions) and his/her
  496:   contributions to the likelihood is 1 - Prob of dying from last
  497:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  498:   the healthy state at last known wave). Version is 0.98
  499: 
  500:   Revision 1.103  2005/09/30 15:54:49  lievre
  501:   (Module): sump fixed, loop imx fixed, and simplifications.
  502: 
  503:   Revision 1.102  2004/09/15 17:31:30  brouard
  504:   Add the possibility to read data file including tab characters.
  505: 
  506:   Revision 1.101  2004/09/15 10:38:38  brouard
  507:   Fix on curr_time
  508: 
  509:   Revision 1.100  2004/07/12 18:29:06  brouard
  510:   Add version for Mac OS X. Just define UNIX in Makefile
  511: 
  512:   Revision 1.99  2004/06/05 08:57:40  brouard
  513:   *** empty log message ***
  514: 
  515:   Revision 1.98  2004/05/16 15:05:56  brouard
  516:   New version 0.97 . First attempt to estimate force of mortality
  517:   directly from the data i.e. without the need of knowing the health
  518:   state at each age, but using a Gompertz model: log u =a + b*age .
  519:   This is the basic analysis of mortality and should be done before any
  520:   other analysis, in order to test if the mortality estimated from the
  521:   cross-longitudinal survey is different from the mortality estimated
  522:   from other sources like vital statistic data.
  523: 
  524:   The same imach parameter file can be used but the option for mle should be -3.
  525: 
  526:   Agnès, who wrote this part of the code, tried to keep most of the
  527:   former routines in order to include the new code within the former code.
  528: 
  529:   The output is very simple: only an estimate of the intercept and of
  530:   the slope with 95% confident intervals.
  531: 
  532:   Current limitations:
  533:   A) Even if you enter covariates, i.e. with the
  534:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  535:   B) There is no computation of Life Expectancy nor Life Table.
  536: 
  537:   Revision 1.97  2004/02/20 13:25:42  lievre
  538:   Version 0.96d. Population forecasting command line is (temporarily)
  539:   suppressed.
  540: 
  541:   Revision 1.96  2003/07/15 15:38:55  brouard
  542:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  543:   rewritten within the same printf. Workaround: many printfs.
  544: 
  545:   Revision 1.95  2003/07/08 07:54:34  brouard
  546:   * imach.c (Repository):
  547:   (Repository): Using imachwizard code to output a more meaningful covariance
  548:   matrix (cov(a12,c31) instead of numbers.
  549: 
  550:   Revision 1.94  2003/06/27 13:00:02  brouard
  551:   Just cleaning
  552: 
  553:   Revision 1.93  2003/06/25 16:33:55  brouard
  554:   (Module): On windows (cygwin) function asctime_r doesn't
  555:   exist so I changed back to asctime which exists.
  556:   (Module): Version 0.96b
  557: 
  558:   Revision 1.92  2003/06/25 16:30:45  brouard
  559:   (Module): On windows (cygwin) function asctime_r doesn't
  560:   exist so I changed back to asctime which exists.
  561: 
  562:   Revision 1.91  2003/06/25 15:30:29  brouard
  563:   * imach.c (Repository): Duplicated warning errors corrected.
  564:   (Repository): Elapsed time after each iteration is now output. It
  565:   helps to forecast when convergence will be reached. Elapsed time
  566:   is stamped in powell.  We created a new html file for the graphs
  567:   concerning matrix of covariance. It has extension -cov.htm.
  568: 
  569:   Revision 1.90  2003/06/24 12:34:15  brouard
  570:   (Module): Some bugs corrected for windows. Also, when
  571:   mle=-1 a template is output in file "or"mypar.txt with the design
  572:   of the covariance matrix to be input.
  573: 
  574:   Revision 1.89  2003/06/24 12:30:52  brouard
  575:   (Module): Some bugs corrected for windows. Also, when
  576:   mle=-1 a template is output in file "or"mypar.txt with the design
  577:   of the covariance matrix to be input.
  578: 
  579:   Revision 1.88  2003/06/23 17:54:56  brouard
  580:   * 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.
  581: 
  582:   Revision 1.87  2003/06/18 12:26:01  brouard
  583:   Version 0.96
  584: 
  585:   Revision 1.86  2003/06/17 20:04:08  brouard
  586:   (Module): Change position of html and gnuplot routines and added
  587:   routine fileappend.
  588: 
  589:   Revision 1.85  2003/06/17 13:12:43  brouard
  590:   * imach.c (Repository): Check when date of death was earlier that
  591:   current date of interview. It may happen when the death was just
  592:   prior to the death. In this case, dh was negative and likelihood
  593:   was wrong (infinity). We still send an "Error" but patch by
  594:   assuming that the date of death was just one stepm after the
  595:   interview.
  596:   (Repository): Because some people have very long ID (first column)
  597:   we changed int to long in num[] and we added a new lvector for
  598:   memory allocation. But we also truncated to 8 characters (left
  599:   truncation)
  600:   (Repository): No more line truncation errors.
  601: 
  602:   Revision 1.84  2003/06/13 21:44:43  brouard
  603:   * imach.c (Repository): Replace "freqsummary" at a correct
  604:   place. It differs from routine "prevalence" which may be called
  605:   many times. Probs is memory consuming and must be used with
  606:   parcimony.
  607:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  608: 
  609:   Revision 1.83  2003/06/10 13:39:11  lievre
  610:   *** empty log message ***
  611: 
  612:   Revision 1.82  2003/06/05 15:57:20  brouard
  613:   Add log in  imach.c and  fullversion number is now printed.
  614: 
  615: */
  616: /*
  617:    Interpolated Markov Chain
  618: 
  619:   Short summary of the programme:
  620:   
  621:   This program computes Healthy Life Expectancies from
  622:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  623:   first survey ("cross") where individuals from different ages are
  624:   interviewed on their health status or degree of disability (in the
  625:   case of a health survey which is our main interest) -2- at least a
  626:   second wave of interviews ("longitudinal") which measure each change
  627:   (if any) in individual health status.  Health expectancies are
  628:   computed from the time spent in each health state according to a
  629:   model. More health states you consider, more time is necessary to reach the
  630:   Maximum Likelihood of the parameters involved in the model.  The
  631:   simplest model is the multinomial logistic model where pij is the
  632:   probability to be observed in state j at the second wave
  633:   conditional to be observed in state i at the first wave. Therefore
  634:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  635:   'age' is age and 'sex' is a covariate. If you want to have a more
  636:   complex model than "constant and age", you should modify the program
  637:   where the markup *Covariates have to be included here again* invites
  638:   you to do it.  More covariates you add, slower the
  639:   convergence.
  640: 
  641:   The advantage of this computer programme, compared to a simple
  642:   multinomial logistic model, is clear when the delay between waves is not
  643:   identical for each individual. Also, if a individual missed an
  644:   intermediate interview, the information is lost, but taken into
  645:   account using an interpolation or extrapolation.  
  646: 
  647:   hPijx is the probability to be observed in state i at age x+h
  648:   conditional to the observed state i at age x. The delay 'h' can be
  649:   split into an exact number (nh*stepm) of unobserved intermediate
  650:   states. This elementary transition (by month, quarter,
  651:   semester or year) is modelled as a multinomial logistic.  The hPx
  652:   matrix is simply the matrix product of nh*stepm elementary matrices
  653:   and the contribution of each individual to the likelihood is simply
  654:   hPijx.
  655: 
  656:   Also this programme outputs the covariance matrix of the parameters but also
  657:   of the life expectancies. It also computes the period (stable) prevalence.
  658: 
  659: Back prevalence and projections:
  660:  - 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)
  661:     Computes the back prevalence limit  for any combination	of covariate values k
  662:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
  663:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  664:  - hBijx Back Probability to be in state i at age x-h being in j at x
  665:    Computes for any combination of covariates k and any age between bage and fage 
  666:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  667:  			oldm=oldms;savm=savms;
  668: 	 - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  669:      Computes the transition matrix starting at age 'age' over
  670:      'nhstepm*hstepm*stepm' months (i.e. until
  671:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  672:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
  673:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
  674: 									 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
  675: 
  676:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  677:            Institut national d'études démographiques, Paris.
  678:   This software have been partly granted by Euro-REVES, a concerted action
  679:   from the European Union.
  680:   It is copyrighted identically to a GNU software product, ie programme and
  681:   software can be distributed freely for non commercial use. Latest version
  682:   can be accessed at http://euroreves.ined.fr/imach .
  683: 
  684:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  685:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  686:   
  687:   **********************************************************************/
  688: /*
  689:   main
  690:   read parameterfile
  691:   read datafile
  692:   concatwav
  693:   freqsummary
  694:   if (mle >= 1)
  695:     mlikeli
  696:   print results files
  697:   if mle==1 
  698:      computes hessian
  699:   read end of parameter file: agemin, agemax, bage, fage, estepm
  700:       begin-prev-date,...
  701:   open gnuplot file
  702:   open html file
  703:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  704:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  705:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  706:     freexexit2 possible for memory heap.
  707: 
  708:   h Pij x                         | pij_nom  ficrestpij
  709:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  710:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  711:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  712: 
  713:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  714:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  715:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  716:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  717:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  718: 
  719:   forecasting if prevfcast==1 prevforecast call prevalence()
  720:   health expectancies
  721:   Variance-covariance of DFLE
  722:   prevalence()
  723:    movingaverage()
  724:   varevsij() 
  725:   if popbased==1 varevsij(,popbased)
  726:   total life expectancies
  727:   Variance of period (stable) prevalence
  728:  end
  729: */
  730: 
  731: /* #define DEBUG */
  732: /* #define DEBUGBRENT */
  733: /* #define DEBUGLINMIN */
  734: /* #define DEBUGHESS */
  735: #define DEBUGHESSIJ
  736: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
  737: #define POWELL /* Instead of NLOPT */
  738: #define POWELLF1F3 /* Skip test */
  739: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  740: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  741: 
  742: #include <math.h>
  743: #include <stdio.h>
  744: #include <stdlib.h>
  745: #include <string.h>
  746: 
  747: #ifdef _WIN32
  748: #include <io.h>
  749: #include <windows.h>
  750: #include <tchar.h>
  751: #else
  752: #include <unistd.h>
  753: #endif
  754: 
  755: #include <limits.h>
  756: #include <sys/types.h>
  757: 
  758: #if defined(__GNUC__)
  759: #include <sys/utsname.h> /* Doesn't work on Windows */
  760: #endif
  761: 
  762: #include <sys/stat.h>
  763: #include <errno.h>
  764: /* extern int errno; */
  765: 
  766: /* #ifdef LINUX */
  767: /* #include <time.h> */
  768: /* #include "timeval.h" */
  769: /* #else */
  770: /* #include <sys/time.h> */
  771: /* #endif */
  772: 
  773: #include <time.h>
  774: 
  775: #ifdef GSL
  776: #include <gsl/gsl_errno.h>
  777: #include <gsl/gsl_multimin.h>
  778: #endif
  779: 
  780: 
  781: #ifdef NLOPT
  782: #include <nlopt.h>
  783: typedef struct {
  784:   double (* function)(double [] );
  785: } myfunc_data ;
  786: #endif
  787: 
  788: /* #include <libintl.h> */
  789: /* #define _(String) gettext (String) */
  790: 
  791: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  792: 
  793: #define GNUPLOTPROGRAM "gnuplot"
  794: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  795: #define FILENAMELENGTH 132
  796: 
  797: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  798: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  799: 
  800: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  801: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  802: 
  803: #define NINTERVMAX 8
  804: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  805: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  806: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  807: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  808: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  809: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  810: #define MAXN 20000
  811: #define YEARM 12. /**< Number of months per year */
  812: /* #define AGESUP 130 */
  813: #define AGESUP 150
  814: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  815: #define AGEBASE 40
  816: #define AGEOVERFLOW 1.e20
  817: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  818: #ifdef _WIN32
  819: #define DIRSEPARATOR '\\'
  820: #define CHARSEPARATOR "\\"
  821: #define ODIRSEPARATOR '/'
  822: #else
  823: #define DIRSEPARATOR '/'
  824: #define CHARSEPARATOR "/"
  825: #define ODIRSEPARATOR '\\'
  826: #endif
  827: 
  828: /* $Id: imach.c,v 1.218 2016/02/12 11:29:23 brouard Exp $ */
  829: /* $State: Exp $ */
  830: #include "version.h"
  831: char version[]=__IMACH_VERSION__;
  832: 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";
  833: char fullversion[]="$Revision: 1.218 $ $Date: 2016/02/12 11:29:23 $"; 
  834: char strstart[80];
  835: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  836: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  837: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  838: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  839: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  840: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  841: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  842: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  843: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  844: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  845: int cptcov=0; /* Working variable */
  846: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  847: int npar=NPARMAX;
  848: int nlstate=2; /* Number of live states */
  849: int ndeath=1; /* Number of dead states */
  850: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  851: int popbased=0;
  852: 
  853: int *wav; /* Number of waves for this individuual 0 is possible */
  854: int maxwav=0; /* Maxim number of waves */
  855: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  856: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  857: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  858: 		   to the likelihood and the sum of weights (done by funcone)*/
  859: int mle=1, weightopt=0;
  860: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  861: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  862: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  863: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  864: int countcallfunc=0;  /* Count the number of calls to func */
  865: double jmean=1; /* Mean space between 2 waves */
  866: double **matprod2(); /* test */
  867: double **oldm, **newm, **savm; /* Working pointers to matrices */
  868: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  869: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  870: 
  871: /*FILE *fic ; */ /* Used in readdata only */
  872: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  873: FILE *ficlog, *ficrespow;
  874: int globpr=0; /* Global variable for printing or not */
  875: double fretone; /* Only one call to likelihood */
  876: long ipmx=0; /* Number of contributions */
  877: double sw; /* Sum of weights */
  878: char filerespow[FILENAMELENGTH];
  879: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  880: FILE *ficresilk;
  881: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  882: FILE *ficresprobmorprev;
  883: FILE *fichtm, *fichtmcov; /* Html File */
  884: FILE *ficreseij;
  885: char filerese[FILENAMELENGTH];
  886: FILE *ficresstdeij;
  887: char fileresstde[FILENAMELENGTH];
  888: FILE *ficrescveij;
  889: char filerescve[FILENAMELENGTH];
  890: FILE  *ficresvij;
  891: char fileresv[FILENAMELENGTH];
  892: FILE  *ficresvpl;
  893: char fileresvpl[FILENAMELENGTH];
  894: char title[MAXLINE];
  895: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
  896: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  897: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  898: char command[FILENAMELENGTH];
  899: int  outcmd=0;
  900: 
  901: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  902: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  903: char filelog[FILENAMELENGTH]; /* Log file */
  904: char filerest[FILENAMELENGTH];
  905: char fileregp[FILENAMELENGTH];
  906: char popfile[FILENAMELENGTH];
  907: 
  908: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  909: 
  910: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  911: /* struct timezone tzp; */
  912: /* extern int gettimeofday(); */
  913: struct tm tml, *gmtime(), *localtime();
  914: 
  915: extern time_t time();
  916: 
  917: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  918: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  919: struct tm tm;
  920: 
  921: char strcurr[80], strfor[80];
  922: 
  923: char *endptr;
  924: long lval;
  925: double dval;
  926: 
  927: #define NR_END 1
  928: #define FREE_ARG char*
  929: #define FTOL 1.0e-10
  930: 
  931: #define NRANSI 
  932: #define ITMAX 200 
  933: 
  934: #define TOL 2.0e-4 
  935: 
  936: #define CGOLD 0.3819660 
  937: #define ZEPS 1.0e-10 
  938: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  939: 
  940: #define GOLD 1.618034 
  941: #define GLIMIT 100.0 
  942: #define TINY 1.0e-20 
  943: 
  944: static double maxarg1,maxarg2;
  945: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  946: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  947:   
  948: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  949: #define rint(a) floor(a+0.5)
  950: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  951: #define mytinydouble 1.0e-16
  952: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  953: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  954: /* static double dsqrarg; */
  955: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  956: static double sqrarg;
  957: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  958: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  959: int agegomp= AGEGOMP;
  960: 
  961: int imx; 
  962: int stepm=1;
  963: /* Stepm, step in month: minimum step interpolation*/
  964: 
  965: int estepm;
  966: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  967: 
  968: int m,nb;
  969: long *num;
  970: int firstpass=0, lastpass=4,*cod, *cens;
  971: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  972: 		   covariate for which somebody answered excluding 
  973: 		   undefined. Usually 2: 0 and 1. */
  974: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  975: 			     covariate for which somebody answered including 
  976: 			     undefined. Usually 3: -1, 0 and 1. */
  977: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  978: double **pmmij, ***probs; /* Global pointer */
  979: double ***mobaverage; /* New global variable */
  980: double *ageexmed,*agecens;
  981: double dateintmean=0;
  982: 
  983: double *weight;
  984: int **s; /* Status */
  985: double *agedc;
  986: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  987: 		  * covar=matrix(0,NCOVMAX,1,n); 
  988: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  989: double  idx; 
  990: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  991: int *Tage;
  992: int *Ndum; /** Freq of modality (tricode */
  993: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
  994: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  995: double *lsurv, *lpop, *tpop;
  996: 
  997: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  998: double ftolhess; /**< Tolerance for computing hessian */
  999: 
 1000: /**************** split *************************/
 1001: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1002: {
 1003:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1004:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1005:   */ 
 1006:   char	*ss;				/* pointer */
 1007:   int	l1=0, l2=0;				/* length counters */
 1008: 
 1009:   l1 = strlen(path );			/* length of path */
 1010:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1011:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1012:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1013:     strcpy( name, path );		/* we got the fullname name because no directory */
 1014:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1015:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1016:     /* get current working directory */
 1017:     /*    extern  char* getcwd ( char *buf , int len);*/
 1018: #ifdef WIN32
 1019:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1020: #else
 1021: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1022: #endif
 1023:       return( GLOCK_ERROR_GETCWD );
 1024:     }
 1025:     /* got dirc from getcwd*/
 1026:     printf(" DIRC = %s \n",dirc);
 1027:   } else {				/* strip directory from path */
 1028:     ss++;				/* after this, the filename */
 1029:     l2 = strlen( ss );			/* length of filename */
 1030:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1031:     strcpy( name, ss );		/* save file name */
 1032:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1033:     dirc[l1-l2] = '\0';			/* add zero */
 1034:     printf(" DIRC2 = %s \n",dirc);
 1035:   }
 1036:   /* We add a separator at the end of dirc if not exists */
 1037:   l1 = strlen( dirc );			/* length of directory */
 1038:   if( dirc[l1-1] != DIRSEPARATOR ){
 1039:     dirc[l1] =  DIRSEPARATOR;
 1040:     dirc[l1+1] = 0; 
 1041:     printf(" DIRC3 = %s \n",dirc);
 1042:   }
 1043:   ss = strrchr( name, '.' );		/* find last / */
 1044:   if (ss >0){
 1045:     ss++;
 1046:     strcpy(ext,ss);			/* save extension */
 1047:     l1= strlen( name);
 1048:     l2= strlen(ss)+1;
 1049:     strncpy( finame, name, l1-l2);
 1050:     finame[l1-l2]= 0;
 1051:   }
 1052: 
 1053:   return( 0 );				/* we're done */
 1054: }
 1055: 
 1056: 
 1057: /******************************************/
 1058: 
 1059: void replace_back_to_slash(char *s, char*t)
 1060: {
 1061:   int i;
 1062:   int lg=0;
 1063:   i=0;
 1064:   lg=strlen(t);
 1065:   for(i=0; i<= lg; i++) {
 1066:     (s[i] = t[i]);
 1067:     if (t[i]== '\\') s[i]='/';
 1068:   }
 1069: }
 1070: 
 1071: char *trimbb(char *out, char *in)
 1072: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1073:   char *s;
 1074:   s=out;
 1075:   while (*in != '\0'){
 1076:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1077:       in++;
 1078:     }
 1079:     *out++ = *in++;
 1080:   }
 1081:   *out='\0';
 1082:   return s;
 1083: }
 1084: 
 1085: /* char *substrchaine(char *out, char *in, char *chain) */
 1086: /* { */
 1087: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1088: /*   char *s, *t; */
 1089: /*   t=in;s=out; */
 1090: /*   while ((*in != *chain) && (*in != '\0')){ */
 1091: /*     *out++ = *in++; */
 1092: /*   } */
 1093: 
 1094: /*   /\* *in matches *chain *\/ */
 1095: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1096: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1097: /*   } */
 1098: /*   in--; chain--; */
 1099: /*   while ( (*in != '\0')){ */
 1100: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1101: /*     *out++ = *in++; */
 1102: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1103: /*   } */
 1104: /*   *out='\0'; */
 1105: /*   out=s; */
 1106: /*   return out; */
 1107: /* } */
 1108: char *substrchaine(char *out, char *in, char *chain)
 1109: {
 1110:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1111:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1112: 
 1113:   char *strloc;
 1114: 
 1115:   strcpy (out, in); 
 1116:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1117:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1118:   if(strloc != NULL){ 
 1119:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1120:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1121:     /* strcpy (strloc, strloc +strlen(chain));*/
 1122:   }
 1123:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1124:   return out;
 1125: }
 1126: 
 1127: 
 1128: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1129: {
 1130:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1131:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1132:      gives blocc="abcdef" and alocc="ghi2j".
 1133:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1134:   */
 1135:   char *s, *t;
 1136:   t=in;s=in;
 1137:   while ((*in != occ) && (*in != '\0')){
 1138:     *alocc++ = *in++;
 1139:   }
 1140:   if( *in == occ){
 1141:     *(alocc)='\0';
 1142:     s=++in;
 1143:   }
 1144:  
 1145:   if (s == t) {/* occ not found */
 1146:     *(alocc-(in-s))='\0';
 1147:     in=s;
 1148:   }
 1149:   while ( *in != '\0'){
 1150:     *blocc++ = *in++;
 1151:   }
 1152: 
 1153:   *blocc='\0';
 1154:   return t;
 1155: }
 1156: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1157: {
 1158:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1159:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1160:      gives blocc="abcdef2ghi" and alocc="j".
 1161:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1162:   */
 1163:   char *s, *t;
 1164:   t=in;s=in;
 1165:   while (*in != '\0'){
 1166:     while( *in == occ){
 1167:       *blocc++ = *in++;
 1168:       s=in;
 1169:     }
 1170:     *blocc++ = *in++;
 1171:   }
 1172:   if (s == t) /* occ not found */
 1173:     *(blocc-(in-s))='\0';
 1174:   else
 1175:     *(blocc-(in-s)-1)='\0';
 1176:   in=s;
 1177:   while ( *in != '\0'){
 1178:     *alocc++ = *in++;
 1179:   }
 1180: 
 1181:   *alocc='\0';
 1182:   return s;
 1183: }
 1184: 
 1185: int nbocc(char *s, char occ)
 1186: {
 1187:   int i,j=0;
 1188:   int lg=20;
 1189:   i=0;
 1190:   lg=strlen(s);
 1191:   for(i=0; i<= lg; i++) {
 1192:   if  (s[i] == occ ) j++;
 1193:   }
 1194:   return j;
 1195: }
 1196: 
 1197: /* void cutv(char *u,char *v, char*t, char occ) */
 1198: /* { */
 1199: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1200: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1201: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1202: /*   int i,lg,j,p=0; */
 1203: /*   i=0; */
 1204: /*   lg=strlen(t); */
 1205: /*   for(j=0; j<=lg-1; j++) { */
 1206: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1207: /*   } */
 1208: 
 1209: /*   for(j=0; j<p; j++) { */
 1210: /*     (u[j] = t[j]); */
 1211: /*   } */
 1212: /*      u[p]='\0'; */
 1213: 
 1214: /*    for(j=0; j<= lg; j++) { */
 1215: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1216: /*   } */
 1217: /* } */
 1218: 
 1219: #ifdef _WIN32
 1220: char * strsep(char **pp, const char *delim)
 1221: {
 1222:   char *p, *q;
 1223:          
 1224:   if ((p = *pp) == NULL)
 1225:     return 0;
 1226:   if ((q = strpbrk (p, delim)) != NULL)
 1227:   {
 1228:     *pp = q + 1;
 1229:     *q = '\0';
 1230:   }
 1231:   else
 1232:     *pp = 0;
 1233:   return p;
 1234: }
 1235: #endif
 1236: 
 1237: /********************** nrerror ********************/
 1238: 
 1239: void nrerror(char error_text[])
 1240: {
 1241:   fprintf(stderr,"ERREUR ...\n");
 1242:   fprintf(stderr,"%s\n",error_text);
 1243:   exit(EXIT_FAILURE);
 1244: }
 1245: /*********************** vector *******************/
 1246: double *vector(int nl, int nh)
 1247: {
 1248:   double *v;
 1249:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1250:   if (!v) nrerror("allocation failure in vector");
 1251:   return v-nl+NR_END;
 1252: }
 1253: 
 1254: /************************ free vector ******************/
 1255: void free_vector(double*v, int nl, int nh)
 1256: {
 1257:   free((FREE_ARG)(v+nl-NR_END));
 1258: }
 1259: 
 1260: /************************ivector *******************************/
 1261: int *ivector(long nl,long nh)
 1262: {
 1263:   int *v;
 1264:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1265:   if (!v) nrerror("allocation failure in ivector");
 1266:   return v-nl+NR_END;
 1267: }
 1268: 
 1269: /******************free ivector **************************/
 1270: void free_ivector(int *v, long nl, long nh)
 1271: {
 1272:   free((FREE_ARG)(v+nl-NR_END));
 1273: }
 1274: 
 1275: /************************lvector *******************************/
 1276: long *lvector(long nl,long nh)
 1277: {
 1278:   long *v;
 1279:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1280:   if (!v) nrerror("allocation failure in ivector");
 1281:   return v-nl+NR_END;
 1282: }
 1283: 
 1284: /******************free lvector **************************/
 1285: void free_lvector(long *v, long nl, long nh)
 1286: {
 1287:   free((FREE_ARG)(v+nl-NR_END));
 1288: }
 1289: 
 1290: /******************* imatrix *******************************/
 1291: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1292:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1293: { 
 1294:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1295:   int **m; 
 1296:   
 1297:   /* allocate pointers to rows */ 
 1298:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1299:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1300:   m += NR_END; 
 1301:   m -= nrl; 
 1302:   
 1303:   
 1304:   /* allocate rows and set pointers to them */ 
 1305:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1306:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1307:   m[nrl] += NR_END; 
 1308:   m[nrl] -= ncl; 
 1309:   
 1310:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1311:   
 1312:   /* return pointer to array of pointers to rows */ 
 1313:   return m; 
 1314: } 
 1315: 
 1316: /****************** free_imatrix *************************/
 1317: void free_imatrix(m,nrl,nrh,ncl,nch)
 1318:       int **m;
 1319:       long nch,ncl,nrh,nrl; 
 1320:      /* free an int matrix allocated by imatrix() */ 
 1321: { 
 1322:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1323:   free((FREE_ARG) (m+nrl-NR_END)); 
 1324: } 
 1325: 
 1326: /******************* matrix *******************************/
 1327: double **matrix(long nrl, long nrh, long ncl, long nch)
 1328: {
 1329:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1330:   double **m;
 1331: 
 1332:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1333:   if (!m) nrerror("allocation failure 1 in matrix()");
 1334:   m += NR_END;
 1335:   m -= nrl;
 1336: 
 1337:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1338:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1339:   m[nrl] += NR_END;
 1340:   m[nrl] -= ncl;
 1341: 
 1342:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1343:   return m;
 1344:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1345: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1346: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1347:    */
 1348: }
 1349: 
 1350: /*************************free matrix ************************/
 1351: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1352: {
 1353:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1354:   free((FREE_ARG)(m+nrl-NR_END));
 1355: }
 1356: 
 1357: /******************* ma3x *******************************/
 1358: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1359: {
 1360:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1361:   double ***m;
 1362: 
 1363:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1364:   if (!m) nrerror("allocation failure 1 in matrix()");
 1365:   m += NR_END;
 1366:   m -= nrl;
 1367: 
 1368:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1369:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1370:   m[nrl] += NR_END;
 1371:   m[nrl] -= ncl;
 1372: 
 1373:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1374: 
 1375:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1376:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1377:   m[nrl][ncl] += NR_END;
 1378:   m[nrl][ncl] -= nll;
 1379:   for (j=ncl+1; j<=nch; j++) 
 1380:     m[nrl][j]=m[nrl][j-1]+nlay;
 1381:   
 1382:   for (i=nrl+1; i<=nrh; i++) {
 1383:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1384:     for (j=ncl+1; j<=nch; j++) 
 1385:       m[i][j]=m[i][j-1]+nlay;
 1386:   }
 1387:   return m; 
 1388:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1389:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1390:   */
 1391: }
 1392: 
 1393: /*************************free ma3x ************************/
 1394: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1395: {
 1396:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1397:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1398:   free((FREE_ARG)(m+nrl-NR_END));
 1399: }
 1400: 
 1401: /*************** function subdirf ***********/
 1402: char *subdirf(char fileres[])
 1403: {
 1404:   /* Caution optionfilefiname is hidden */
 1405:   strcpy(tmpout,optionfilefiname);
 1406:   strcat(tmpout,"/"); /* Add to the right */
 1407:   strcat(tmpout,fileres);
 1408:   return tmpout;
 1409: }
 1410: 
 1411: /*************** function subdirf2 ***********/
 1412: char *subdirf2(char fileres[], char *preop)
 1413: {
 1414:   
 1415:   /* Caution optionfilefiname is hidden */
 1416:   strcpy(tmpout,optionfilefiname);
 1417:   strcat(tmpout,"/");
 1418:   strcat(tmpout,preop);
 1419:   strcat(tmpout,fileres);
 1420:   return tmpout;
 1421: }
 1422: 
 1423: /*************** function subdirf3 ***********/
 1424: char *subdirf3(char fileres[], char *preop, char *preop2)
 1425: {
 1426:   
 1427:   /* Caution optionfilefiname is hidden */
 1428:   strcpy(tmpout,optionfilefiname);
 1429:   strcat(tmpout,"/");
 1430:   strcat(tmpout,preop);
 1431:   strcat(tmpout,preop2);
 1432:   strcat(tmpout,fileres);
 1433:   return tmpout;
 1434: }
 1435:  
 1436: /*************** function subdirfext ***********/
 1437: char *subdirfext(char fileres[], char *preop, char *postop)
 1438: {
 1439:   
 1440:   strcpy(tmpout,preop);
 1441:   strcat(tmpout,fileres);
 1442:   strcat(tmpout,postop);
 1443:   return tmpout;
 1444: }
 1445: 
 1446: /*************** function subdirfext3 ***********/
 1447: char *subdirfext3(char fileres[], char *preop, char *postop)
 1448: {
 1449:   
 1450:   /* Caution optionfilefiname is hidden */
 1451:   strcpy(tmpout,optionfilefiname);
 1452:   strcat(tmpout,"/");
 1453:   strcat(tmpout,preop);
 1454:   strcat(tmpout,fileres);
 1455:   strcat(tmpout,postop);
 1456:   return tmpout;
 1457: }
 1458:  
 1459: char *asc_diff_time(long time_sec, char ascdiff[])
 1460: {
 1461:   long sec_left, days, hours, minutes;
 1462:   days = (time_sec) / (60*60*24);
 1463:   sec_left = (time_sec) % (60*60*24);
 1464:   hours = (sec_left) / (60*60) ;
 1465:   sec_left = (sec_left) %(60*60);
 1466:   minutes = (sec_left) /60;
 1467:   sec_left = (sec_left) % (60);
 1468:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1469:   return ascdiff;
 1470: }
 1471: 
 1472: /***************** f1dim *************************/
 1473: extern int ncom; 
 1474: extern double *pcom,*xicom;
 1475: extern double (*nrfunc)(double []); 
 1476:  
 1477: double f1dim(double x) 
 1478: { 
 1479:   int j; 
 1480:   double f;
 1481:   double *xt; 
 1482:  
 1483:   xt=vector(1,ncom); 
 1484:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1485:   f=(*nrfunc)(xt); 
 1486:   free_vector(xt,1,ncom); 
 1487:   return f; 
 1488: } 
 1489: 
 1490: /*****************brent *************************/
 1491: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1492: {
 1493:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1494:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1495:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1496:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1497:    * returned function value. 
 1498:   */
 1499:   int iter; 
 1500:   double a,b,d,etemp;
 1501:   double fu=0,fv,fw,fx;
 1502:   double ftemp=0.;
 1503:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1504:   double e=0.0; 
 1505:  
 1506:   a=(ax < cx ? ax : cx); 
 1507:   b=(ax > cx ? ax : cx); 
 1508:   x=w=v=bx; 
 1509:   fw=fv=fx=(*f)(x); 
 1510:   for (iter=1;iter<=ITMAX;iter++) { 
 1511:     xm=0.5*(a+b); 
 1512:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1513:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1514:     printf(".");fflush(stdout);
 1515:     fprintf(ficlog,".");fflush(ficlog);
 1516: #ifdef DEBUGBRENT
 1517:     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);
 1518:     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);
 1519:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1520: #endif
 1521:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1522:       *xmin=x; 
 1523:       return fx; 
 1524:     } 
 1525:     ftemp=fu;
 1526:     if (fabs(e) > tol1) { 
 1527:       r=(x-w)*(fx-fv); 
 1528:       q=(x-v)*(fx-fw); 
 1529:       p=(x-v)*q-(x-w)*r; 
 1530:       q=2.0*(q-r); 
 1531:       if (q > 0.0) p = -p; 
 1532:       q=fabs(q); 
 1533:       etemp=e; 
 1534:       e=d; 
 1535:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1536: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1537:       else { 
 1538: 	d=p/q; 
 1539: 	u=x+d; 
 1540: 	if (u-a < tol2 || b-u < tol2) 
 1541: 	  d=SIGN(tol1,xm-x); 
 1542:       } 
 1543:     } else { 
 1544:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1545:     } 
 1546:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1547:     fu=(*f)(u); 
 1548:     if (fu <= fx) { 
 1549:       if (u >= x) a=x; else b=x; 
 1550:       SHFT(v,w,x,u) 
 1551:       SHFT(fv,fw,fx,fu) 
 1552:     } else { 
 1553:       if (u < x) a=u; else b=u; 
 1554:       if (fu <= fw || w == x) { 
 1555: 	v=w; 
 1556: 	w=u; 
 1557: 	fv=fw; 
 1558: 	fw=fu; 
 1559:       } else if (fu <= fv || v == x || v == w) { 
 1560: 	v=u; 
 1561: 	fv=fu; 
 1562:       } 
 1563:     } 
 1564:   } 
 1565:   nrerror("Too many iterations in brent"); 
 1566:   *xmin=x; 
 1567:   return fx; 
 1568: } 
 1569: 
 1570: /****************** mnbrak ***********************/
 1571: 
 1572: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1573: 	    double (*func)(double)) 
 1574: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1575: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1576: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1577: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1578:    */
 1579:   double ulim,u,r,q, dum;
 1580:   double fu; 
 1581: 
 1582:   double scale=10.;
 1583:   int iterscale=0;
 1584: 
 1585:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1586:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1587: 
 1588: 
 1589:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1590:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1591:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1592:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1593:   /* } */
 1594: 
 1595:   if (*fb > *fa) { 
 1596:     SHFT(dum,*ax,*bx,dum) 
 1597:     SHFT(dum,*fb,*fa,dum) 
 1598:   } 
 1599:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1600:   *fc=(*func)(*cx); 
 1601: #ifdef DEBUG
 1602:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1603:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1604: #endif
 1605:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1606:     r=(*bx-*ax)*(*fb-*fc); 
 1607:     q=(*bx-*cx)*(*fb-*fa); 
 1608:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1609:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1610:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1611:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1612:       fu=(*func)(u); 
 1613: #ifdef DEBUG
 1614:       /* f(x)=A(x-u)**2+f(u) */
 1615:       double A, fparabu; 
 1616:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1617:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1618:       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);
 1619:       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);
 1620:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1621:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1622:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1623:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1624: #endif 
 1625: #ifdef MNBRAKORIGINAL
 1626: #else
 1627: /*       if (fu > *fc) { */
 1628: /* #ifdef DEBUG */
 1629: /*       printf("mnbrak4  fu > fc \n"); */
 1630: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1631: /* #endif */
 1632: /* 	/\* 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 *\\/  *\/ */
 1633: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1634: /* 	dum=u; /\* Shifting c and u *\/ */
 1635: /* 	u = *cx; */
 1636: /* 	*cx = dum; */
 1637: /* 	dum = fu; */
 1638: /* 	fu = *fc; */
 1639: /* 	*fc =dum; */
 1640: /*       } else { /\* end *\/ */
 1641: /* #ifdef DEBUG */
 1642: /*       printf("mnbrak3  fu < fc \n"); */
 1643: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1644: /* #endif */
 1645: /* 	dum=u; /\* Shifting c and u *\/ */
 1646: /* 	u = *cx; */
 1647: /* 	*cx = dum; */
 1648: /* 	dum = fu; */
 1649: /* 	fu = *fc; */
 1650: /* 	*fc =dum; */
 1651: /*       } */
 1652: #ifdef DEBUG
 1653:       printf("mnbrak34  fu < or >= fc \n");
 1654:       fprintf(ficlog, "mnbrak34 fu < fc\n");
 1655: #endif
 1656:       dum=u; /* Shifting c and u */
 1657:       u = *cx;
 1658:       *cx = dum;
 1659:       dum = fu;
 1660:       fu = *fc;
 1661:       *fc =dum;
 1662: #endif
 1663:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1664: #ifdef DEBUG
 1665:       printf("mnbrak2  u after c but before ulim\n");
 1666:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1667: #endif
 1668:       fu=(*func)(u); 
 1669:       if (fu < *fc) { 
 1670: #ifdef DEBUG
 1671:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1672:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1673: #endif
 1674: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1675: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1676:       } 
 1677:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1678: #ifdef DEBUG
 1679:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1680:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1681: #endif
 1682:       u=ulim; 
 1683:       fu=(*func)(u); 
 1684:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1685: #ifdef DEBUG
 1686:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1687:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1688: #endif
 1689:       u=(*cx)+GOLD*(*cx-*bx); 
 1690:       fu=(*func)(u); 
 1691:     } /* end tests */
 1692:     SHFT(*ax,*bx,*cx,u) 
 1693:     SHFT(*fa,*fb,*fc,fu) 
 1694: #ifdef DEBUG
 1695:       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);
 1696:       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);
 1697: #endif
 1698:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1699: } 
 1700: 
 1701: /*************** linmin ************************/
 1702: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1703: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1704: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1705: the value of func at the returned location p . This is actually all accomplished by calling the
 1706: routines mnbrak and brent .*/
 1707: int ncom; 
 1708: double *pcom,*xicom;
 1709: double (*nrfunc)(double []); 
 1710:  
 1711: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1712: { 
 1713:   double brent(double ax, double bx, double cx, 
 1714: 	       double (*f)(double), double tol, double *xmin); 
 1715:   double f1dim(double x); 
 1716:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1717: 	      double *fc, double (*func)(double)); 
 1718:   int j; 
 1719:   double xx,xmin,bx,ax; 
 1720:   double fx,fb,fa;
 1721: 
 1722: #ifdef LINMINORIGINAL
 1723: #else
 1724:   double scale=10., axs, xxs; /* Scale added for infinity */
 1725: #endif
 1726:   
 1727:   ncom=n; 
 1728:   pcom=vector(1,n); 
 1729:   xicom=vector(1,n); 
 1730:   nrfunc=func; 
 1731:   for (j=1;j<=n;j++) { 
 1732:     pcom[j]=p[j]; 
 1733:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1734:   } 
 1735: 
 1736: #ifdef LINMINORIGINAL
 1737:   xx=1.;
 1738: #else
 1739:   axs=0.0;
 1740:   xxs=1.;
 1741:   do{
 1742:     xx= xxs;
 1743: #endif
 1744:     ax=0.;
 1745:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1746:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1747:     /* 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))   */
 1748:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1749:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1750:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1751:     /* 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]]*/
 1752: #ifdef LINMINORIGINAL
 1753: #else
 1754:     if (fx != fx){
 1755:   	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1756: 	printf("|");
 1757: 	fprintf(ficlog,"|");
 1758: #ifdef DEBUGLINMIN
 1759:   	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);
 1760: #endif
 1761:     }
 1762:   }while(fx != fx);
 1763: #endif
 1764:   
 1765: #ifdef DEBUGLINMIN
 1766:   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);
 1767:   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);
 1768: #endif
 1769:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1770:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1771:   /* fmin = f(p[j] + xmin * xi[j]) */
 1772:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1773:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1774: #ifdef DEBUG
 1775:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1776:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1777: #endif
 1778: #ifdef DEBUGLINMIN
 1779:   printf("linmin end ");
 1780:   fprintf(ficlog,"linmin end ");
 1781: #endif
 1782:   for (j=1;j<=n;j++) { 
 1783: #ifdef LINMINORIGINAL
 1784:     xi[j] *= xmin; 
 1785: #else
 1786: #ifdef DEBUGLINMIN
 1787:     if(xxs <1.0)
 1788:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1789: #endif
 1790:     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) */
 1791: #ifdef DEBUGLINMIN
 1792:     if(xxs <1.0)
 1793:       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 );
 1794: #endif
 1795: #endif
 1796:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1797:   } 
 1798: #ifdef DEBUGLINMIN
 1799:   printf("\n");
 1800:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1801:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1802:   for (j=1;j<=n;j++) { 
 1803:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1804:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1805:     if(j % ncovmodel == 0){
 1806:       printf("\n");
 1807:       fprintf(ficlog,"\n");
 1808:     }
 1809:   }
 1810: #else
 1811: #endif
 1812:   free_vector(xicom,1,n); 
 1813:   free_vector(pcom,1,n); 
 1814: } 
 1815: 
 1816: 
 1817: /*************** powell ************************/
 1818: /*
 1819: Minimization of a function func of n variables. Input consists of an initial starting point
 1820: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1821: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1822: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1823: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1824: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1825:  */
 1826: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1827: 	    double (*func)(double [])) 
 1828: { 
 1829:   void linmin(double p[], double xi[], int n, double *fret, 
 1830: 	      double (*func)(double [])); 
 1831:   int i,ibig,j; 
 1832:   double del,t,*pt,*ptt,*xit;
 1833:   double directest;
 1834:   double fp,fptt;
 1835:   double *xits;
 1836:   int niterf, itmp;
 1837: 
 1838:   pt=vector(1,n); 
 1839:   ptt=vector(1,n); 
 1840:   xit=vector(1,n); 
 1841:   xits=vector(1,n); 
 1842:   *fret=(*func)(p); 
 1843:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1844:   rcurr_time = time(NULL);  
 1845:   for (*iter=1;;++(*iter)) { 
 1846:     fp=(*fret); /* From former iteration or initial value */
 1847:     ibig=0; 
 1848:     del=0.0; 
 1849:     rlast_time=rcurr_time;
 1850:     /* (void) gettimeofday(&curr_time,&tzp); */
 1851:     rcurr_time = time(NULL);  
 1852:     curr_time = *localtime(&rcurr_time);
 1853:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1854:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1855: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1856:     for (i=1;i<=n;i++) {
 1857:       printf(" %d %.12f",i, p[i]);
 1858:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1859:       fprintf(ficrespow," %.12lf", p[i]);
 1860:     }
 1861:     printf("\n");
 1862:     fprintf(ficlog,"\n");
 1863:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1864:     if(*iter <=3){
 1865:       tml = *localtime(&rcurr_time);
 1866:       strcpy(strcurr,asctime(&tml));
 1867:       rforecast_time=rcurr_time; 
 1868:       itmp = strlen(strcurr);
 1869:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1870: 	strcurr[itmp-1]='\0';
 1871:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1872:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1873:       for(niterf=10;niterf<=30;niterf+=10){
 1874: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1875: 	forecast_time = *localtime(&rforecast_time);
 1876: 	strcpy(strfor,asctime(&forecast_time));
 1877: 	itmp = strlen(strfor);
 1878: 	if(strfor[itmp-1]=='\n')
 1879: 	strfor[itmp-1]='\0';
 1880: 	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);
 1881: 	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);
 1882:       }
 1883:     }
 1884:     for (i=1;i<=n;i++) { /* For each direction i */
 1885:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1886:       fptt=(*fret); 
 1887: #ifdef DEBUG
 1888:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1889:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1890: #endif
 1891:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1892:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1893:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1894: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1895:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1896: 	/* because that direction will be replaced unless the gain del is small */
 1897: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1898: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1899: 	/* with the new direction. */
 1900: 	del=fabs(fptt-(*fret)); 
 1901: 	ibig=i; 
 1902:       } 
 1903: #ifdef DEBUG
 1904:       printf("%d %.12e",i,(*fret));
 1905:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1906:       for (j=1;j<=n;j++) {
 1907: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1908: 	printf(" x(%d)=%.12e",j,xit[j]);
 1909: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1910:       }
 1911:       for(j=1;j<=n;j++) {
 1912: 	printf(" p(%d)=%.12e",j,p[j]);
 1913: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1914:       }
 1915:       printf("\n");
 1916:       fprintf(ficlog,"\n");
 1917: #endif
 1918:     } /* end loop on each direction i */
 1919:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1920:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1921:     /* New value of last point Pn is not computed, P(n-1) */
 1922:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1923:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1924:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1925:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1926:       /* decreased of more than 3.84  */
 1927:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1928:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1929:       /* By adding 10 parameters more the gain should be 18.31 */
 1930: 
 1931:       /* Starting the program with initial values given by a former maximization will simply change */
 1932:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1933:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1934:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1935: #ifdef DEBUG
 1936:       int k[2],l;
 1937:       k[0]=1;
 1938:       k[1]=-1;
 1939:       printf("Max: %.12e",(*func)(p));
 1940:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1941:       for (j=1;j<=n;j++) {
 1942: 	printf(" %.12e",p[j]);
 1943: 	fprintf(ficlog," %.12e",p[j]);
 1944:       }
 1945:       printf("\n");
 1946:       fprintf(ficlog,"\n");
 1947:       for(l=0;l<=1;l++) {
 1948: 	for (j=1;j<=n;j++) {
 1949: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1950: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1951: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1952: 	}
 1953: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1954: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1955:       }
 1956: #endif
 1957: 
 1958: 
 1959:       free_vector(xit,1,n); 
 1960:       free_vector(xits,1,n); 
 1961:       free_vector(ptt,1,n); 
 1962:       free_vector(pt,1,n); 
 1963:       return; 
 1964:     } /* enough precision */ 
 1965:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1966:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1967:       ptt[j]=2.0*p[j]-pt[j]; 
 1968:       xit[j]=p[j]-pt[j]; 
 1969:       pt[j]=p[j]; 
 1970:     } 
 1971:     fptt=(*func)(ptt); /* f_3 */
 1972: #ifdef POWELLF1F3
 1973: #else
 1974:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1975: #endif
 1976:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1977:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1978:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1979:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1980:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1981:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1982:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1983: #ifdef NRCORIGINAL
 1984:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1985: #else
 1986:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1987:       t= t- del*SQR(fp-fptt);
 1988: #endif
 1989:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 1990: #ifdef DEBUG
 1991:       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);
 1992:       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);
 1993:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1994: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1995:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1996: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1997:       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);
 1998:       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);
 1999: #endif
 2000: #ifdef POWELLORIGINAL
 2001:       if (t < 0.0) { /* Then we use it for new direction */
 2002: #else
 2003:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2004: 	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);
 2005:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2006:         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);
 2007:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2008:       } 
 2009:       if (directest < 0.0) { /* Then we use it for new direction */
 2010: #endif
 2011: #ifdef DEBUGLINMIN
 2012: 	printf("Before linmin in direction P%d-P0\n",n);
 2013: 	for (j=1;j<=n;j++) { 
 2014: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2015: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2016: 	  if(j % ncovmodel == 0){
 2017: 	    printf("\n");
 2018: 	    fprintf(ficlog,"\n");
 2019: 	  }
 2020: 	}
 2021: #endif
 2022: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2023: #ifdef DEBUGLINMIN
 2024: 	for (j=1;j<=n;j++) { 
 2025: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2026: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2027: 	  if(j % ncovmodel == 0){
 2028: 	    printf("\n");
 2029: 	    fprintf(ficlog,"\n");
 2030: 	  }
 2031: 	}
 2032: #endif
 2033: 	for (j=1;j<=n;j++) { 
 2034: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2035: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2036: 	}
 2037: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2038: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2039: 
 2040: #ifdef DEBUG
 2041: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2042: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2043: 	for(j=1;j<=n;j++){
 2044: 	  printf(" %.12e",xit[j]);
 2045: 	  fprintf(ficlog," %.12e",xit[j]);
 2046: 	}
 2047: 	printf("\n");
 2048: 	fprintf(ficlog,"\n");
 2049: #endif
 2050:       } /* end of t or directest negative */
 2051: #ifdef POWELLF1F3
 2052: #else
 2053:     } /* end if (fptt < fp)  */
 2054: #endif
 2055:   } /* loop iteration */ 
 2056: } 
 2057: 
 2058: /**** Prevalence limit (stable or period prevalence)  ****************/
 2059: 
 2060: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2061: {
 2062:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
 2063:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2064:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2065:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2066:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2067:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2068:   /* Initial matrix pimij */
 2069:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2070:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2071:   /*  0,                   0                  , 1} */
 2072:   /*
 2073:    * and after some iteration: */
 2074:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2075:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2076:   /*  0,                   0                  , 1} */
 2077:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2078:   /* {0.51571254859325999, 0.4842874514067399, */
 2079:   /*  0.51326036147820708, 0.48673963852179264} */
 2080:   /* If we start from prlim again, prlim tends to a constant matrix */
 2081: 
 2082:   int i, ii,j,k;
 2083:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2084:   /* double **matprod2(); */ /* test */
 2085:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2086:   double **newm;
 2087:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2088:   int ncvloop=0;
 2089:   
 2090:   min=vector(1,nlstate);
 2091:   max=vector(1,nlstate);
 2092:   meandiff=vector(1,nlstate);
 2093: 
 2094: 	/* Starting with matrix unity */
 2095:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2096:     for (j=1;j<=nlstate+ndeath;j++){
 2097:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2098:     }
 2099:   
 2100:   cov[1]=1.;
 2101:   
 2102:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2103:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2104:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2105:     ncvloop++;
 2106:     newm=savm;
 2107:     /* Covariates have to be included here again */
 2108:     cov[2]=agefin;
 2109:     if(nagesqr==1)
 2110:       cov[3]= agefin*agefin;;
 2111:     for (k=1; k<=cptcovn;k++) {
 2112:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2113: 			/* Here comes the value of the covariate 'ij' */
 2114:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2115:       /* 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])]); */
 2116:     }
 2117:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2118:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2119:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2120:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2121:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2122:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2123:     
 2124:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2125:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2126:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2127:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2128:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2129: 		/* age and covariate values of ij are in 'cov' */
 2130:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2131:     
 2132:     savm=oldm;
 2133:     oldm=newm;
 2134: 
 2135:     for(j=1; j<=nlstate; j++){
 2136:       max[j]=0.;
 2137:       min[j]=1.;
 2138:     }
 2139:     for(i=1;i<=nlstate;i++){
 2140:       sumnew=0;
 2141:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2142:       for(j=1; j<=nlstate; j++){ 
 2143: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2144: 	max[j]=FMAX(max[j],prlim[i][j]);
 2145: 	min[j]=FMIN(min[j],prlim[i][j]);
 2146:       }
 2147:     }
 2148: 
 2149:     maxmax=0.;
 2150:     for(j=1; j<=nlstate; j++){
 2151:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2152:       maxmax=FMAX(maxmax,meandiff[j]);
 2153:       /* 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); */
 2154:     } /* j loop */
 2155:     *ncvyear= (int)age- (int)agefin;
 2156:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2157:     if(maxmax < ftolpl){
 2158:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2159:       free_vector(min,1,nlstate);
 2160:       free_vector(max,1,nlstate);
 2161:       free_vector(meandiff,1,nlstate);
 2162:       return prlim;
 2163:     }
 2164:   } /* age loop */
 2165:     /* After some age loop it doesn't converge */
 2166:   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\
 2167: 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);
 2168:   /* 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); */
 2169:   free_vector(min,1,nlstate);
 2170:   free_vector(max,1,nlstate);
 2171:   free_vector(meandiff,1,nlstate);
 2172:   
 2173:   return prlim; /* should not reach here */
 2174: }
 2175: 
 2176: 
 2177:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2178: 
 2179:  /* 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) */
 2180:  /* 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) */
 2181:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
 2182: {
 2183:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2184:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2185:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2186:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2187:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2188:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2189:   /* Initial matrix pimij */
 2190:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2191:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2192:   /*  0,                   0                  , 1} */
 2193:   /*
 2194:    * and after some iteration: */
 2195:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2196:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2197:   /*  0,                   0                  , 1} */
 2198:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2199:   /* {0.51571254859325999, 0.4842874514067399, */
 2200:   /*  0.51326036147820708, 0.48673963852179264} */
 2201:   /* If we start from prlim again, prlim tends to a constant matrix */
 2202: 
 2203:   int i, ii,j,k;
 2204:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2205:   /* double **matprod2(); */ /* test */
 2206:   double **out, cov[NCOVMAX+1], **bmij();
 2207:   double **newm;
 2208:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2209:   double	 **oldm, **savm;  /* for use */
 2210: 
 2211:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2212:   int ncvloop=0;
 2213:   
 2214:   min=vector(1,nlstate);
 2215:   max=vector(1,nlstate);
 2216:   meandiff=vector(1,nlstate);
 2217: 
 2218: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2219: 	oldm=oldms; savm=savms;
 2220: 
 2221: 	/* Starting with matrix unity */
 2222: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2223: 		for (j=1;j<=nlstate+ndeath;j++){
 2224:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2225:     }
 2226:   
 2227:   cov[1]=1.;
 2228:   
 2229:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2230:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2231:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2232:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2233:     ncvloop++;
 2234:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2235: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2236:     /* Covariates have to be included here again */
 2237:     cov[2]=agefin;
 2238:     if(nagesqr==1)
 2239:       cov[3]= agefin*agefin;;
 2240:     for (k=1; k<=cptcovn;k++) {
 2241:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2242:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2243:       /* 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])]); */
 2244:     }
 2245:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2246:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2247:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2248:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2249:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2250:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2251:     
 2252:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2253:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2254:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2255:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2256:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2257: 		/* ij should be linked to the correct index of cov */
 2258: 		/* age and covariate values ij are in 'cov', but we need to pass
 2259: 		 * ij for the observed prevalence at age and status and covariate
 2260: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2261: 		 */
 2262:     /* 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 *\/ */
 2263:     /* 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 *\/ */
 2264:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2265:     savm=oldm;
 2266:     oldm=newm;
 2267:     for(j=1; j<=nlstate; j++){
 2268:       max[j]=0.;
 2269:       min[j]=1.;
 2270:     }
 2271:     for(j=1; j<=nlstate; j++){ 
 2272:       for(i=1;i<=nlstate;i++){
 2273: 				/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2274: 				bprlim[i][j]= newm[i][j];
 2275: 				max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2276: 				min[i]=FMIN(min[i],bprlim[i][j]);
 2277:       }
 2278:     }
 2279: 		
 2280:     maxmax=0.;
 2281:     for(i=1; i<=nlstate; i++){
 2282:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2283:       maxmax=FMAX(maxmax,meandiff[i]);
 2284:       /* 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); */
 2285:     } /* j loop */
 2286:     *ncvyear= -( (int)age- (int)agefin);
 2287:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2288:     if(maxmax < ftolpl){
 2289:       printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);
 2290:       free_vector(min,1,nlstate);
 2291:       free_vector(max,1,nlstate);
 2292:       free_vector(meandiff,1,nlstate);
 2293:       return bprlim;
 2294:     }
 2295:   } /* age loop */
 2296:     /* After some age loop it doesn't converge */
 2297:   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\
 2298: 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);
 2299:   /* 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); */
 2300:   free_vector(min,1,nlstate);
 2301:   free_vector(max,1,nlstate);
 2302:   free_vector(meandiff,1,nlstate);
 2303:   
 2304:   return bprlim; /* should not reach here */
 2305: }
 2306: 
 2307: /*************** transition probabilities ***************/ 
 2308: 
 2309: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2310: {
 2311:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2312:      computes the probability to be observed in state j being in state i by appying the
 2313:      model to the ncovmodel covariates (including constant and age).
 2314:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2315:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2316:      ncth covariate in the global vector x is given by the formula:
 2317:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2318:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2319:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2320:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2321:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2322:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2323:   */
 2324:   double s1, lnpijopii;
 2325:   /*double t34;*/
 2326:   int i,j, nc, ii, jj;
 2327: 
 2328: 	for(i=1; i<= nlstate; i++){
 2329: 		for(j=1; j<i;j++){
 2330: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2331: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2332: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2333: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2334: 			}
 2335: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2336: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2337: 		}
 2338: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2339: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2340: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2341: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2342: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2343: 			}
 2344: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2345: 		}
 2346: 	}
 2347:   
 2348: 	for(i=1; i<= nlstate; i++){
 2349: 		s1=0;
 2350: 		for(j=1; j<i; j++){
 2351: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2352: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2353: 		}
 2354: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2355: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2356: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2357: 		}
 2358: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2359: 		ps[i][i]=1./(s1+1.);
 2360: 		/* Computing other pijs */
 2361: 		for(j=1; j<i; j++)
 2362: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2363: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2364: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2365: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2366: 	} /* end i */
 2367:   
 2368: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2369: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2370: 			ps[ii][jj]=0;
 2371: 			ps[ii][ii]=1;
 2372: 		}
 2373: 	}
 2374:   
 2375:   
 2376: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2377: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2378: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2379: 	/*   } */
 2380: 	/*   printf("\n "); */
 2381: 	/* } */
 2382: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2383: 	/*
 2384: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2385: 		goto end;*/
 2386: 	return ps;
 2387: }
 2388: 
 2389: /*************** backward transition probabilities ***************/ 
 2390: 
 2391:  /* 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 ) */
 2392: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2393:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2394: {
 2395: 	/* Computes the backward probability at age agefin and covariate ij
 2396: 	 * and returns in **ps as well as **bmij.
 2397: 	 */
 2398:   int i, ii, j,k;
 2399: 
 2400: 	double **out, **pmij();
 2401: 	double sumnew=0.;
 2402:   double agefin;
 2403: 
 2404: 	double **dnewm, **dsavm, **doldm;
 2405: 	double **bbmij;
 2406: 
 2407:   doldm=ddoldms; /* global pointers */
 2408: 	dnewm=ddnewms;
 2409: 	dsavm=ddsavms;
 2410: 
 2411: 	agefin=cov[2];
 2412: 	/* bmij *//* age is cov[2], ij is included in cov, but we need for
 2413: 		 the observed prevalence (with this covariate ij) */
 2414: 	dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2415: 	/* We do have the matrix Px in savm  and we need pij */
 2416: 	for (j=1;j<=nlstate+ndeath;j++){
 2417: 		sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2418: 		for (ii=1;ii<=nlstate;ii++){
 2419: 			sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2420: 		} /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2421: 		for (ii=1;ii<=nlstate+ndeath;ii++){
 2422: 			if(sumnew >= 1.e-10){
 2423: 				/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2424: 				/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2425: 				/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2426: 				/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2427: 				/* }else */
 2428: 					doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2429: 			}else{
 2430: 				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);
 2431: 			}
 2432: 		} /*End ii */
 2433: 	} /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2434: 		/* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2435: 	bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2436: 	/* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2437: 	/* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2438: 	/* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2439: 	/* left Product of this matrix by diag matrix of prevalences (savm) */
 2440: 	for (j=1;j<=nlstate+ndeath;j++){
 2441: 		for (ii=1;ii<=nlstate+ndeath;ii++){
 2442: 			dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2443: 		}
 2444: 	} /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2445: 	ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2446: 	/* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2447: 	/* end bmij */
 2448: 	return ps; 
 2449: }
 2450: /*************** transition probabilities ***************/ 
 2451: 
 2452: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2453: {
 2454:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2455:      computes the probability to be observed in state j being in state i by appying the
 2456:      model to the ncovmodel covariates (including constant and age).
 2457:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2458:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2459:      ncth covariate in the global vector x is given by the formula:
 2460:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2461:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2462:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2463:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2464:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2465:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2466:   */
 2467:   double s1, lnpijopii;
 2468:   /*double t34;*/
 2469:   int i,j, nc, ii, jj;
 2470: 
 2471: 	for(i=1; i<= nlstate; i++){
 2472: 		for(j=1; j<i;j++){
 2473: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2474: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2475: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2476: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2477: 			}
 2478: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2479: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2480: 		}
 2481: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2482: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2483: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2484: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2485: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2486: 			}
 2487: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2488: 		}
 2489: 	}
 2490: 	
 2491: 	for(i=1; i<= nlstate; i++){
 2492: 		s1=0;
 2493: 		for(j=1; j<i; j++){
 2494: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2495: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2496: 		}
 2497: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2498: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2499: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2500: 		}
 2501: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2502: 		ps[i][i]=1./(s1+1.);
 2503: 		/* Computing other pijs */
 2504: 		for(j=1; j<i; j++)
 2505: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2506: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2507: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2508: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2509: 	} /* end i */
 2510: 	
 2511: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2512: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2513: 			ps[ii][jj]=0;
 2514: 			ps[ii][ii]=1;
 2515: 		}
 2516: 	}
 2517: 	/* Added for backcast */ /* Transposed matrix too */
 2518: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2519: 		s1=0.;
 2520: 		for(ii=1; ii<= nlstate+ndeath; ii++){
 2521: 			s1+=ps[ii][jj];
 2522: 		}
 2523: 		for(ii=1; ii<= nlstate; ii++){
 2524: 			ps[ii][jj]=ps[ii][jj]/s1;
 2525: 		}
 2526: 	}
 2527: 	/* Transposition */
 2528: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2529: 		for(ii=jj; ii<= nlstate+ndeath; ii++){
 2530: 			s1=ps[ii][jj];
 2531: 			ps[ii][jj]=ps[jj][ii];
 2532: 			ps[jj][ii]=s1;
 2533: 		}
 2534: 	}
 2535: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2536: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2537: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2538: 	/*   } */
 2539: 	/*   printf("\n "); */
 2540: 	/* } */
 2541: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2542: 	/*
 2543: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2544: 		goto end;*/
 2545: 	return ps;
 2546: }
 2547: 
 2548: 
 2549: /**************** Product of 2 matrices ******************/
 2550: 
 2551: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2552: {
 2553:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2554:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2555:   /* in, b, out are matrice of pointers which should have been initialized 
 2556:      before: only the contents of out is modified. The function returns
 2557:      a pointer to pointers identical to out */
 2558:   int i, j, k;
 2559:   for(i=nrl; i<= nrh; i++)
 2560:     for(k=ncolol; k<=ncoloh; k++){
 2561:       out[i][k]=0.;
 2562:       for(j=ncl; j<=nch; j++)
 2563:   	out[i][k] +=in[i][j]*b[j][k];
 2564:     }
 2565:   return out;
 2566: }
 2567: 
 2568: 
 2569: /************* Higher Matrix Product ***************/
 2570: 
 2571: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2572: {
 2573:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2574:      'nhstepm*hstepm*stepm' months (i.e. until
 2575:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2576:      nhstepm*hstepm matrices. 
 2577:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2578:      (typically every 2 years instead of every month which is too big 
 2579:      for the memory).
 2580:      Model is determined by parameters x and covariates have to be 
 2581:      included manually here. 
 2582: 
 2583:      */
 2584: 
 2585:   int i, j, d, h, k;
 2586:   double **out, cov[NCOVMAX+1];
 2587:   double **newm;
 2588:   double agexact;
 2589:   double agebegin, ageend;
 2590: 
 2591:   /* Hstepm could be zero and should return the unit matrix */
 2592:   for (i=1;i<=nlstate+ndeath;i++)
 2593:     for (j=1;j<=nlstate+ndeath;j++){
 2594:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2595:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2596:     }
 2597:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2598:   for(h=1; h <=nhstepm; h++){
 2599:     for(d=1; d <=hstepm; d++){
 2600:       newm=savm;
 2601:       /* Covariates have to be included here again */
 2602:       cov[1]=1.;
 2603:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2604:       cov[2]=agexact;
 2605:       if(nagesqr==1)
 2606: 				cov[3]= agexact*agexact;
 2607:       for (k=1; k<=cptcovn;k++) 
 2608: 				cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2609: 			/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2610:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2611: 				/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2612: 				cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2613: 			/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2614:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2615: 				cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2616: 			/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2617: 
 2618: 
 2619:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2620:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2621: 			/* right multiplication of oldm by the current matrix */
 2622:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2623: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2624:       /* if((int)age == 70){ */
 2625:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2626:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2627:       /* 	  printf("%d pmmij ",i); */
 2628:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2629:       /* 	    printf("%f ",pmmij[i][j]); */
 2630:       /* 	  } */
 2631:       /* 	  printf(" oldm "); */
 2632:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2633:       /* 	    printf("%f ",oldm[i][j]); */
 2634:       /* 	  } */
 2635:       /* 	  printf("\n"); */
 2636:       /* 	} */
 2637:       /* } */
 2638:       savm=oldm;
 2639:       oldm=newm;
 2640:     }
 2641:     for(i=1; i<=nlstate+ndeath; i++)
 2642:       for(j=1;j<=nlstate+ndeath;j++) {
 2643: 				po[i][j][h]=newm[i][j];
 2644: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2645:       }
 2646:     /*printf("h=%d ",h);*/
 2647:   } /* end h */
 2648: 	/*     printf("\n H=%d \n",h); */
 2649:   return po;
 2650: }
 2651: 
 2652: /************* Higher Back Matrix Product ***************/
 2653: /* 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 ) */
 2654:  double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 2655: {
 2656:   /* Computes the transition matrix starting at age 'age' over
 2657:      'nhstepm*hstepm*stepm' months (i.e. until
 2658:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 2659:      nhstepm*hstepm matrices.
 2660:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 2661:      (typically every 2 years instead of every month which is too big
 2662:      for the memory).
 2663:      Model is determined by parameters x and covariates have to be
 2664:      included manually here.
 2665: 
 2666:      */
 2667: 
 2668:   int i, j, d, h, k;
 2669:   double **out, cov[NCOVMAX+1];
 2670:   double **newm;
 2671:   double agexact;
 2672:   double agebegin, ageend;
 2673: 	double **oldm, **savm;
 2674: 
 2675: 	oldm=oldms;savm=savms;
 2676:   /* Hstepm could be zero and should return the unit matrix */
 2677:   for (i=1;i<=nlstate+ndeath;i++)
 2678:     for (j=1;j<=nlstate+ndeath;j++){
 2679:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2680:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2681:     }
 2682:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2683:   for(h=1; h <=nhstepm; h++){
 2684:     for(d=1; d <=hstepm; d++){
 2685:       newm=savm;
 2686:       /* Covariates have to be included here again */
 2687:       cov[1]=1.;
 2688:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2689:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 2690:       cov[2]=agexact;
 2691:       if(nagesqr==1)
 2692: 				cov[3]= agexact*agexact;
 2693:       for (k=1; k<=cptcovn;k++)
 2694: 				cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2695: 			/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2696:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2697: 				/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2698: 				cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2699: 			/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2700:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2701: 				cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2702: 			/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2703: 			
 2704: 			
 2705:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2706:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2707:       /* Careful transposed matrix */
 2708: 			/* age is in cov[2] */
 2709:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 2710: 			/* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 2711:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 2712: 									 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 2713:       /* if((int)age == 70){ */
 2714:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2715:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2716:       /* 	  printf("%d pmmij ",i); */
 2717:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2718:       /* 	    printf("%f ",pmmij[i][j]); */
 2719:       /* 	  } */
 2720:       /* 	  printf(" oldm "); */
 2721:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2722:       /* 	    printf("%f ",oldm[i][j]); */
 2723:       /* 	  } */
 2724:       /* 	  printf("\n"); */
 2725:       /* 	} */
 2726:       /* } */
 2727:       savm=oldm;
 2728:       oldm=newm;
 2729:     }
 2730:     for(i=1; i<=nlstate+ndeath; i++)
 2731:       for(j=1;j<=nlstate+ndeath;j++) {
 2732: 				po[i][j][h]=newm[i][j];
 2733: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2734:       }
 2735:     /*printf("h=%d ",h);*/
 2736:   } /* end h */
 2737: 	/*     printf("\n H=%d \n",h); */
 2738:   return po;
 2739: }
 2740: 
 2741: 
 2742: #ifdef NLOPT
 2743:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2744:   double fret;
 2745:   double *xt;
 2746:   int j;
 2747:   myfunc_data *d2 = (myfunc_data *) pd;
 2748: /* xt = (p1-1); */
 2749:   xt=vector(1,n); 
 2750:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2751: 
 2752:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2753:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2754:   printf("Function = %.12lf ",fret);
 2755:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2756:   printf("\n");
 2757:  free_vector(xt,1,n);
 2758:   return fret;
 2759: }
 2760: #endif
 2761: 
 2762: /*************** log-likelihood *************/
 2763: double func( double *x)
 2764: {
 2765:   int i, ii, j, k, mi, d, kk;
 2766:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2767:   double **out;
 2768:   double sw; /* Sum of weights */
 2769:   double lli; /* Individual log likelihood */
 2770:   int s1, s2;
 2771:   double bbh, survp;
 2772:   long ipmx;
 2773:   double agexact;
 2774:   /*extern weight */
 2775:   /* We are differentiating ll according to initial status */
 2776:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2777:   /*for(i=1;i<imx;i++) 
 2778:     printf(" %d\n",s[4][i]);
 2779:   */
 2780: 
 2781:   ++countcallfunc;
 2782: 
 2783:   cov[1]=1.;
 2784: 
 2785:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2786: 
 2787:   if(mle==1){
 2788:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2789:       /* Computes the values of the ncovmodel covariates of the model
 2790: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2791: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2792: 	 to be observed in j being in i according to the model.
 2793:        */
 2794:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2795: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2796:       }
 2797:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2798: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2799: 	 has been calculated etc */
 2800:       for(mi=1; mi<= wav[i]-1; mi++){
 2801: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2802: 	  for (j=1;j<=nlstate+ndeath;j++){
 2803: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2804: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2805: 	  }
 2806: 	for(d=0; d<dh[mi][i]; d++){
 2807: 	  newm=savm;
 2808: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2809: 	  cov[2]=agexact;
 2810: 	  if(nagesqr==1)
 2811: 	    cov[3]= agexact*agexact;
 2812: 	  for (kk=1; kk<=cptcovage;kk++) {
 2813: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2814: 	  }
 2815: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2816: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2817: 	  savm=oldm;
 2818: 	  oldm=newm;
 2819: 	} /* end mult */
 2820:       
 2821: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2822: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2823: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2824: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2825: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2826: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2827: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2828: 	 * probability in order to take into account the bias as a fraction of the way
 2829: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2830: 	 * -stepm/2 to stepm/2 .
 2831: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2832: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2833: 	 */
 2834: 	s1=s[mw[mi][i]][i];
 2835: 	s2=s[mw[mi+1][i]][i];
 2836: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2837: 	/* bias bh is positive if real duration
 2838: 	 * is higher than the multiple of stepm and negative otherwise.
 2839: 	 */
 2840: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2841: 	if( s2 > nlstate){ 
 2842: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2843: 	     then the contribution to the likelihood is the probability to 
 2844: 	     die between last step unit time and current  step unit time, 
 2845: 	     which is also equal to probability to die before dh 
 2846: 	     minus probability to die before dh-stepm . 
 2847: 	     In version up to 0.92 likelihood was computed
 2848: 	as if date of death was unknown. Death was treated as any other
 2849: 	health state: the date of the interview describes the actual state
 2850: 	and not the date of a change in health state. The former idea was
 2851: 	to consider that at each interview the state was recorded
 2852: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2853: 	introduced the exact date of death then we should have modified
 2854: 	the contribution of an exact death to the likelihood. This new
 2855: 	contribution is smaller and very dependent of the step unit
 2856: 	stepm. It is no more the probability to die between last interview
 2857: 	and month of death but the probability to survive from last
 2858: 	interview up to one month before death multiplied by the
 2859: 	probability to die within a month. Thanks to Chris
 2860: 	Jackson for correcting this bug.  Former versions increased
 2861: 	mortality artificially. The bad side is that we add another loop
 2862: 	which slows down the processing. The difference can be up to 10%
 2863: 	lower mortality.
 2864: 	  */
 2865: 	/* If, at the beginning of the maximization mostly, the
 2866: 	   cumulative probability or probability to be dead is
 2867: 	   constant (ie = 1) over time d, the difference is equal to
 2868: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2869: 	   s1 at precedent wave, to be dead a month before current
 2870: 	   wave is equal to probability, being at state s1 at
 2871: 	   precedent wave, to be dead at mont of the current
 2872: 	   wave. Then the observed probability (that this person died)
 2873: 	   is null according to current estimated parameter. In fact,
 2874: 	   it should be very low but not zero otherwise the log go to
 2875: 	   infinity.
 2876: 	*/
 2877: /* #ifdef INFINITYORIGINAL */
 2878: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2879: /* #else */
 2880: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2881: /* 	    lli=log(mytinydouble); */
 2882: /* 	  else */
 2883: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2884: /* #endif */
 2885: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2886: 	  
 2887: 	} else if  ( s2==-1 ) { /* alive */
 2888: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2889: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2890: 	  /*survp += out[s1][j]; */
 2891: 	  lli= log(survp);
 2892: 	}
 2893:  	else if  (s2==-4) { 
 2894: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2895: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2896:  	  lli= log(survp); 
 2897:  	} 
 2898:  	else if  (s2==-5) { 
 2899:  	  for (j=1,survp=0. ; j<=2; j++)  
 2900: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2901:  	  lli= log(survp); 
 2902:  	} 
 2903: 	else{
 2904: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2905: 	  /*  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 */
 2906: 	} 
 2907: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2908: 	/*if(lli ==000.0)*/
 2909: 	/*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); */
 2910:   	ipmx +=1;
 2911: 	sw += weight[i];
 2912: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2913: 	/* if (lli < log(mytinydouble)){ */
 2914: 	/*   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); */
 2915: 	/*   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]); */
 2916: 	/* } */
 2917:       } /* end of wave */
 2918:     } /* end of individual */
 2919:   }  else if(mle==2){
 2920:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2921:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2922:       for(mi=1; mi<= wav[i]-1; mi++){
 2923: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2924: 	  for (j=1;j<=nlstate+ndeath;j++){
 2925: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2926: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2927: 	  }
 2928: 	for(d=0; d<=dh[mi][i]; d++){
 2929: 	  newm=savm;
 2930: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2931: 	  cov[2]=agexact;
 2932: 	  if(nagesqr==1)
 2933: 	    cov[3]= agexact*agexact;
 2934: 	  for (kk=1; kk<=cptcovage;kk++) {
 2935: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2936: 	  }
 2937: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2938: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2939: 	  savm=oldm;
 2940: 	  oldm=newm;
 2941: 	} /* end mult */
 2942:       
 2943: 	s1=s[mw[mi][i]][i];
 2944: 	s2=s[mw[mi+1][i]][i];
 2945: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2946: 	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 */
 2947: 	ipmx +=1;
 2948: 	sw += weight[i];
 2949: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2950:       } /* end of wave */
 2951:     } /* end of individual */
 2952:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2953:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2954:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2955:       for(mi=1; mi<= wav[i]-1; mi++){
 2956: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2957: 	  for (j=1;j<=nlstate+ndeath;j++){
 2958: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2959: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2960: 	  }
 2961: 	for(d=0; d<dh[mi][i]; d++){
 2962: 	  newm=savm;
 2963: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2964: 	  cov[2]=agexact;
 2965: 	  if(nagesqr==1)
 2966: 	    cov[3]= agexact*agexact;
 2967: 	  for (kk=1; kk<=cptcovage;kk++) {
 2968: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2969: 	  }
 2970: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2971: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2972: 	  savm=oldm;
 2973: 	  oldm=newm;
 2974: 	} /* end mult */
 2975:       
 2976: 	s1=s[mw[mi][i]][i];
 2977: 	s2=s[mw[mi+1][i]][i];
 2978: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2979: 	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 */
 2980: 	ipmx +=1;
 2981: 	sw += weight[i];
 2982: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2983:       } /* end of wave */
 2984:     } /* end of individual */
 2985:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2986:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2987:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2988:       for(mi=1; mi<= wav[i]-1; mi++){
 2989: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2990: 	  for (j=1;j<=nlstate+ndeath;j++){
 2991: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2992: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2993: 	  }
 2994: 	for(d=0; d<dh[mi][i]; d++){
 2995: 	  newm=savm;
 2996: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2997: 	  cov[2]=agexact;
 2998: 	  if(nagesqr==1)
 2999: 	    cov[3]= agexact*agexact;
 3000: 	  for (kk=1; kk<=cptcovage;kk++) {
 3001: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3002: 	  }
 3003: 	
 3004: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3005: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3006: 	  savm=oldm;
 3007: 	  oldm=newm;
 3008: 	} /* end mult */
 3009:       
 3010: 	s1=s[mw[mi][i]][i];
 3011: 	s2=s[mw[mi+1][i]][i];
 3012: 	if( s2 > nlstate){ 
 3013: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3014: 	} else if  ( s2==-1 ) { /* alive */
 3015: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3016: 	    survp += out[s1][j];
 3017: 	  lli= log(survp);
 3018: 	}else{
 3019: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3020: 	}
 3021: 	ipmx +=1;
 3022: 	sw += weight[i];
 3023: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3024: /* 	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]); */
 3025:       } /* end of wave */
 3026:     } /* end of individual */
 3027:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3028:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3029:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3030:       for(mi=1; mi<= wav[i]-1; mi++){
 3031: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3032: 	  for (j=1;j<=nlstate+ndeath;j++){
 3033: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3034: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3035: 	  }
 3036: 	for(d=0; d<dh[mi][i]; d++){
 3037: 	  newm=savm;
 3038: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3039: 	  cov[2]=agexact;
 3040: 	  if(nagesqr==1)
 3041: 	    cov[3]= agexact*agexact;
 3042: 	  for (kk=1; kk<=cptcovage;kk++) {
 3043: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3044: 	  }
 3045: 	
 3046: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3047: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3048: 	  savm=oldm;
 3049: 	  oldm=newm;
 3050: 	} /* end mult */
 3051:       
 3052: 	s1=s[mw[mi][i]][i];
 3053: 	s2=s[mw[mi+1][i]][i];
 3054: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3055: 	ipmx +=1;
 3056: 	sw += weight[i];
 3057: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3058: 	/*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]);*/
 3059:       } /* end of wave */
 3060:     } /* end of individual */
 3061:   } /* End of if */
 3062:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3063:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3064:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3065:   return -l;
 3066: }
 3067: 
 3068: /*************** log-likelihood *************/
 3069: double funcone( double *x)
 3070: {
 3071:   /* Same as likeli but slower because of a lot of printf and if */
 3072:   int i, ii, j, k, mi, d, kk;
 3073:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3074:   double **out;
 3075:   double lli; /* Individual log likelihood */
 3076:   double llt;
 3077:   int s1, s2;
 3078:   double bbh, survp;
 3079:   double agexact;
 3080:   double agebegin, ageend;
 3081:   /*extern weight */
 3082:   /* We are differentiating ll according to initial status */
 3083:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3084:   /*for(i=1;i<imx;i++) 
 3085:     printf(" %d\n",s[4][i]);
 3086:   */
 3087:   cov[1]=1.;
 3088: 
 3089:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3090: 
 3091:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3092:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3093:     for(mi=1; mi<= wav[i]-1; mi++){
 3094:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3095: 	for (j=1;j<=nlstate+ndeath;j++){
 3096: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3097: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3098: 	}
 3099:       
 3100:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3101:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3102:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3103: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3104: 	  and mw[mi+1][i]. dh depends on stepm.*/
 3105: 	newm=savm;
 3106: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3107: 	cov[2]=agexact;
 3108: 	if(nagesqr==1)
 3109: 	  cov[3]= agexact*agexact;
 3110: 	for (kk=1; kk<=cptcovage;kk++) {
 3111: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3112: 	}
 3113: 
 3114: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3115: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3116: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3117: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3118: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3119: 	savm=oldm;
 3120: 	oldm=newm;
 3121:       } /* end mult */
 3122:       
 3123:       s1=s[mw[mi][i]][i];
 3124:       s2=s[mw[mi+1][i]][i];
 3125:       /* if(s2==-1){ */
 3126:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3127:       /* 	/\* exit(1); *\/ */
 3128:       /* } */
 3129:       bbh=(double)bh[mi][i]/(double)stepm; 
 3130:       /* bias is positive if real duration
 3131:        * is higher than the multiple of stepm and negative otherwise.
 3132:        */
 3133:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3134: 	lli=log(out[s1][s2] - savm[s1][s2]);
 3135:       } else if  ( s2==-1 ) { /* alive */
 3136: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 3137: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3138: 	lli= log(survp);
 3139:       }else if (mle==1){
 3140: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3141:       } else if(mle==2){
 3142: 	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 */
 3143:       } else if(mle==3){  /* exponential inter-extrapolation */
 3144: 	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 */
 3145:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3146: 	lli=log(out[s1][s2]); /* Original formula */
 3147:       } else{  /* mle=0 back to 1 */
 3148: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3149: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 3150:       } /* End of if */
 3151:       ipmx +=1;
 3152:       sw += weight[i];
 3153:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3154:       /*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]); */
 3155:       if(globpr){
 3156: 	fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
 3157:  %11.6f %11.6f %11.6f ", \
 3158: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3159: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3160: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3161: 	  llt +=ll[k]*gipmx/gsw;
 3162: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3163: 	}
 3164: 	fprintf(ficresilk," %10.6f\n", -llt);
 3165:       }
 3166:     } /* end of wave */
 3167:   } /* end of individual */
 3168:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3169:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3170:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3171:   if(globpr==0){ /* First time we count the contributions and weights */
 3172:     gipmx=ipmx;
 3173:     gsw=sw;
 3174:   }
 3175:   return -l;
 3176: }
 3177: 
 3178: 
 3179: /*************** function likelione ***********/
 3180: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3181: {
 3182:   /* This routine should help understanding what is done with 
 3183:      the selection of individuals/waves and
 3184:      to check the exact contribution to the likelihood.
 3185:      Plotting could be done.
 3186:    */
 3187:   int k;
 3188: 
 3189:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3190:     strcpy(fileresilk,"ILK_"); 
 3191:     strcat(fileresilk,fileresu);
 3192:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3193:       printf("Problem with resultfile: %s\n", fileresilk);
 3194:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3195:     }
 3196:     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");
 3197:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3198:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3199:     for(k=1; k<=nlstate; k++) 
 3200:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3201:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3202:   }
 3203: 
 3204:   *fretone=(*funcone)(p);
 3205:   if(*globpri !=0){
 3206:     fclose(ficresilk);
 3207:     if (mle ==0)
 3208:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3209:     else if(mle >=1)
 3210:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3211:     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));
 3212:     
 3213:       
 3214:     for (k=1; k<= nlstate ; k++) {
 3215:       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> \
 3216: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3217:     }
 3218:     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> \
 3219: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3220:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3221: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3222:     fflush(fichtm);
 3223:   }
 3224:   return;
 3225: }
 3226: 
 3227: 
 3228: /*********** Maximum Likelihood Estimation ***************/
 3229: 
 3230: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3231: {
 3232:   int i,j, iter=0;
 3233:   double **xi;
 3234:   double fret;
 3235:   double fretone; /* Only one call to likelihood */
 3236:   /*  char filerespow[FILENAMELENGTH];*/
 3237: 
 3238: #ifdef NLOPT
 3239:   int creturn;
 3240:   nlopt_opt opt;
 3241:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3242:   double *lb;
 3243:   double minf; /* the minimum objective value, upon return */
 3244:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3245:   myfunc_data dinst, *d = &dinst;
 3246: #endif
 3247: 
 3248: 
 3249:   xi=matrix(1,npar,1,npar);
 3250:   for (i=1;i<=npar;i++)
 3251:     for (j=1;j<=npar;j++)
 3252:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3253:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3254:   strcpy(filerespow,"POW_"); 
 3255:   strcat(filerespow,fileres);
 3256:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3257:     printf("Problem with resultfile: %s\n", filerespow);
 3258:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3259:   }
 3260:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3261:   for (i=1;i<=nlstate;i++)
 3262:     for(j=1;j<=nlstate+ndeath;j++)
 3263:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3264:   fprintf(ficrespow,"\n");
 3265: #ifdef POWELL
 3266:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3267: #endif
 3268: 
 3269: #ifdef NLOPT
 3270: #ifdef NEWUOA
 3271:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3272: #else
 3273:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3274: #endif
 3275:   lb=vector(0,npar-1);
 3276:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3277:   nlopt_set_lower_bounds(opt, lb);
 3278:   nlopt_set_initial_step1(opt, 0.1);
 3279:   
 3280:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3281:   d->function = func;
 3282:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3283:   nlopt_set_min_objective(opt, myfunc, d);
 3284:   nlopt_set_xtol_rel(opt, ftol);
 3285:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3286:     printf("nlopt failed! %d\n",creturn); 
 3287:   }
 3288:   else {
 3289:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3290:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3291:     iter=1; /* not equal */
 3292:   }
 3293:   nlopt_destroy(opt);
 3294: #endif
 3295:   free_matrix(xi,1,npar,1,npar);
 3296:   fclose(ficrespow);
 3297:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3298:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3299:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3300: 
 3301: }
 3302: 
 3303: /**** Computes Hessian and covariance matrix ***/
 3304: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3305: {
 3306:   double  **a,**y,*x,pd;
 3307:   /* double **hess; */
 3308:   int i, j;
 3309:   int *indx;
 3310: 
 3311:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3312:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3313:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3314:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3315:   double gompertz(double p[]);
 3316:   /* hess=matrix(1,npar,1,npar); */
 3317: 
 3318:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3319:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3320:   for (i=1;i<=npar;i++){
 3321:     printf("%d-",i);fflush(stdout);
 3322:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3323:    
 3324:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3325:     
 3326:     /*  printf(" %f ",p[i]);
 3327: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3328:   }
 3329:   
 3330:   for (i=1;i<=npar;i++) {
 3331:     for (j=1;j<=npar;j++)  {
 3332:       if (j>i) { 
 3333: 	printf(".%d-%d",i,j);fflush(stdout);
 3334: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3335: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3336: 	
 3337: 	hess[j][i]=hess[i][j];    
 3338: 	/*printf(" %lf ",hess[i][j]);*/
 3339:       }
 3340:     }
 3341:   }
 3342:   printf("\n");
 3343:   fprintf(ficlog,"\n");
 3344: 
 3345:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3346:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3347:   
 3348:   a=matrix(1,npar,1,npar);
 3349:   y=matrix(1,npar,1,npar);
 3350:   x=vector(1,npar);
 3351:   indx=ivector(1,npar);
 3352:   for (i=1;i<=npar;i++)
 3353:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3354:   ludcmp(a,npar,indx,&pd);
 3355: 
 3356:   for (j=1;j<=npar;j++) {
 3357:     for (i=1;i<=npar;i++) x[i]=0;
 3358:     x[j]=1;
 3359:     lubksb(a,npar,indx,x);
 3360:     for (i=1;i<=npar;i++){ 
 3361:       matcov[i][j]=x[i];
 3362:     }
 3363:   }
 3364: 
 3365:   printf("\n#Hessian matrix#\n");
 3366:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3367:   for (i=1;i<=npar;i++) { 
 3368:     for (j=1;j<=npar;j++) { 
 3369:       printf("%.6e ",hess[i][j]);
 3370:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3371:     }
 3372:     printf("\n");
 3373:     fprintf(ficlog,"\n");
 3374:   }
 3375: 
 3376:   /* printf("\n#Covariance matrix#\n"); */
 3377:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3378:   /* for (i=1;i<=npar;i++) {  */
 3379:   /*   for (j=1;j<=npar;j++) {  */
 3380:   /*     printf("%.6e ",matcov[i][j]); */
 3381:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3382:   /*   } */
 3383:   /*   printf("\n"); */
 3384:   /*   fprintf(ficlog,"\n"); */
 3385:   /* } */
 3386: 
 3387:   /* Recompute Inverse */
 3388:   /* for (i=1;i<=npar;i++) */
 3389:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3390:   /* ludcmp(a,npar,indx,&pd); */
 3391: 
 3392:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3393: 
 3394:   /* for (j=1;j<=npar;j++) { */
 3395:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3396:   /*   x[j]=1; */
 3397:   /*   lubksb(a,npar,indx,x); */
 3398:   /*   for (i=1;i<=npar;i++){  */
 3399:   /*     y[i][j]=x[i]; */
 3400:   /*     printf("%.3e ",y[i][j]); */
 3401:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3402:   /*   } */
 3403:   /*   printf("\n"); */
 3404:   /*   fprintf(ficlog,"\n"); */
 3405:   /* } */
 3406: 
 3407:   /* Verifying the inverse matrix */
 3408: #ifdef DEBUGHESS
 3409:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3410: 
 3411:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3412:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3413: 
 3414:   for (j=1;j<=npar;j++) {
 3415:     for (i=1;i<=npar;i++){ 
 3416:       printf("%.2f ",y[i][j]);
 3417:       fprintf(ficlog,"%.2f ",y[i][j]);
 3418:     }
 3419:     printf("\n");
 3420:     fprintf(ficlog,"\n");
 3421:   }
 3422: #endif
 3423: 
 3424:   free_matrix(a,1,npar,1,npar);
 3425:   free_matrix(y,1,npar,1,npar);
 3426:   free_vector(x,1,npar);
 3427:   free_ivector(indx,1,npar);
 3428:   /* free_matrix(hess,1,npar,1,npar); */
 3429: 
 3430: 
 3431: }
 3432: 
 3433: /*************** hessian matrix ****************/
 3434: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3435: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3436:   int i;
 3437:   int l=1, lmax=20;
 3438:   double k1,k2, res, fx;
 3439:   double p2[MAXPARM+1]; /* identical to x */
 3440:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3441:   int k=0,kmax=10;
 3442:   double l1;
 3443: 
 3444:   fx=func(x);
 3445:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3446:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3447:     l1=pow(10,l);
 3448:     delts=delt;
 3449:     for(k=1 ; k <kmax; k=k+1){
 3450:       delt = delta*(l1*k);
 3451:       p2[theta]=x[theta] +delt;
 3452:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3453:       p2[theta]=x[theta]-delt;
 3454:       k2=func(p2)-fx;
 3455:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3456:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3457:       
 3458: #ifdef DEBUGHESSII
 3459:       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);
 3460:       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);
 3461: #endif
 3462:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3463:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3464: 	k=kmax;
 3465:       }
 3466:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3467: 	k=kmax; l=lmax*10;
 3468:       }
 3469:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3470: 	delts=delt;
 3471:       }
 3472:     } /* End loop k */
 3473:   }
 3474:   delti[theta]=delts;
 3475:   return res; 
 3476:   
 3477: }
 3478: 
 3479: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3480: {
 3481:   int i;
 3482:   int l=1, lmax=20;
 3483:   double k1,k2,k3,k4,res,fx;
 3484:   double p2[MAXPARM+1];
 3485:   int k, kmax=1;
 3486:   double v1, v2, cv12, lc1, lc2;
 3487: 
 3488:   int firstime=0;
 3489:   
 3490:   fx=func(x);
 3491:   for (k=1; k<=kmax; k=k+10) {
 3492:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3493:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3494:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3495:     k1=func(p2)-fx;
 3496:   
 3497:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3498:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3499:     k2=func(p2)-fx;
 3500:   
 3501:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3502:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3503:     k3=func(p2)-fx;
 3504:   
 3505:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3506:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3507:     k4=func(p2)-fx;
 3508:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3509:     if(k1*k2*k3*k4 <0.){
 3510:       firstime=1;
 3511:       kmax=kmax+10;
 3512:     }
 3513:     if(kmax >=10 || firstime ==1){
 3514:       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);
 3515:       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);
 3516:       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);
 3517:       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);
 3518:     }
 3519: #ifdef DEBUGHESSIJ
 3520:     v1=hess[thetai][thetai];
 3521:     v2=hess[thetaj][thetaj];
 3522:     cv12=res;
 3523:     /* Computing eigen value of Hessian matrix */
 3524:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3525:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3526:     if ((lc2 <0) || (lc1 <0) ){
 3527:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3528:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3529:       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);
 3530:       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);
 3531:     }
 3532: #endif
 3533:   }
 3534:   return res;
 3535: }
 3536: 
 3537:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3538: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3539: /* { */
 3540: /*   int i; */
 3541: /*   int l=1, lmax=20; */
 3542: /*   double k1,k2,k3,k4,res,fx; */
 3543: /*   double p2[MAXPARM+1]; */
 3544: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3545: /*   int k=0,kmax=10; */
 3546: /*   double l1; */
 3547:   
 3548: /*   fx=func(x); */
 3549: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3550: /*     l1=pow(10,l); */
 3551: /*     delts=delt; */
 3552: /*     for(k=1 ; k <kmax; k=k+1){ */
 3553: /*       delt = delti*(l1*k); */
 3554: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3555: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3556: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3557: /*       k1=func(p2)-fx; */
 3558:       
 3559: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3560: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3561: /*       k2=func(p2)-fx; */
 3562:       
 3563: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3564: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3565: /*       k3=func(p2)-fx; */
 3566:       
 3567: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3568: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3569: /*       k4=func(p2)-fx; */
 3570: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3571: /* #ifdef DEBUGHESSIJ */
 3572: /*       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); */
 3573: /*       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); */
 3574: /* #endif */
 3575: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3576: /* 	k=kmax; */
 3577: /*       } */
 3578: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3579: /* 	k=kmax; l=lmax*10; */
 3580: /*       } */
 3581: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3582: /* 	delts=delt; */
 3583: /*       } */
 3584: /*     } /\* End loop k *\/ */
 3585: /*   } */
 3586: /*   delti[theta]=delts; */
 3587: /*   return res;  */
 3588: /* } */
 3589: 
 3590: 
 3591: /************** Inverse of matrix **************/
 3592: void ludcmp(double **a, int n, int *indx, double *d) 
 3593: { 
 3594:   int i,imax,j,k; 
 3595:   double big,dum,sum,temp; 
 3596:   double *vv; 
 3597:  
 3598:   vv=vector(1,n); 
 3599:   *d=1.0; 
 3600:   for (i=1;i<=n;i++) { 
 3601:     big=0.0; 
 3602:     for (j=1;j<=n;j++) 
 3603:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3604:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3605:     vv[i]=1.0/big; 
 3606:   } 
 3607:   for (j=1;j<=n;j++) { 
 3608:     for (i=1;i<j;i++) { 
 3609:       sum=a[i][j]; 
 3610:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3611:       a[i][j]=sum; 
 3612:     } 
 3613:     big=0.0; 
 3614:     for (i=j;i<=n;i++) { 
 3615:       sum=a[i][j]; 
 3616:       for (k=1;k<j;k++) 
 3617: 	sum -= a[i][k]*a[k][j]; 
 3618:       a[i][j]=sum; 
 3619:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3620: 	big=dum; 
 3621: 	imax=i; 
 3622:       } 
 3623:     } 
 3624:     if (j != imax) { 
 3625:       for (k=1;k<=n;k++) { 
 3626: 	dum=a[imax][k]; 
 3627: 	a[imax][k]=a[j][k]; 
 3628: 	a[j][k]=dum; 
 3629:       } 
 3630:       *d = -(*d); 
 3631:       vv[imax]=vv[j]; 
 3632:     } 
 3633:     indx[j]=imax; 
 3634:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3635:     if (j != n) { 
 3636:       dum=1.0/(a[j][j]); 
 3637:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3638:     } 
 3639:   } 
 3640:   free_vector(vv,1,n);  /* Doesn't work */
 3641: ;
 3642: } 
 3643: 
 3644: void lubksb(double **a, int n, int *indx, double b[]) 
 3645: { 
 3646:   int i,ii=0,ip,j; 
 3647:   double sum; 
 3648:  
 3649:   for (i=1;i<=n;i++) { 
 3650:     ip=indx[i]; 
 3651:     sum=b[ip]; 
 3652:     b[ip]=b[i]; 
 3653:     if (ii) 
 3654:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3655:     else if (sum) ii=i; 
 3656:     b[i]=sum; 
 3657:   } 
 3658:   for (i=n;i>=1;i--) { 
 3659:     sum=b[i]; 
 3660:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3661:     b[i]=sum/a[i][i]; 
 3662:   } 
 3663: } 
 3664: 
 3665: void pstamp(FILE *fichier)
 3666: {
 3667:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3668: }
 3669: 
 3670: /************ Frequencies ********************/
 3671: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 3672: 		  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
 3673: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 3674: {  /* Some frequencies */
 3675:   
 3676:   int i, m, jk, j1, bool, z1,j;
 3677:   int mi; /* Effective wave */
 3678:   int first;
 3679:   double ***freq; /* Frequencies */
 3680:   double *pp, **prop;
 3681:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 3682:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 3683:   double agebegin, ageend;
 3684:     
 3685:   pp=vector(1,nlstate);
 3686:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 3687:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 3688:   strcpy(fileresp,"P_");
 3689:   strcat(fileresp,fileresu);
 3690:   /*strcat(fileresphtm,fileresu);*/
 3691:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 3692:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 3693:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 3694:     exit(0);
 3695:   }
 3696: 
 3697:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 3698:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 3699:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3700:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3701:     fflush(ficlog);
 3702:     exit(70); 
 3703:   }
 3704:   else{
 3705:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3706: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3707: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3708: 	  fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3709:   }
 3710:     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);
 3711:     
 3712:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 3713:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 3714:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3715:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3716:     fflush(ficlog);
 3717:     exit(70); 
 3718:   }
 3719:   else{
 3720:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3721: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3722: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3723: 	  fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3724:   }
 3725:   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);
 3726: 
 3727:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 3728:   j1=0;
 3729:   
 3730:   j=cptcoveff;
 3731:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3732: 
 3733:   first=1;
 3734: 
 3735:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
 3736:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 3737: 	scanf("%d", i);*/
 3738:       for (i=-5; i<=nlstate+ndeath; i++)  
 3739: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 3740: 	  for(m=iagemin; m <= iagemax+3; m++)
 3741: 	    freq[i][jk][m]=0;
 3742:       
 3743:       for (i=1; i<=nlstate; i++)  
 3744: 	for(m=iagemin; m <= iagemax+3; m++)
 3745: 	  prop[i][m]=0;
 3746:       
 3747:       dateintsum=0;
 3748:       k2cpt=0;
 3749:       for (i=1; i<=imx; i++) { /* For each individual i */
 3750: 	bool=1;
 3751: 	if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3752: 	  for (z1=1; z1<=cptcoveff; z1++)       
 3753:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 3754:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 3755:               bool=0;
 3756:               /* 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", 
 3757:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 3758:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 3759:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 3760:             } 
 3761: 	} /* cptcovn > 0 */
 3762: 
 3763: 	if (bool==1){
 3764: 	  /* for(m=firstpass; m<=lastpass; m++){ */
 3765: 	  for(mi=1; mi<wav[i];mi++){
 3766: 	    m=mw[mi][i];
 3767: 	    /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
 3768: 	       and mw[mi+1][i]. dh depends on stepm. */
 3769: 	    agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 3770: 	    ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
 3771: 	    if(m >=firstpass && m <=lastpass){
 3772: 	      k2=anint[m][i]+(mint[m][i]/12.);
 3773: 	      /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 3774: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 3775: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 3776: 	      if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
 3777: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
 3778: 	      if (m<lastpass) {
 3779: 		/* if(s[m][i]==4 && s[m+1][i]==4) */
 3780: 		/*   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
 3781: 		if(s[m][i]==-1)
 3782: 		  printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
 3783: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
 3784: 		/* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
 3785: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
 3786: 	      }
 3787: 	    }  
 3788: 	    if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
 3789: 	      dateintsum=dateintsum+k2;
 3790: 	      k2cpt++;
 3791: 	      /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 3792: 	    }
 3793: 	    /*}*/
 3794: 	  } /* end m */
 3795: 	} /* end bool */
 3796:       } /* end i = 1 to imx */
 3797:        
 3798:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 3799:       pstamp(ficresp);
 3800:       if  (cptcovn>0) {
 3801: 	fprintf(ficresp, "\n#********** Variable "); 
 3802: 	fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 3803: 	fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 3804: 	for (z1=1; z1<=cptcoveff; z1++){
 3805: 	  fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3806: 	  fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3807: 	  fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3808: 	}
 3809: 	  fprintf(ficresp, "**********\n#");
 3810: 	fprintf(ficresphtm, "**********</h3>\n");
 3811: 	fprintf(ficresphtmfr, "**********</h3>\n");
 3812: 	fprintf(ficlog, "\n#********** Variable "); 
 3813: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3814: 	fprintf(ficlog, "**********\n");
 3815:       }
 3816:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 3817:       for(i=1; i<=nlstate;i++) {
 3818: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 3819: 	fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 3820:       }
 3821:       fprintf(ficresp, "\n");
 3822:       fprintf(ficresphtm, "\n");
 3823:       
 3824:       /* Header of frequency table by age */
 3825:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 3826:       fprintf(ficresphtmfr,"<th>Age</th> ");
 3827:       for(jk=-1; jk <=nlstate+ndeath; jk++){
 3828: 	for(m=-1; m <=nlstate+ndeath; m++){
 3829: 	  if(jk!=0 && m!=0)
 3830: 	    fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 3831: 	}
 3832:       }
 3833:       fprintf(ficresphtmfr, "\n");
 3834:       
 3835:       /* For each age */
 3836:       for(i=iagemin; i <= iagemax+3; i++){
 3837: 	fprintf(ficresphtm,"<tr>");
 3838: 	if(i==iagemax+1){
 3839: 	  fprintf(ficlog,"1");
 3840: 	  fprintf(ficresphtmfr,"<tr><th>0</th> ");
 3841: 	}else if(i==iagemax+2){
 3842: 	  fprintf(ficlog,"0");
 3843: 	  fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 3844: 	}else if(i==iagemax+3){
 3845: 	  fprintf(ficlog,"Total");
 3846: 	  fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 3847: 	}else{
 3848: 	  if(first==1){
 3849: 	    first=0;
 3850: 	    printf("See log file for details...\n");
 3851: 	  }
 3852: 	  fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
 3853: 	  fprintf(ficlog,"Age %d", i);
 3854: 	}
 3855: 	for(jk=1; jk <=nlstate ; jk++){
 3856: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 3857: 	    pp[jk] += freq[jk][m][i]; 
 3858: 	}
 3859: 	for(jk=1; jk <=nlstate ; jk++){
 3860: 	  for(m=-1, pos=0; m <=0 ; m++)
 3861: 	    pos += freq[jk][m][i];
 3862: 	  if(pp[jk]>=1.e-10){
 3863: 	    if(first==1){
 3864: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3865: 	    }
 3866: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3867: 	  }else{
 3868: 	    if(first==1)
 3869: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3870: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3871: 	  }
 3872: 	}
 3873: 
 3874: 	for(jk=1; jk <=nlstate ; jk++){
 3875: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 3876: 	    pp[jk] += freq[jk][m][i];
 3877: 	}	
 3878: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 3879: 	  pos += pp[jk];
 3880: 	  posprop += prop[jk][i];
 3881: 	}
 3882: 	for(jk=1; jk <=nlstate ; jk++){
 3883: 	  if(pos>=1.e-5){
 3884: 	    if(first==1)
 3885: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3886: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3887: 	  }else{
 3888: 	    if(first==1)
 3889: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3890: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3891: 	  }
 3892: 	  if( i <= iagemax){
 3893: 	    if(pos>=1.e-5){
 3894: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3895: 	      fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3896: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 3897: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 3898: 	    }
 3899: 	    else{
 3900: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 3901: 	      fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
 3902: 	    }
 3903: 	  }
 3904: 	}
 3905: 	
 3906: 	for(jk=-1; jk <=nlstate+ndeath; jk++){
 3907: 	  for(m=-1; m <=nlstate+ndeath; m++){
 3908: 	    if(freq[jk][m][i] !=0 ) { /* minimizing output */
 3909: 	      if(first==1){
 3910: 		printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 3911: 	      }
 3912: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 3913: 	    }
 3914: 	    if(jk!=0 && m!=0)
 3915: 	      fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
 3916: 	  }
 3917: 	}
 3918: 	fprintf(ficresphtmfr,"</tr>\n ");
 3919: 	if(i <= iagemax){
 3920: 	  fprintf(ficresp,"\n");
 3921: 	  fprintf(ficresphtm,"</tr>\n");
 3922: 	}
 3923: 	if(first==1)
 3924: 	  printf("Others in log...\n");
 3925: 	fprintf(ficlog,"\n");
 3926:       } /* end loop i */
 3927:       fprintf(ficresphtm,"</table>\n");
 3928:       fprintf(ficresphtmfr,"</table>\n");
 3929:       /*}*/
 3930:   } /* end j1 */
 3931:   dateintmean=dateintsum/k2cpt; 
 3932:  
 3933:   fclose(ficresp);
 3934:   fclose(ficresphtm);
 3935:   fclose(ficresphtmfr);
 3936:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 3937:   free_vector(pp,1,nlstate);
 3938:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 3939:   /* End of Freq */
 3940: }
 3941: 
 3942: /************ Prevalence ********************/
 3943: 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)
 3944: {  
 3945:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3946:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3947:      We still use firstpass and lastpass as another selection.
 3948:   */
 3949:  
 3950:   int i, m, jk, j1, bool, z1,j;
 3951:   int mi; /* Effective wave */
 3952:   int iage;
 3953:   double agebegin, ageend;
 3954: 
 3955:   double **prop;
 3956:   double posprop; 
 3957:   double  y2; /* in fractional years */
 3958:   int iagemin, iagemax;
 3959:   int first; /** to stop verbosity which is redirected to log file */
 3960: 
 3961:   iagemin= (int) agemin;
 3962:   iagemax= (int) agemax;
 3963:   /*pp=vector(1,nlstate);*/
 3964:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 3965:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3966:   j1=0;
 3967:   
 3968:   /*j=cptcoveff;*/
 3969:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3970:   
 3971:   first=1;
 3972:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3973:     for (i=1; i<=nlstate; i++)  
 3974:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 3975: 				prop[i][iage]=0.0;
 3976:     
 3977:     for (i=1; i<=imx; i++) { /* Each individual */
 3978:       bool=1;
 3979:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3980: 				for (z1=1; z1<=cptcoveff; z1++) 
 3981: 					if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
 3982: 						bool=0;
 3983:       } 
 3984:       if (bool==1) { 
 3985: 				/* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 3986: 				for(mi=1; mi<wav[i];mi++){
 3987: 					m=mw[mi][i];
 3988: 					agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 3989: 					/* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 3990: 					if(m >=firstpass && m <=lastpass){
 3991: 						y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3992: 						if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3993: 							if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3994: 							if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3995: 							if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 3996: 								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); 
 3997: 								exit(1);
 3998: 							}
 3999: 							if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4000: 								/*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]]);*/
 4001: 								prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4002: 								prop[s[m][i]][iagemax+3] += weight[i]; 
 4003: 							} /* end valid statuses */ 
 4004: 						} /* end selection of dates */
 4005: 					} /* end selection of waves */
 4006: 				} /* end effective waves */
 4007:       } /* end bool */
 4008:     }
 4009:     for(i=iagemin; i <= iagemax+3; i++){  
 4010:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4011: 				posprop += prop[jk][i]; 
 4012:       } 
 4013:       
 4014:       for(jk=1; jk <=nlstate ; jk++){	    
 4015: 				if( i <=  iagemax){ 
 4016: 					if(posprop>=1.e-5){ 
 4017: 						probs[i][jk][j1]= prop[jk][i]/posprop;
 4018: 					} else{
 4019: 						if(first==1){
 4020: 							first=0;
 4021: 							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]);
 4022: 						}
 4023: 					}
 4024: 				} 
 4025:       }/* end jk */ 
 4026:     }/* end i */ 
 4027:     /*} *//* end i1 */
 4028:   } /* end j1 */
 4029:   
 4030:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4031:   /*free_vector(pp,1,nlstate);*/
 4032:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4033: }  /* End of prevalence */
 4034: 
 4035: /************* Waves Concatenation ***************/
 4036: 
 4037: 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)
 4038: {
 4039:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4040:      Death is a valid wave (if date is known).
 4041:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4042:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4043:      and mw[mi+1][i]. dh depends on stepm.
 4044:      */
 4045: 
 4046:   int i, mi, m;
 4047:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4048:      double sum=0., jmean=0.;*/
 4049:   int first, firstwo, firsthree, firstfour;
 4050:   int j, k=0,jk, ju, jl;
 4051:   double sum=0.;
 4052:   first=0;
 4053:   firstwo=0;
 4054:   firsthree=0;
 4055:   firstfour=0;
 4056:   jmin=100000;
 4057:   jmax=-1;
 4058:   jmean=0.;
 4059:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4060:     mi=0;
 4061:     m=firstpass;
 4062:     while(s[m][i] <= nlstate){  /* a live state */
 4063:       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 */
 4064: 	mw[++mi][i]=m;
 4065:       }
 4066:       if(m >=lastpass){
 4067: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4068: 	  if(firsthree == 0){
 4069: 	    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);
 4070: 	    firsthree=1;
 4071: 	  }
 4072: 	  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);
 4073: 	  mw[++mi][i]=m;
 4074: 	}
 4075: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 4076: 	  nbwarn++;
 4077: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4078: 	    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);
 4079: 	    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);
 4080: 	  }
 4081: 	  break;
 4082: 	}
 4083: 	break;
 4084:       }
 4085:       else
 4086: 	m++;
 4087:     }/* end while */
 4088:     
 4089:     /* After last pass */
 4090:     if (s[m][i] > nlstate){  /* In a death state */
 4091:       mi++;	/* Death is another wave */
 4092:       /* if(mi==0)  never been interviewed correctly before death */
 4093: 	 /* Only death is a correct wave */
 4094:       mw[mi][i]=m;
 4095:     }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 */
 4096:       /* m++; */
 4097:       /* mi++; */
 4098:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4099:       /* mw[mi][i]=m; */
 4100:       nberr++;
 4101:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4102: 	if(firstwo==0){
 4103: 	  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 );
 4104: 	  firstwo=1;
 4105: 	}
 4106: 	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 );
 4107:       }else{ /* end date of interview is known */
 4108: 	/* death is known but not confirmed by death status at any wave */
 4109: 	if(firstfour==0){
 4110: 	  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 );
 4111: 	  firstfour=1;
 4112: 	}
 4113: 	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 );
 4114:       }
 4115:     }
 4116:     wav[i]=mi;
 4117:     if(mi==0){
 4118:       nbwarn++;
 4119:       if(first==0){
 4120: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4121: 	first=1;
 4122:       }
 4123:       if(first==1){
 4124: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4125:       }
 4126:     } /* end mi==0 */
 4127:   } /* End individuals */
 4128:   /* wav and mw are no more changed */
 4129: 
 4130:   
 4131:   for(i=1; i<=imx; i++){
 4132:     for(mi=1; mi<wav[i];mi++){
 4133:       if (stepm <=0)
 4134: 	dh[mi][i]=1;
 4135:       else{
 4136: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4137: 	  if (agedc[i] < 2*AGESUP) {
 4138: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4139: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4140: 	    else if(j<0){
 4141: 	      nberr++;
 4142: 	      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]);
 4143: 	      j=1; /* Temporary Dangerous patch */
 4144: 	      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);
 4145: 	      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]);
 4146: 	      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);
 4147: 	    }
 4148: 	    k=k+1;
 4149: 	    if (j >= jmax){
 4150: 	      jmax=j;
 4151: 	      ijmax=i;
 4152: 	    }
 4153: 	    if (j <= jmin){
 4154: 	      jmin=j;
 4155: 	      ijmin=i;
 4156: 	    }
 4157: 	    sum=sum+j;
 4158: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4159: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4160: 	  }
 4161: 	}
 4162: 	else{
 4163: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4164: /* 	  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]); */
 4165: 
 4166: 	  k=k+1;
 4167: 	  if (j >= jmax) {
 4168: 	    jmax=j;
 4169: 	    ijmax=i;
 4170: 	  }
 4171: 	  else if (j <= jmin){
 4172: 	    jmin=j;
 4173: 	    ijmin=i;
 4174: 	  }
 4175: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4176: 	  /*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]);*/
 4177: 	  if(j<0){
 4178: 	    nberr++;
 4179: 	    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]);
 4180: 	    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]);
 4181: 	  }
 4182: 	  sum=sum+j;
 4183: 	}
 4184: 	jk= j/stepm;
 4185: 	jl= j -jk*stepm;
 4186: 	ju= j -(jk+1)*stepm;
 4187: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4188: 	  if(jl==0){
 4189: 	    dh[mi][i]=jk;
 4190: 	    bh[mi][i]=0;
 4191: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4192: 		  * to avoid the price of an extra matrix product in likelihood */
 4193: 	    dh[mi][i]=jk+1;
 4194: 	    bh[mi][i]=ju;
 4195: 	  }
 4196: 	}else{
 4197: 	  if(jl <= -ju){
 4198: 	    dh[mi][i]=jk;
 4199: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4200: 				 * is higher than the multiple of stepm and negative otherwise.
 4201: 				 */
 4202: 	  }
 4203: 	  else{
 4204: 	    dh[mi][i]=jk+1;
 4205: 	    bh[mi][i]=ju;
 4206: 	  }
 4207: 	  if(dh[mi][i]==0){
 4208: 	    dh[mi][i]=1; /* At least one step */
 4209: 	    bh[mi][i]=ju; /* At least one step */
 4210: 	    /*  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);*/
 4211: 	  }
 4212: 	} /* end if mle */
 4213:       }
 4214:     } /* end wave */
 4215:   }
 4216:   jmean=sum/k;
 4217:   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);
 4218:   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);
 4219:  }
 4220: 
 4221: /*********** Tricode ****************************/
 4222: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 4223: {
 4224:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4225:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4226:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4227:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 4228:    * nbcode[Tvar[j]][1]= 
 4229:   */
 4230: 
 4231:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4232:   int modmaxcovj=0; /* Modality max of covariates j */
 4233:   int cptcode=0; /* Modality max of covariates j */
 4234:   int modmincovj=0; /* Modality min of covariates j */
 4235: 
 4236: 
 4237:   cptcoveff=0; 
 4238:  
 4239:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4240: 
 4241:   /* Loop on covariates without age and products */
 4242:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 4243:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 4244:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 4245: 			       modality of this covariate Vj*/ 
 4246:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4247: 				    * If product of Vn*Vm, still boolean *:
 4248: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4249: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4250:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4251: 				      modality of the nth covariate of individual i. */
 4252:       if (ij > modmaxcovj)
 4253:         modmaxcovj=ij; 
 4254:       else if (ij < modmincovj) 
 4255: 	modmincovj=ij; 
 4256:       if ((ij < -1) && (ij > NCOVMAX)){
 4257: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4258: 	exit(1);
 4259:       }else
 4260:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4261:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4262:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4263:       /* getting the maximum value of the modality of the covariate
 4264: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4265: 	 female is 1, then modmaxcovj=1.*/
 4266:     } /* end for loop on individuals i */
 4267:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4268:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4269:     cptcode=modmaxcovj;
 4270:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4271:    /*for (i=0; i<=cptcode; i++) {*/
 4272:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 4273:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4274:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4275:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 4276: 	if( k != -1){
 4277: 	  ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 4278: 			     covariate for which somebody answered excluding 
 4279: 			     undefined. Usually 2: 0 and 1. */
 4280: 	}
 4281: 	ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 4282: 			     covariate for which somebody answered including 
 4283: 			     undefined. Usually 3: -1, 0 and 1. */
 4284:       }
 4285:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 4286: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4287:     } /* Ndum[-1] number of undefined modalities */
 4288: 
 4289:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4290:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 4291:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 4292:        modmincovj=3; modmaxcovj = 7;
 4293:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 4294:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 4295:        defining two dummy variables: variables V1_1 and V1_2.
 4296:        nbcode[Tvar[j]][ij]=k;
 4297:        nbcode[Tvar[j]][1]=0;
 4298:        nbcode[Tvar[j]][2]=1;
 4299:        nbcode[Tvar[j]][3]=2;
 4300:        To be continued (not working yet).
 4301:     */
 4302:     ij=0; /* ij is similar to i but can jump over null modalities */
 4303:     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*/
 4304:     	if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4305: 	  break;
 4306: 	}
 4307: 	ij++;
 4308: 	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.*/
 4309: 	cptcode = ij; /* New max modality for covar j */
 4310:     } /* end of loop on modality i=-1 to 1 or more */
 4311:       
 4312:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4313:     /* 	/\*recode from 0 *\/ */
 4314:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4315:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4316:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4317:     /* 	} */
 4318:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4319:     /* 	if (ij > ncodemax[j]) { */
 4320:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4321:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4322:     /* 	  break; */
 4323:     /* 	} */
 4324:     /*   }  /\* end of loop on modality k *\/ */
 4325:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4326:   
 4327:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4328:   
 4329:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4330:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4331:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 4332:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 4333:  } 
 4334: 
 4335:  ij=0;
 4336:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4337:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4338:    if((Ndum[i]!=0) && (i<=ncovcol)){
 4339:      ij++;
 4340:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4341:      Tvaraff[ij]=i; /*For printing (unclear) */
 4342:    }else{
 4343:        /* Tvaraff[ij]=0; */
 4344:    }
 4345:  }
 4346:  /* ij--; */
 4347:  cptcoveff=ij; /*Number of total covariates*/
 4348: 
 4349: }
 4350: 
 4351: 
 4352: /*********** Health Expectancies ****************/
 4353: 
 4354: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 4355: 
 4356: {
 4357:   /* Health expectancies, no variances */
 4358:   int i, j, nhstepm, hstepm, h, nstepm;
 4359:   int nhstepma, nstepma; /* Decreasing with age */
 4360:   double age, agelim, hf;
 4361:   double ***p3mat;
 4362:   double eip;
 4363: 
 4364:   pstamp(ficreseij);
 4365:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4366:   fprintf(ficreseij,"# Age");
 4367:   for(i=1; i<=nlstate;i++){
 4368:     for(j=1; j<=nlstate;j++){
 4369:       fprintf(ficreseij," e%1d%1d ",i,j);
 4370:     }
 4371:     fprintf(ficreseij," e%1d. ",i);
 4372:   }
 4373:   fprintf(ficreseij,"\n");
 4374: 
 4375:   
 4376:   if(estepm < stepm){
 4377:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4378:   }
 4379:   else  hstepm=estepm;   
 4380:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4381:    * This is mainly to measure the difference between two models: for example
 4382:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4383:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4384:    * progression in between and thus overestimating or underestimating according
 4385:    * to the curvature of the survival function. If, for the same date, we 
 4386:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4387:    * to compare the new estimate of Life expectancy with the same linear 
 4388:    * hypothesis. A more precise result, taking into account a more precise
 4389:    * curvature will be obtained if estepm is as small as stepm. */
 4390: 
 4391:   /* For example we decided to compute the life expectancy with the smallest unit */
 4392:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4393:      nhstepm is the number of hstepm from age to agelim 
 4394:      nstepm is the number of stepm from age to agelin. 
 4395:      Look at hpijx to understand the reason of that which relies in memory size
 4396:      and note for a fixed period like estepm months */
 4397:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4398:      survival function given by stepm (the optimization length). Unfortunately it
 4399:      means that if the survival funtion is printed only each two years of age and if
 4400:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4401:      results. So we changed our mind and took the option of the best precision.
 4402:   */
 4403:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4404: 
 4405:   agelim=AGESUP;
 4406:   /* If stepm=6 months */
 4407:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 4408:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 4409:     
 4410: /* nhstepm age range expressed in number of stepm */
 4411:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4412:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4413:   /* if (stepm >= YEARM) hstepm=1;*/
 4414:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4415:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4416: 
 4417:   for (age=bage; age<=fage; age ++){ 
 4418:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4419:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4420:     /* if (stepm >= YEARM) hstepm=1;*/
 4421:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4422: 
 4423:     /* If stepm=6 months */
 4424:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4425:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4426:     
 4427:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4428:     
 4429:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4430:     
 4431:     printf("%d|",(int)age);fflush(stdout);
 4432:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4433:     
 4434:     /* Computing expectancies */
 4435:     for(i=1; i<=nlstate;i++)
 4436:       for(j=1; j<=nlstate;j++)
 4437: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4438: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 4439: 	  
 4440: 	  /* 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]);*/
 4441: 
 4442: 	}
 4443: 
 4444:     fprintf(ficreseij,"%3.0f",age );
 4445:     for(i=1; i<=nlstate;i++){
 4446:       eip=0;
 4447:       for(j=1; j<=nlstate;j++){
 4448: 	eip +=eij[i][j][(int)age];
 4449: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 4450:       }
 4451:       fprintf(ficreseij,"%9.4f", eip );
 4452:     }
 4453:     fprintf(ficreseij,"\n");
 4454:     
 4455:   }
 4456:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4457:   printf("\n");
 4458:   fprintf(ficlog,"\n");
 4459:   
 4460: }
 4461: 
 4462: 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[] )
 4463: 
 4464: {
 4465:   /* Covariances of health expectancies eij and of total life expectancies according
 4466:    to initial status i, ei. .
 4467:   */
 4468:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 4469:   int nhstepma, nstepma; /* Decreasing with age */
 4470:   double age, agelim, hf;
 4471:   double ***p3matp, ***p3matm, ***varhe;
 4472:   double **dnewm,**doldm;
 4473:   double *xp, *xm;
 4474:   double **gp, **gm;
 4475:   double ***gradg, ***trgradg;
 4476:   int theta;
 4477: 
 4478:   double eip, vip;
 4479: 
 4480:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 4481:   xp=vector(1,npar);
 4482:   xm=vector(1,npar);
 4483:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 4484:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 4485:   
 4486:   pstamp(ficresstdeij);
 4487:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 4488:   fprintf(ficresstdeij,"# Age");
 4489:   for(i=1; i<=nlstate;i++){
 4490:     for(j=1; j<=nlstate;j++)
 4491:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 4492:     fprintf(ficresstdeij," e%1d. ",i);
 4493:   }
 4494:   fprintf(ficresstdeij,"\n");
 4495: 
 4496:   pstamp(ficrescveij);
 4497:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 4498:   fprintf(ficrescveij,"# Age");
 4499:   for(i=1; i<=nlstate;i++)
 4500:     for(j=1; j<=nlstate;j++){
 4501:       cptj= (j-1)*nlstate+i;
 4502:       for(i2=1; i2<=nlstate;i2++)
 4503: 	for(j2=1; j2<=nlstate;j2++){
 4504: 	  cptj2= (j2-1)*nlstate+i2;
 4505: 	  if(cptj2 <= cptj)
 4506: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 4507: 	}
 4508:     }
 4509:   fprintf(ficrescveij,"\n");
 4510:   
 4511:   if(estepm < stepm){
 4512:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4513:   }
 4514:   else  hstepm=estepm;   
 4515:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4516:    * This is mainly to measure the difference between two models: for example
 4517:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4518:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4519:    * progression in between and thus overestimating or underestimating according
 4520:    * to the curvature of the survival function. If, for the same date, we 
 4521:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4522:    * to compare the new estimate of Life expectancy with the same linear 
 4523:    * hypothesis. A more precise result, taking into account a more precise
 4524:    * curvature will be obtained if estepm is as small as stepm. */
 4525: 
 4526:   /* For example we decided to compute the life expectancy with the smallest unit */
 4527:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4528:      nhstepm is the number of hstepm from age to agelim 
 4529:      nstepm is the number of stepm from age to agelin. 
 4530:      Look at hpijx to understand the reason of that which relies in memory size
 4531:      and note for a fixed period like estepm months */
 4532:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4533:      survival function given by stepm (the optimization length). Unfortunately it
 4534:      means that if the survival funtion is printed only each two years of age and if
 4535:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4536:      results. So we changed our mind and took the option of the best precision.
 4537:   */
 4538:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4539: 
 4540:   /* If stepm=6 months */
 4541:   /* nhstepm age range expressed in number of stepm */
 4542:   agelim=AGESUP;
 4543:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 4544:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4545:   /* if (stepm >= YEARM) hstepm=1;*/
 4546:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4547:   
 4548:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4549:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4550:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 4551:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 4552:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 4553:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 4554: 
 4555:   for (age=bage; age<=fage; age ++){ 
 4556:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4557:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4558:     /* if (stepm >= YEARM) hstepm=1;*/
 4559:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4560: 		
 4561:     /* If stepm=6 months */
 4562:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4563:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4564:     
 4565:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4566: 		
 4567:     /* Computing  Variances of health expectancies */
 4568:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 4569:        decrease memory allocation */
 4570:     for(theta=1; theta <=npar; theta++){
 4571:       for(i=1; i<=npar; i++){ 
 4572: 				xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4573: 				xm[i] = x[i] - (i==theta ?delti[theta]:0);
 4574:       }
 4575:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 4576:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 4577: 			
 4578:       for(j=1; j<= nlstate; j++){
 4579: 				for(i=1; i<=nlstate; i++){
 4580: 					for(h=0; h<=nhstepm-1; h++){
 4581: 						gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 4582: 						gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 4583: 					}
 4584: 				}
 4585:       }
 4586: 			
 4587:       for(ij=1; ij<= nlstate*nlstate; ij++)
 4588: 				for(h=0; h<=nhstepm-1; h++){
 4589: 					gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 4590: 				}
 4591:     }/* End theta */
 4592:     
 4593:     
 4594:     for(h=0; h<=nhstepm-1; h++)
 4595:       for(j=1; j<=nlstate*nlstate;j++)
 4596: 				for(theta=1; theta <=npar; theta++)
 4597: 					trgradg[h][j][theta]=gradg[h][theta][j];
 4598:     
 4599: 		
 4600: 		for(ij=1;ij<=nlstate*nlstate;ij++)
 4601:       for(ji=1;ji<=nlstate*nlstate;ji++)
 4602: 				varhe[ij][ji][(int)age] =0.;
 4603: 		
 4604: 		printf("%d|",(int)age);fflush(stdout);
 4605: 		fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4606: 		for(h=0;h<=nhstepm-1;h++){
 4607:       for(k=0;k<=nhstepm-1;k++){
 4608: 				matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 4609: 				matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 4610: 				for(ij=1;ij<=nlstate*nlstate;ij++)
 4611: 					for(ji=1;ji<=nlstate*nlstate;ji++)
 4612: 						varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 4613:       }
 4614:     }
 4615: 		
 4616:     /* Computing expectancies */
 4617:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4618:     for(i=1; i<=nlstate;i++)
 4619:       for(j=1; j<=nlstate;j++)
 4620: 				for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4621: 					eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 4622: 					
 4623: 					/* 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]);*/
 4624: 					
 4625: 				}
 4626: 		
 4627:     fprintf(ficresstdeij,"%3.0f",age );
 4628:     for(i=1; i<=nlstate;i++){
 4629:       eip=0.;
 4630:       vip=0.;
 4631:       for(j=1; j<=nlstate;j++){
 4632: 				eip += eij[i][j][(int)age];
 4633: 				for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 4634: 					vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 4635: 				fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 4636:       }
 4637:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 4638:     }
 4639:     fprintf(ficresstdeij,"\n");
 4640: 		
 4641:     fprintf(ficrescveij,"%3.0f",age );
 4642:     for(i=1; i<=nlstate;i++)
 4643:       for(j=1; j<=nlstate;j++){
 4644: 				cptj= (j-1)*nlstate+i;
 4645: 				for(i2=1; i2<=nlstate;i2++)
 4646: 					for(j2=1; j2<=nlstate;j2++){
 4647: 						cptj2= (j2-1)*nlstate+i2;
 4648: 						if(cptj2 <= cptj)
 4649: 							fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 4650: 					}
 4651:       }
 4652:     fprintf(ficrescveij,"\n");
 4653: 		
 4654:   }
 4655:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 4656:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 4657:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 4658:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 4659:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4660:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4661:   printf("\n");
 4662:   fprintf(ficlog,"\n");
 4663: 	
 4664:   free_vector(xm,1,npar);
 4665:   free_vector(xp,1,npar);
 4666:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 4667:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 4668:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 4669: }
 4670:  
 4671: /************ Variance ******************/
 4672:  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[])
 4673:  {
 4674:    /* Variance of health expectancies */
 4675:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 4676:    /* double **newm;*/
 4677:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 4678:   
 4679:    /* int movingaverage(); */
 4680:    double **dnewm,**doldm;
 4681:    double **dnewmp,**doldmp;
 4682:    int i, j, nhstepm, hstepm, h, nstepm ;
 4683:    int k;
 4684:    double *xp;
 4685:    double **gp, **gm;  /* for var eij */
 4686:    double ***gradg, ***trgradg; /*for var eij */
 4687:    double **gradgp, **trgradgp; /* for var p point j */
 4688:    double *gpp, *gmp; /* for var p point j */
 4689:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 4690:    double ***p3mat;
 4691:    double age,agelim, hf;
 4692:    /* double ***mobaverage; */
 4693:    int theta;
 4694:    char digit[4];
 4695:    char digitp[25];
 4696: 
 4697:    char fileresprobmorprev[FILENAMELENGTH];
 4698: 
 4699:    if(popbased==1){
 4700:      if(mobilav!=0)
 4701:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 4702:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 4703:    }
 4704:    else 
 4705:      strcpy(digitp,"-STABLBASED_");
 4706: 
 4707:    /* if (mobilav!=0) { */
 4708:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 4709:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 4710:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 4711:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 4712:    /*   } */
 4713:    /* } */
 4714: 
 4715:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 4716:    sprintf(digit,"%-d",ij);
 4717:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 4718:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 4719:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 4720:    strcat(fileresprobmorprev,fileresu);
 4721:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 4722:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 4723:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 4724:    }
 4725:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4726:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4727:    pstamp(ficresprobmorprev);
 4728:    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);
 4729:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 4730:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4731:      fprintf(ficresprobmorprev," p.%-d SE",j);
 4732:      for(i=1; i<=nlstate;i++)
 4733:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 4734:    }  
 4735:    fprintf(ficresprobmorprev,"\n");
 4736:   
 4737:    fprintf(ficgp,"\n# Routine varevsij");
 4738:    fprintf(ficgp,"\nunset title \n");
 4739:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 4740:    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");
 4741:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 4742:    /*   } */
 4743:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4744:    pstamp(ficresvij);
 4745:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 4746:    if(popbased==1)
 4747:      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);
 4748:    else
 4749:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 4750:    fprintf(ficresvij,"# Age");
 4751:    for(i=1; i<=nlstate;i++)
 4752:      for(j=1; j<=nlstate;j++)
 4753:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 4754:    fprintf(ficresvij,"\n");
 4755: 
 4756:    xp=vector(1,npar);
 4757:    dnewm=matrix(1,nlstate,1,npar);
 4758:    doldm=matrix(1,nlstate,1,nlstate);
 4759:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 4760:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4761: 
 4762:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 4763:    gpp=vector(nlstate+1,nlstate+ndeath);
 4764:    gmp=vector(nlstate+1,nlstate+ndeath);
 4765:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4766:   
 4767:    if(estepm < stepm){
 4768:      printf ("Problem %d lower than %d\n",estepm, stepm);
 4769:    }
 4770:    else  hstepm=estepm;   
 4771:    /* For example we decided to compute the life expectancy with the smallest unit */
 4772:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4773:       nhstepm is the number of hstepm from age to agelim 
 4774:       nstepm is the number of stepm from age to agelim. 
 4775:       Look at function hpijx to understand why because of memory size limitations, 
 4776:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 4777:       survival function given by stepm (the optimization length). Unfortunately it
 4778:       means that if the survival funtion is printed every two years of age and if
 4779:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4780:       results. So we changed our mind and took the option of the best precision.
 4781:    */
 4782:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4783:    agelim = AGESUP;
 4784:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4785:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4786:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4787:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4788:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 4789:      gp=matrix(0,nhstepm,1,nlstate);
 4790:      gm=matrix(0,nhstepm,1,nlstate);
 4791: 		
 4792: 		
 4793:      for(theta=1; theta <=npar; theta++){
 4794:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 4795: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4796:        }
 4797: 			
 4798:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4799: 			
 4800:        if (popbased==1) {
 4801: 	 if(mobilav ==0){
 4802: 	   for(i=1; i<=nlstate;i++)
 4803: 	     prlim[i][i]=probs[(int)age][i][ij];
 4804: 	 }else{ /* mobilav */ 
 4805: 	   for(i=1; i<=nlstate;i++)
 4806: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 4807: 	 }
 4808:        }
 4809: 			
 4810:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 4811:        for(j=1; j<= nlstate; j++){
 4812: 	 for(h=0; h<=nhstepm; h++){
 4813: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 4814: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 4815: 	 }
 4816:        }
 4817:        /* Next for computing probability of death (h=1 means
 4818: 	  computed over hstepm matrices product = hstepm*stepm months) 
 4819: 	  as a weighted average of prlim.
 4820:        */
 4821:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4822: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 4823: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 4824:        }    
 4825:        /* end probability of death */
 4826: 			
 4827:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 4828: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4829: 			
 4830:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 4831: 			
 4832:        if (popbased==1) {
 4833: 	 if(mobilav ==0){
 4834: 	   for(i=1; i<=nlstate;i++)
 4835: 	     prlim[i][i]=probs[(int)age][i][ij];
 4836: 	 }else{ /* mobilav */ 
 4837: 	   for(i=1; i<=nlstate;i++)
 4838: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 4839: 	 }
 4840:        }
 4841: 			
 4842:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 4843: 			
 4844:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 4845: 	 for(h=0; h<=nhstepm; h++){
 4846: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 4847: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 4848: 	 }
 4849:        }
 4850:        /* This for computing probability of death (h=1 means
 4851: 	  computed over hstepm matrices product = hstepm*stepm months) 
 4852: 	  as a weighted average of prlim.
 4853:        */
 4854:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4855: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 4856: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 4857:        }    
 4858:        /* end probability of death */
 4859: 			
 4860:        for(j=1; j<= nlstate; j++) /* vareij */
 4861: 	 for(h=0; h<=nhstepm; h++){
 4862: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 4863: 	 }
 4864: 			
 4865:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 4866: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 4867:        }
 4868: 			
 4869:      } /* End theta */
 4870: 		
 4871:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 4872: 		
 4873:      for(h=0; h<=nhstepm; h++) /* veij */
 4874:        for(j=1; j<=nlstate;j++)
 4875: 	 for(theta=1; theta <=npar; theta++)
 4876: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 4877: 		
 4878:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 4879:        for(theta=1; theta <=npar; theta++)
 4880: 	 trgradgp[j][theta]=gradgp[theta][j];
 4881: 		
 4882: 		
 4883:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4884:      for(i=1;i<=nlstate;i++)
 4885:        for(j=1;j<=nlstate;j++)
 4886: 	 vareij[i][j][(int)age] =0.;
 4887: 		
 4888:      for(h=0;h<=nhstepm;h++){
 4889:        for(k=0;k<=nhstepm;k++){
 4890: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 4891: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 4892: 	 for(i=1;i<=nlstate;i++)
 4893: 	   for(j=1;j<=nlstate;j++)
 4894: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 4895:        }
 4896:      }
 4897: 		
 4898:      /* pptj */
 4899:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 4900:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 4901:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 4902:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 4903: 	 varppt[j][i]=doldmp[j][i];
 4904:      /* end ppptj */
 4905:      /*  x centered again */
 4906: 		
 4907:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 4908: 		
 4909:      if (popbased==1) {
 4910:        if(mobilav ==0){
 4911: 	 for(i=1; i<=nlstate;i++)
 4912: 	   prlim[i][i]=probs[(int)age][i][ij];
 4913:        }else{ /* mobilav */ 
 4914: 	 for(i=1; i<=nlstate;i++)
 4915: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 4916:        }
 4917:      }
 4918: 		
 4919:      /* This for computing probability of death (h=1 means
 4920: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 4921: 	as a weighted average of prlim.
 4922:      */
 4923:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 4924:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4925:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 4926: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 4927:      }    
 4928:      /* end probability of death */
 4929: 		
 4930:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 4931:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4932:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 4933:        for(i=1; i<=nlstate;i++){
 4934: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 4935:        }
 4936:      } 
 4937:      fprintf(ficresprobmorprev,"\n");
 4938: 		
 4939:      fprintf(ficresvij,"%.0f ",age );
 4940:      for(i=1; i<=nlstate;i++)
 4941:        for(j=1; j<=nlstate;j++){
 4942: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 4943:        }
 4944:      fprintf(ficresvij,"\n");
 4945:      free_matrix(gp,0,nhstepm,1,nlstate);
 4946:      free_matrix(gm,0,nhstepm,1,nlstate);
 4947:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 4948:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 4949:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4950:    } /* End age */
 4951:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 4952:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 4953:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 4954:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4955:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 4956:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 4957:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 4958:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 4959:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4960:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 4961:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4962:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4963:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 4964:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 4965:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 4966:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 4967:    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);
 4968:    /*  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);
 4969:     */
 4970:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 4971:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4972: 
 4973:    free_vector(xp,1,npar);
 4974:    free_matrix(doldm,1,nlstate,1,nlstate);
 4975:    free_matrix(dnewm,1,nlstate,1,npar);
 4976:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4977:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 4978:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4979:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 4980:    fclose(ficresprobmorprev);
 4981:    fflush(ficgp);
 4982:    fflush(fichtm); 
 4983:  }  /* end varevsij */
 4984: 
 4985: /************ Variance of prevlim ******************/
 4986:  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[])
 4987: {
 4988:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 4989:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 4990: 
 4991:   double **dnewm,**doldm;
 4992:   int i, j, nhstepm, hstepm;
 4993:   double *xp;
 4994:   double *gp, *gm;
 4995:   double **gradg, **trgradg;
 4996:   double **mgm, **mgp;
 4997:   double age,agelim;
 4998:   int theta;
 4999:   
 5000:   pstamp(ficresvpl);
 5001:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5002:   fprintf(ficresvpl,"# Age");
 5003:   for(i=1; i<=nlstate;i++)
 5004:       fprintf(ficresvpl," %1d-%1d",i,i);
 5005:   fprintf(ficresvpl,"\n");
 5006: 
 5007:   xp=vector(1,npar);
 5008:   dnewm=matrix(1,nlstate,1,npar);
 5009:   doldm=matrix(1,nlstate,1,nlstate);
 5010:   
 5011:   hstepm=1*YEARM; /* Every year of age */
 5012:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5013:   agelim = AGESUP;
 5014:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5015:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5016:     if (stepm >= YEARM) hstepm=1;
 5017:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5018:     gradg=matrix(1,npar,1,nlstate);
 5019:     mgp=matrix(1,npar,1,nlstate);
 5020:     mgm=matrix(1,npar,1,nlstate);
 5021:     gp=vector(1,nlstate);
 5022:     gm=vector(1,nlstate);
 5023: 
 5024:     for(theta=1; theta <=npar; theta++){
 5025:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5026: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5027:       }
 5028:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5029: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5030:       else
 5031: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5032:       for(i=1;i<=nlstate;i++){
 5033: 	gp[i] = prlim[i][i];
 5034: 	mgp[theta][i] = prlim[i][i];
 5035:       }
 5036:       for(i=1; i<=npar; i++) /* Computes gradient */
 5037: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5038:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5039: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5040:       else
 5041: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5042:       for(i=1;i<=nlstate;i++){
 5043: 	gm[i] = prlim[i][i];
 5044: 	mgm[theta][i] = prlim[i][i];
 5045:       }
 5046:       for(i=1;i<=nlstate;i++)
 5047: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5048:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5049:     } /* End theta */
 5050: 
 5051:     trgradg =matrix(1,nlstate,1,npar);
 5052: 
 5053:     for(j=1; j<=nlstate;j++)
 5054:       for(theta=1; theta <=npar; theta++)
 5055: 	trgradg[j][theta]=gradg[theta][j];
 5056:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5057:     /*   printf("\nmgm mgp %d ",(int)age); */
 5058:     /*   for(j=1; j<=nlstate;j++){ */
 5059:     /* 	printf(" %d ",j); */
 5060:     /* 	for(theta=1; theta <=npar; theta++) */
 5061:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5062:     /* 	printf("\n "); */
 5063:     /*   } */
 5064:     /* } */
 5065:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5066:     /*   printf("\n gradg %d ",(int)age); */
 5067:     /*   for(j=1; j<=nlstate;j++){ */
 5068:     /* 	printf("%d ",j); */
 5069:     /* 	for(theta=1; theta <=npar; theta++) */
 5070:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5071:     /* 	printf("\n "); */
 5072:     /*   } */
 5073:     /* } */
 5074: 
 5075:     for(i=1;i<=nlstate;i++)
 5076:       varpl[i][(int)age] =0.;
 5077:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5078:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5079:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5080:     }else{
 5081:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5082:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5083:     }
 5084:     for(i=1;i<=nlstate;i++)
 5085:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5086: 
 5087:     fprintf(ficresvpl,"%.0f ",age );
 5088:     for(i=1; i<=nlstate;i++)
 5089:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5090:     fprintf(ficresvpl,"\n");
 5091:     free_vector(gp,1,nlstate);
 5092:     free_vector(gm,1,nlstate);
 5093:     free_matrix(mgm,1,npar,1,nlstate);
 5094:     free_matrix(mgp,1,npar,1,nlstate);
 5095:     free_matrix(gradg,1,npar,1,nlstate);
 5096:     free_matrix(trgradg,1,nlstate,1,npar);
 5097:   } /* End age */
 5098: 
 5099:   free_vector(xp,1,npar);
 5100:   free_matrix(doldm,1,nlstate,1,npar);
 5101:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5102: 
 5103: }
 5104: 
 5105: /************ Variance of one-step probabilities  ******************/
 5106: 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[])
 5107: {
 5108:   int i, j=0,  k1, l1, tj;
 5109:   int k2, l2, j1,  z1;
 5110:   int k=0, l;
 5111:   int first=1, first1, first2;
 5112:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5113:   double **dnewm,**doldm;
 5114:   double *xp;
 5115:   double *gp, *gm;
 5116:   double **gradg, **trgradg;
 5117:   double **mu;
 5118:   double age, cov[NCOVMAX+1];
 5119:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5120:   int theta;
 5121:   char fileresprob[FILENAMELENGTH];
 5122:   char fileresprobcov[FILENAMELENGTH];
 5123:   char fileresprobcor[FILENAMELENGTH];
 5124:   double ***varpij;
 5125: 
 5126:   strcpy(fileresprob,"PROB_"); 
 5127:   strcat(fileresprob,fileres);
 5128:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5129:     printf("Problem with resultfile: %s\n", fileresprob);
 5130:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5131:   }
 5132:   strcpy(fileresprobcov,"PROBCOV_"); 
 5133:   strcat(fileresprobcov,fileresu);
 5134:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5135:     printf("Problem with resultfile: %s\n", fileresprobcov);
 5136:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5137:   }
 5138:   strcpy(fileresprobcor,"PROBCOR_"); 
 5139:   strcat(fileresprobcor,fileresu);
 5140:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5141:     printf("Problem with resultfile: %s\n", fileresprobcor);
 5142:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5143:   }
 5144:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5145:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5146:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5147:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5148:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5149:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5150:   pstamp(ficresprob);
 5151:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5152:   fprintf(ficresprob,"# Age");
 5153:   pstamp(ficresprobcov);
 5154:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5155:   fprintf(ficresprobcov,"# Age");
 5156:   pstamp(ficresprobcor);
 5157:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5158:   fprintf(ficresprobcor,"# Age");
 5159: 
 5160: 
 5161:   for(i=1; i<=nlstate;i++)
 5162:     for(j=1; j<=(nlstate+ndeath);j++){
 5163:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5164:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5165:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5166:     }  
 5167:  /* fprintf(ficresprob,"\n");
 5168:   fprintf(ficresprobcov,"\n");
 5169:   fprintf(ficresprobcor,"\n");
 5170:  */
 5171:   xp=vector(1,npar);
 5172:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5173:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5174:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5175:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5176:   first=1;
 5177:   fprintf(ficgp,"\n# Routine varprob");
 5178:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5179:   fprintf(fichtm,"\n");
 5180: 
 5181:   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);
 5182:   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);
 5183:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5184: and drawn. It helps understanding how is the covariance between two incidences.\
 5185:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5186:   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. \
 5187: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5188: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5189: standard deviations wide on each axis. <br>\
 5190:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5191:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5192: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5193: 
 5194:   cov[1]=1;
 5195:   /* tj=cptcoveff; */
 5196:   tj = (int) pow(2,cptcoveff);
 5197:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5198:   j1=0;
 5199:   for(j1=1; j1<=tj;j1++){
 5200:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 5201:     /*j1++;*/
 5202:       if  (cptcovn>0) {
 5203: 	fprintf(ficresprob, "\n#********** Variable "); 
 5204: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5205: 	fprintf(ficresprob, "**********\n#\n");
 5206: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 5207: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5208: 	fprintf(ficresprobcov, "**********\n#\n");
 5209: 	
 5210: 	fprintf(ficgp, "\n#********** Variable "); 
 5211: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5212: 	fprintf(ficgp, "**********\n#\n");
 5213: 	
 5214: 	
 5215: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5216: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5217: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5218: 	
 5219: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 5220: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5221: 	fprintf(ficresprobcor, "**********\n#");    
 5222:       }
 5223:       
 5224:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5225:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5226:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 5227:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 5228:       for (age=bage; age<=fage; age ++){ 
 5229: 	cov[2]=age;
 5230: 	if(nagesqr==1)
 5231: 	  cov[3]= age*age;
 5232: 	for (k=1; k<=cptcovn;k++) {
 5233: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5234: 	  /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5235: 							 * 1  1 1 1 1
 5236: 							 * 2  2 1 1 1
 5237: 							 * 3  1 2 1 1
 5238: 							 */
 5239: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5240: 	}
 5241: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5242: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5243: 	for (k=1; k<=cptcovprod;k++)
 5244: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5245: 	
 5246:     
 5247: 	for(theta=1; theta <=npar; theta++){
 5248: 	  for(i=1; i<=npar; i++)
 5249: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5250: 	  
 5251: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5252: 	  
 5253: 	  k=0;
 5254: 	  for(i=1; i<= (nlstate); i++){
 5255: 	    for(j=1; j<=(nlstate+ndeath);j++){
 5256: 	      k=k+1;
 5257: 	      gp[k]=pmmij[i][j];
 5258: 	    }
 5259: 	  }
 5260: 	  
 5261: 	  for(i=1; i<=npar; i++)
 5262: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5263:     
 5264: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5265: 	  k=0;
 5266: 	  for(i=1; i<=(nlstate); i++){
 5267: 	    for(j=1; j<=(nlstate+ndeath);j++){
 5268: 	      k=k+1;
 5269: 	      gm[k]=pmmij[i][j];
 5270: 	    }
 5271: 	  }
 5272:      
 5273: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5274: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5275: 	}
 5276: 
 5277: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5278: 	  for(theta=1; theta <=npar; theta++)
 5279: 	    trgradg[j][theta]=gradg[theta][j];
 5280: 	
 5281: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5282: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5283: 
 5284: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 5285: 	
 5286: 	k=0;
 5287: 	for(i=1; i<=(nlstate); i++){
 5288: 	  for(j=1; j<=(nlstate+ndeath);j++){
 5289: 	    k=k+1;
 5290: 	    mu[k][(int) age]=pmmij[i][j];
 5291: 	  }
 5292: 	}
 5293:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5294: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5295: 	    varpij[i][j][(int)age] = doldm[i][j];
 5296: 
 5297: 	/*printf("\n%d ",(int)age);
 5298: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5299: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5300: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5301: 	  }*/
 5302: 
 5303: 	fprintf(ficresprob,"\n%d ",(int)age);
 5304: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 5305: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 5306: 
 5307: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5308: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5309: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5310: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5311: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5312: 	}
 5313: 	i=0;
 5314: 	for (k=1; k<=(nlstate);k++){
 5315:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 5316:  	    i++;
 5317: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5318: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5319: 	    for (j=1; j<=i;j++){
 5320: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5321: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5322: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5323: 	    }
 5324: 	  }
 5325: 	}/* end of loop for state */
 5326:       } /* end of loop for age */
 5327:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5328:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5329:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5330:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5331:       
 5332:       /* Confidence intervalle of pij  */
 5333:       /*
 5334: 	fprintf(ficgp,"\nunset parametric;unset label");
 5335: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5336: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5337: 	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);
 5338: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5339: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5340: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5341:       */
 5342: 
 5343:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5344:       first1=1;first2=2;
 5345:       for (k2=1; k2<=(nlstate);k2++){
 5346: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5347: 	  if(l2==k2) continue;
 5348: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 5349: 	  for (k1=1; k1<=(nlstate);k1++){
 5350: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5351: 	      if(l1==k1) continue;
 5352: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 5353: 	      if(i<=j) continue;
 5354: 	      for (age=bage; age<=fage; age ++){ 
 5355: 		if ((int)age %5==0){
 5356: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5357: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5358: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5359: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 5360: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 5361: 		  c12=cv12/sqrt(v1*v2);
 5362: 		  /* Computing eigen value of matrix of covariance */
 5363: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5364: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5365: 		  if ((lc2 <0) || (lc1 <0) ){
 5366: 		    if(first2==1){
 5367: 		      first1=0;
 5368: 		    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);
 5369: 		    }
 5370: 		    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);
 5371: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5372: 		    /* lc2=fabs(lc2); */
 5373: 		  }
 5374: 
 5375: 		  /* Eigen vectors */
 5376: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5377: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 5378: 		  v21=(lc1-v1)/cv12*v11;
 5379: 		  v12=-v21;
 5380: 		  v22=v11;
 5381: 		  tnalp=v21/v11;
 5382: 		  if(first1==1){
 5383: 		    first1=0;
 5384: 		    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);
 5385: 		  }
 5386: 		  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);
 5387: 		  /*printf(fignu*/
 5388: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 5389: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 5390: 		  if(first==1){
 5391: 		    first=0;
 5392:  		    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 5393:  		    fprintf(ficgp,"\nset parametric;unset label");
 5394: 		    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);
 5395: 		    fprintf(ficgp,"\nset ter svg size 640, 480");
 5396: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 5397:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
 5398: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 5399: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
 5400: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5401: 		    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5402: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 5403: 		    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5404: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5405: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5406: 		    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",\
 5407: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 5408: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5409: 		  }else{
 5410: 		    first=0;
 5411: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 5412: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5413: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5414: 		    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",\
 5415: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 5416: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5417: 		  }/* if first */
 5418: 		} /* age mod 5 */
 5419: 	      } /* end loop age */
 5420: 	      fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5421: 	      first=1;
 5422: 	    } /*l12 */
 5423: 	  } /* k12 */
 5424: 	} /*l1 */
 5425:       }/* k1 */
 5426:       /* } */ /* loop covariates */
 5427:   }
 5428:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 5429:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 5430:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5431:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 5432:   free_vector(xp,1,npar);
 5433:   fclose(ficresprob);
 5434:   fclose(ficresprobcov);
 5435:   fclose(ficresprobcor);
 5436:   fflush(ficgp);
 5437:   fflush(fichtmcov);
 5438: }
 5439: 
 5440: 
 5441: /******************* Printing html file ***********/
 5442: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 5443: 		  int lastpass, int stepm, int weightopt, char model[],\
 5444: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 5445: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 5446: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 5447: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 5448:   int jj1, k1, i1, cpt;
 5449: 
 5450:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 5451:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 5452: </ul>");
 5453:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 5454:    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",
 5455: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 5456:    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) ",
 5457: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 5458:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 5459:    fprintf(fichtm,"\
 5460:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5461: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 5462:    fprintf(fichtm,"\
 5463:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5464: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 5465:    fprintf(fichtm,"\
 5466:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5467: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 5468:    fprintf(fichtm,"\
 5469:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5470: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 5471:    fprintf(fichtm,"\
 5472:  - (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): \
 5473:    <a href=\"%s\">%s</a> <br>\n",
 5474: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 5475:    if(prevfcast==1){
 5476:      fprintf(fichtm,"\
 5477:  - Prevalence projections by age and states:				\
 5478:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 5479:    }
 5480: 
 5481: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 5482: 
 5483:  m=pow(2,cptcoveff);
 5484:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5485: 
 5486:  jj1=0;
 5487:  for(k1=1; k1<=m;k1++){
 5488:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5489:      jj1++;
 5490:      if (cptcovn > 0) {
 5491:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5492:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 5493: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5494: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 5495:        }
 5496:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5497:      }
 5498:      /* aij, bij */
 5499:      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> \
 5500: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 5501:      /* Pij */
 5502:      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> \
 5503: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 5504:      /* Quasi-incidences */
 5505:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 5506:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
 5507:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 5508: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 5509: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 5510:      /* Survival functions (period) in state j */
 5511:      for(cpt=1; cpt<=nlstate;cpt++){
 5512:        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> \
 5513: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 5514:      }
 5515:      /* State specific survival functions (period) */
 5516:      for(cpt=1; cpt<=nlstate;cpt++){
 5517:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 5518:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
 5519:  <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);
 5520:      }
 5521:      /* Period (stable) prevalence in each health state */
 5522:      for(cpt=1; cpt<=nlstate;cpt++){
 5523:        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> \
 5524: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 5525:      }
 5526:     if(backcast==1){
 5527:      /* Period (stable) back prevalence in each health state */
 5528:      for(cpt=1; cpt<=nlstate;cpt++){
 5529:        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> \
 5530: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 5531:      }
 5532:     }
 5533:     if(prevfcast==1){
 5534:       /* Projection of prevalence up to period (stable) prevalence in each health state */
 5535:       for(cpt=1; cpt<=nlstate;cpt++){
 5536: 	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> \
 5537: <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);
 5538:       }
 5539:     }
 5540: 
 5541:      for(cpt=1; cpt<=nlstate;cpt++) {
 5542:        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> \
 5543: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 5544:      }
 5545:    /* } /\* end i1 *\/ */
 5546:  }/* End k1 */
 5547:  fprintf(fichtm,"</ul>");
 5548: 
 5549:  fprintf(fichtm,"\
 5550: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 5551:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 5552:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 5553: But because parameters are usually highly correlated (a higher incidence of disability \
 5554: and a higher incidence of recovery can give very close observed transition) it might \
 5555: be very useful to look not only at linear confidence intervals estimated from the \
 5556: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 5557: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 5558: covariance matrix of the one-step probabilities. \
 5559: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 5560: 
 5561:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5562: 	 subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 5563:  fprintf(fichtm,"\
 5564:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5565: 	 subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 5566: 
 5567:  fprintf(fichtm,"\
 5568:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5569: 	 subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 5570:  fprintf(fichtm,"\
 5571:  - 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): \
 5572:    <a href=\"%s\">%s</a> <br>\n</li>",
 5573: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 5574:  fprintf(fichtm,"\
 5575:  - (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): \
 5576:    <a href=\"%s\">%s</a> <br>\n</li>",
 5577: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 5578:  fprintf(fichtm,"\
 5579:  - 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",
 5580: 	 estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 5581:  fprintf(fichtm,"\
 5582:  - 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",
 5583: 	 estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 5584:  fprintf(fichtm,"\
 5585:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 5586: 	 subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 5587: 
 5588: /*  if(popforecast==1) fprintf(fichtm,"\n */
 5589: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 5590: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 5591: /* 	<br>",fileres,fileres,fileres,fileres); */
 5592: /*  else  */
 5593: /*    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); */
 5594:  fflush(fichtm);
 5595:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 5596: 
 5597:  m=pow(2,cptcoveff);
 5598:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5599: 
 5600:  jj1=0;
 5601:  for(k1=1; k1<=m;k1++){
 5602:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5603:      jj1++;
 5604:      if (cptcovn > 0) {
 5605:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5606:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 5607: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5608:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5609:      }
 5610:      for(cpt=1; cpt<=nlstate;cpt++) {
 5611:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 5612: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
 5613: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 5614:      }
 5615:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 5616: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 5617: true period expectancies (those weighted with period prevalences are also\
 5618:  drawn in addition to the population based expectancies computed using\
 5619:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 5620: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 5621:    /* } /\* end i1 *\/ */
 5622:  }/* End k1 */
 5623:  fprintf(fichtm,"</ul>");
 5624:  fflush(fichtm);
 5625: }
 5626: 
 5627: /******************* Gnuplot file **************/
 5628:  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 5629: 
 5630:   char dirfileres[132],optfileres[132];
 5631:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 5632:   int lv=0, vlv=0, kl=0;
 5633:   int ng=0;
 5634:   int vpopbased;
 5635: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 5636: /*     printf("Problem with file %s",optionfilegnuplot); */
 5637: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 5638: /*   } */
 5639: 
 5640:   /*#ifdef windows */
 5641:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5642:     /*#endif */
 5643:   m=pow(2,cptcoveff);
 5644: 
 5645:   /* Contribution to likelihood */
 5646:   /* Plot the probability implied in the likelihood */
 5647:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 5648:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 5649:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 5650:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 5651: /* nice for mle=4 plot by number of matrix products.
 5652:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 5653: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 5654:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 5655:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 5656:     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));
 5657:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 5658:     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));
 5659:     for (i=1; i<= nlstate ; i ++) {
 5660:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 5661:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 5662:       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);
 5663:       for (j=2; j<= nlstate+ndeath ; j ++) {
 5664: 	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);
 5665:       }
 5666:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 5667:     }
 5668:     /* 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 */		 
 5669:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 5670:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 5671:     fprintf(ficgp,"\nset out;unset log\n");
 5672:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 5673: 
 5674:   strcpy(dirfileres,optionfilefiname);
 5675:   strcpy(optfileres,"vpl");
 5676:  /* 1eme*/
 5677:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 5678:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
 5679:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 5680:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 5681:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5682: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5683: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5684: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5685: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5686: 	vlv= nbcode[Tvaraff[lv]][lv];
 5687: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5688:       }
 5689:       fprintf(ficgp,"\n#\n");
 5690: 
 5691:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 5692:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 5693:      fprintf(ficgp,"set xlabel \"Age\" \n\
 5694: set ylabel \"Probability\" \n\
 5695: set ter svg size 640, 480\n\
 5696: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5697: 
 5698:      for (i=1; i<= nlstate ; i ++) {
 5699:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5700:        else        fprintf(ficgp," %%*lf (%%*lf)");
 5701:      }
 5702:      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);
 5703:      for (i=1; i<= nlstate ; i ++) {
 5704:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5705:        else fprintf(ficgp," %%*lf (%%*lf)");
 5706:      } 
 5707:      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); 
 5708:      for (i=1; i<= nlstate ; i ++) {
 5709:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5710:        else fprintf(ficgp," %%*lf (%%*lf)");
 5711:      }  
 5712:      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));
 5713: 		 if(backcast==1){
 5714: 			 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);
 5715: 		 }
 5716:      fprintf(ficgp,"\nset out \n");
 5717:     } /* k1 */
 5718:   } /* cpt */
 5719:   /*2 eme*/
 5720:   for (k1=1; k1<= m ; k1 ++) { 
 5721:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 5722:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5723: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5724: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5725: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5726: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5727: 	vlv= nbcode[Tvaraff[lv]][lv];
 5728: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5729:       }
 5730:       fprintf(ficgp,"\n#\n");
 5731: 
 5732:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 5733:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 5734:       if(vpopbased==0)
 5735: 	fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 5736:       else
 5737: 	fprintf(ficgp,"\nreplot ");
 5738:       for (i=1; i<= nlstate+1 ; i ++) {
 5739: 	k=2*i;
 5740: 	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);
 5741: 	for (j=1; j<= nlstate+1 ; j ++) {
 5742: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5743: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5744: 	}   
 5745: 	if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 5746: 	else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 5747: 	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);
 5748: 	for (j=1; j<= nlstate+1 ; j ++) {
 5749: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5750: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5751: 	}   
 5752: 	fprintf(ficgp,"\" t\"\" w l lt 0,");
 5753: 	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);
 5754: 	for (j=1; j<= nlstate+1 ; j ++) {
 5755: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5756: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5757: 	}   
 5758: 	if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 5759: 	else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 5760:       } /* state */
 5761:     } /* vpopbased */
 5762:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 5763:   } /* k1 */
 5764: 
 5765: 
 5766:   /*3eme*/
 5767:   for (k1=1; k1<= m ; k1 ++) { 
 5768:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 5769:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 5770:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5771: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5772: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5773: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5774: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5775: 	vlv= nbcode[Tvaraff[lv]][lv];
 5776: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5777:       }
 5778:       fprintf(ficgp,"\n#\n");
 5779: 
 5780:       /*       k=2+nlstate*(2*cpt-2); */
 5781:       k=2+(nlstate+1)*(cpt-1);
 5782:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 5783:       fprintf(ficgp,"set ter svg size 640, 480\n\
 5784: 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);
 5785:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5786: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5787: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5788: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5789: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5790: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5791: 	
 5792:       */
 5793:       for (i=1; i< nlstate ; i ++) {
 5794: 	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);
 5795: 	/*	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);*/
 5796: 	
 5797:       } 
 5798:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 5799:     }
 5800:   }
 5801:   
 5802:   /* Survival functions (period) from state i in state j by initial state i */
 5803:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 5804:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5805:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 5806:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5807: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5808: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5809: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5810: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5811: 	vlv= nbcode[Tvaraff[lv]][lv];
 5812: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5813:       }
 5814:       fprintf(ficgp,"\n#\n");
 5815: 
 5816:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 5817:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5818: set ter svg size 640, 480\n\
 5819: unset log y\n\
 5820: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5821:       k=3;
 5822:       for (i=1; i<= nlstate ; i ++){
 5823: 	if(i==1){
 5824: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5825: 	}else{
 5826: 	  fprintf(ficgp,", '' ");
 5827: 	}
 5828: 	l=(nlstate+ndeath)*(i-1)+1;
 5829: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5830: 	for (j=2; j<= nlstate+ndeath ; j ++)
 5831: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5832: 	fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 5833:       } /* nlstate */
 5834:       fprintf(ficgp,"\nset out\n");
 5835:     } /* end cpt state*/ 
 5836:   } /* end covariate */  
 5837: 
 5838:   /* Survival functions (period) from state i in state j by final state j */
 5839:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 5840:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 5841:       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);
 5842:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5843: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5844: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5845: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5846: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5847: 	vlv= nbcode[Tvaraff[lv]][lv];
 5848: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5849:       }
 5850:       fprintf(ficgp,"\n#\n");
 5851: 
 5852:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 5853:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5854: set ter svg size 640, 480\n\
 5855: unset log y\n\
 5856: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5857:       k=3;
 5858:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5859: 	if(j==1)
 5860: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5861: 	else
 5862: 	  fprintf(ficgp,", '' ");
 5863: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5864: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 5865: 	/* for (i=2; i<= nlstate+ndeath ; i ++) */
 5866: 	/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 5867: 	fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 5868:       } /* nlstate */
 5869:       fprintf(ficgp,", '' ");
 5870:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 5871:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5872: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5873: 	if(j < nlstate)
 5874: 	  fprintf(ficgp,"$%d +",k+l);
 5875: 	else
 5876: 	  fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 5877:       }
 5878:       fprintf(ficgp,"\nset out\n");
 5879:     } /* end cpt state*/ 
 5880:   } /* end covariate */  
 5881: 
 5882:   /* CV preval stable (period) for each covariate */
 5883:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5884:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5885:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 5886:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5887: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5888: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5889: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5890: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5891: 	vlv= nbcode[Tvaraff[lv]][lv];
 5892: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5893:       }
 5894:       fprintf(ficgp,"\n#\n");
 5895: 
 5896:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 5897:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 5898: set ter svg size 640, 480\n\
 5899: unset log y\n\
 5900: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5901:       k=3; /* Offset */
 5902:       for (i=1; i<= nlstate ; i ++){
 5903: 	if(i==1)
 5904: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5905: 	else
 5906: 	  fprintf(ficgp,", '' ");
 5907: 	l=(nlstate+ndeath)*(i-1)+1;
 5908: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5909: 	for (j=2; j<= nlstate ; j ++)
 5910: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5911: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 5912:       } /* nlstate */
 5913:       fprintf(ficgp,"\nset out\n");
 5914:     } /* end cpt state*/ 
 5915:   } /* end covariate */  
 5916:   if(backcast == 1){
 5917:     /* CV back preval stable (period) for each covariate */
 5918:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5919:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5920: 	fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 5921: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5922: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5923: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5924: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5925: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5926: 	  vlv= nbcode[Tvaraff[lv]][lv];
 5927: 	  fprintf(ficgp," V%d=%d ",k,vlv);
 5928: 	}
 5929: 	fprintf(ficgp,"\n#\n");
 5930: 	
 5931: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 5932: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 5933: set ter svg size 640, 480\n						\
 5934: unset log y\n								\
 5935: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5936: 	k=3; /* Offset */
 5937: 	for (i=1; i<= nlstate ; i ++){
 5938: 	  if(i==1)
 5939: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 5940: 	  else
 5941: 	    fprintf(ficgp,", '' ");
 5942: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 5943: 	  l=(nlstate+ndeath)*(cpt-1)+1;
 5944: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 5945: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 5946: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 5947: 	  /* for (j=2; j<= nlstate ; j ++) */
 5948: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 5949: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 5950: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 5951: 	} /* nlstate */
 5952: 	fprintf(ficgp,"\nset out\n");
 5953:       } /* end cpt state*/ 
 5954:     } /* end covariate */  
 5955:   } /* End if backcast */
 5956:   
 5957:   if(prevfcast==1){
 5958:     /* Projection from cross-sectional to stable (period) for each covariate */
 5959:     
 5960:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5961:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5962: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 5963: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 5964: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5965: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5966: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5967: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5968: 	  vlv= nbcode[Tvaraff[lv]][lv];
 5969: 	  fprintf(ficgp," V%d=%d ",k,vlv);
 5970: 	}
 5971: 	fprintf(ficgp,"\n#\n");
 5972: 	
 5973: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 5974: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 5975: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 5976: set ter svg size 640, 480\n\
 5977: unset log y\n\
 5978: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5979: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 5980: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5981: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5982: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5983: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5984: 	  if(i==1){
 5985: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 5986: 	  }else{
 5987: 	    fprintf(ficgp,",\\\n '' ");
 5988: 	  }
 5989: 	  if(cptcoveff ==0){ /* No covariate */
 5990: 	    fprintf(ficgp," u 2:("); /* Age is in 2 */
 5991: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 5992: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 5993: 	    if(i==nlstate+1)
 5994: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
 5995: 			2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
 5996: 	    else
 5997: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
 5998: 		      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 5999: 	  }else{
 6000: 	    fprintf(ficgp,"u 6:(("); /* Age is in 6 */
 6001: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6002: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6003: 	    kl=0;
 6004: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
 6005: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6006: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6007: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6008: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6009: 	      vlv= nbcode[Tvaraff[lv]][lv];
 6010: 	      kl++;
 6011: 	      /* 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 *\/ */
 6012: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6013: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6014: 	      /* ''  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*/
 6015: 	      if(k==cptcoveff)
 6016: 		if(i==nlstate+1)
 6017: 		  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
 6018: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6019: 		else
 6020: 		  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
 6021: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6022: 	      else{
 6023: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
 6024: 		kl++;
 6025: 	      }
 6026: 	    } /* end covariate */
 6027: 	  } /* end if covariate */
 6028: 	} /* nlstate */
 6029: 	fprintf(ficgp,"\nset out\n");
 6030:       } /* end cpt state*/
 6031:     } /* end covariate */
 6032:   } /* End if prevfcast */
 6033: 
 6034: 
 6035:   /* proba elementaires */
 6036:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 6037:   for(i=1,jk=1; i <=nlstate; i++){
 6038:     fprintf(ficgp,"# initial state %d\n",i);
 6039:     for(k=1; k <=(nlstate+ndeath); k++){
 6040:       if (k != i) {
 6041: 	fprintf(ficgp,"#   current state %d\n",k);
 6042: 	for(j=1; j <=ncovmodel; j++){
 6043: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6044: 	  jk++; 
 6045: 	}
 6046: 	fprintf(ficgp,"\n");
 6047:       }
 6048:     }
 6049:    }
 6050:   fprintf(ficgp,"##############\n#\n");
 6051: 
 6052:   /*goto avoid;*/
 6053:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 6054:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6055:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6056:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6057:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6058:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6059:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6060:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6061:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6062:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6063:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6064:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6065:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6066:   fprintf(ficgp,"#\n");
 6067:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6068:      fprintf(ficgp,"# ng=%d\n",ng);
 6069:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 6070:      for(jk=1; jk <=m; jk++) {
 6071:        fprintf(ficgp,"#    jk=%d\n",jk);
 6072:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 6073:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6074:        if (ng==1){
 6075: 	 fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6076: 	 fprintf(ficgp,"\nunset log y");
 6077:        }else if (ng==2){
 6078: 	 fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6079: 	 fprintf(ficgp,"\nset log y");
 6080:        }else if (ng==3){
 6081: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6082: 	 fprintf(ficgp,"\nset log y");
 6083:        }else
 6084: 	 fprintf(ficgp,"\nunset title ");
 6085:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6086:        i=1;
 6087:        for(k2=1; k2<=nlstate; k2++) {
 6088: 	 k3=i;
 6089: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 6090: 	   if (k != k2){
 6091: 	     switch( ng) {
 6092: 	     case 1:
 6093: 	       if(nagesqr==0)
 6094: 		 fprintf(ficgp," p%d+p%d*x",i,i+1);
 6095: 	       else /* nagesqr =1 */
 6096: 		 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6097: 	       break;
 6098: 	     case 2: /* ng=2 */
 6099: 	       if(nagesqr==0)
 6100: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6101: 	       else /* nagesqr =1 */
 6102: 		   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6103: 	       break;
 6104: 	     case 3:
 6105: 	       if(nagesqr==0)
 6106: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6107: 	       else /* nagesqr =1 */
 6108: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6109: 	       break;
 6110: 	     }
 6111: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 6112: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 6113: 	       /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6114: 	       if(ij <=cptcovage) { /* Bug valgrind */
 6115: 		 if((j-2)==Tage[ij]) { /* Bug valgrind */
 6116: 		   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6117: 		   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6118: 		   ij++;
 6119: 		 }
 6120: 	       }
 6121: 	       else
 6122: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6123: 	     }
 6124: 	   }else{
 6125: 	     i=i-ncovmodel;
 6126: 	     if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 6127: 	       fprintf(ficgp," (1.");
 6128: 	   }
 6129: 	   
 6130: 	   if(ng != 1){
 6131: 	     fprintf(ficgp,")/(1");
 6132: 	     
 6133: 	     for(k1=1; k1 <=nlstate; k1++){ 
 6134: 	       if(nagesqr==0)
 6135: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6136: 	       else /* nagesqr =1 */
 6137: 		 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);
 6138: 	       
 6139: 	       ij=1;
 6140: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 6141: 		 if(ij <=cptcovage) { /* Bug valgrind */
 6142: 		   if((j-2)==Tage[ij]) { /* Bug valgrind */
 6143: 		     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6144: 		     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6145: 		     ij++;
 6146: 		   }
 6147: 		 }
 6148: 		 else
 6149: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6150: 	       }
 6151: 	       fprintf(ficgp,")");
 6152: 	     }
 6153: 	     fprintf(ficgp,")");
 6154: 	     if(ng ==2)
 6155: 	       fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6156: 	     else /* ng= 3 */
 6157: 	       fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6158: 	   }else{ /* end ng <> 1 */
 6159: 	     if( k !=k2) /* logit p11 is hard to draw */
 6160: 	       fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6161: 	   }
 6162: 	   if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6163: 	     fprintf(ficgp,",");
 6164: 	   if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6165: 	     fprintf(ficgp,",");
 6166: 	   i=i+ncovmodel;
 6167: 	 } /* end k */
 6168:        } /* end k2 */
 6169:        fprintf(ficgp,"\n set out\n");
 6170:      } /* end jk */
 6171:    } /* end ng */
 6172:  /* avoid: */
 6173:    fflush(ficgp); 
 6174: }  /* end gnuplot */
 6175: 
 6176: 
 6177: /*************** Moving average **************/
 6178: 		/* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 6179: int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 6180:    
 6181:   int i, cpt, cptcod;
 6182:   int modcovmax =1;
 6183:   int mobilavrange, mob;
 6184:   double age;
 6185:   int iage=0;
 6186:   double *sumnewp, *sumnewm;
 6187:   double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 6188:   
 6189:   sumnewp = vector(1,modcovmax);
 6190:   sumnewm = vector(1,modcovmax);
 6191:   agemingood = vector(1,modcovmax);	
 6192:   agemaxgood = vector(1,modcovmax);
 6193:   
 6194:   
 6195:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 6196: 			   a covariate has 2 modalities, should be equal to ncovcombmax  */
 6197:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 6198:   
 6199:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 6200:     if(mobilav==1) mobilavrange=5; /* default */
 6201:     else mobilavrange=mobilav;
 6202:     for (age=bage; age<=fage; age++)
 6203:       for (i=1; i<=nlstate;i++)
 6204: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 6205: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 6206:     /* We keep the original values on the extreme ages bage, fage and for 
 6207:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 6208:        we use a 5 terms etc. until the borders are no more concerned. 
 6209:     */ 
 6210:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 6211:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 6212: 	for (i=1; i<=nlstate;i++){
 6213: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 6214: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 6215: 	    for (cpt=1;cpt<=(mob-1)/2;cpt++){
 6216: 	      mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 6217: 	      mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 6218: 	    }
 6219: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 6220: 	  }
 6221: 	}
 6222:       }/* end age */
 6223:     }/* end mob */
 6224:   }else
 6225:     return -1;
 6226:   for (cptcod=1;cptcod<=modcovmax;cptcod++){
 6227:     /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 6228:     agemingood[cptcod]=fage+(mob-1)/2;
 6229:     for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 6230:       sumnewm[cptcod]=0.;
 6231:       for (i=1; i<=nlstate;i++){
 6232:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6233:       }
 6234:       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6235: 	agemingood[cptcod]=age;
 6236:       }else{ /* bad */
 6237: 	for (i=1; i<=nlstate;i++){
 6238: 	  mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6239: 	} /* i */
 6240:       } /* end bad */
 6241:     }/* age */
 6242:     /* From youngest, finding the oldest wrong */
 6243:     agemaxgood[cptcod]=bage+(mob-1)/2;
 6244:     for (age=bage+(mob-1)/2; age<=fage; age++){
 6245:       sumnewm[cptcod]=0.;
 6246:       for (i=1; i<=nlstate;i++){
 6247:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6248:       }
 6249:       if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6250: 	agemaxgood[cptcod]=age;
 6251:       }else{ /* bad */
 6252: 	for (i=1; i<=nlstate;i++){
 6253: 	  mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6254: 	} /* i */
 6255:       } /* end bad */
 6256:     }/* age */
 6257:     for (age=bage; age<=fage; age++){
 6258:       printf("%d %d ", cptcod, (int)age);
 6259:       sumnewp[cptcod]=0.;
 6260:       sumnewm[cptcod]=0.;
 6261:       for (i=1; i<=nlstate;i++){
 6262: 	sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 6263:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6264: 	printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]);
 6265:       }
 6266:       printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]);
 6267:     }
 6268:     printf("\n");
 6269:     /* brutal averaging */
 6270:     for (i=1; i<=nlstate;i++){
 6271:       for (age=1; age<=bage; age++){
 6272: 	mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6273: 	printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]);
 6274:       }	
 6275:       for (age=fage; age<=AGESUP; age++){
 6276: 	mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6277: 	printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]);
 6278:       }
 6279:     } /* end i status */
 6280:     for (i=nlstate+1; i<=nlstate+ndeath;i++){
 6281:       for (age=1; age<=AGESUP; age++){
 6282: 	/*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 6283: 	mobaverage[(int)age][i][cptcod]=0.;
 6284:       }
 6285:     }
 6286:   }/* end cptcod */
 6287:   free_vector(sumnewm,1, modcovmax);
 6288:   free_vector(sumnewp,1, modcovmax);
 6289:   free_vector(agemaxgood,1, modcovmax);
 6290:   free_vector(agemingood,1, modcovmax);
 6291:   return 0;
 6292: }/* End movingaverage */
 6293:  
 6294: 
 6295: /************** Forecasting ******************/
 6296: 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){
 6297:   /* proj1, year, month, day of starting projection 
 6298:      agemin, agemax range of age
 6299:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6300:      anproj2 year of en of projection (same day and month as proj1).
 6301:   */
 6302:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6303:   double agec; /* generic age */
 6304:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6305:   double *popeffectif,*popcount;
 6306:   double ***p3mat;
 6307:   /* double ***mobaverage; */
 6308:   char fileresf[FILENAMELENGTH];
 6309: 
 6310:   agelim=AGESUP;
 6311:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6312:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6313:      We still use firstpass and lastpass as another selection.
 6314:   */
 6315:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6316:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6317:  
 6318:   strcpy(fileresf,"F_"); 
 6319:   strcat(fileresf,fileresu);
 6320:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 6321:     printf("Problem with forecast resultfile: %s\n", fileresf);
 6322:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 6323:   }
 6324:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6325:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6326: 
 6327:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6328: 
 6329: 
 6330:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6331:   if (stepm<=12) stepsize=1;
 6332:   if(estepm < stepm){
 6333:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6334:   }
 6335:   else  hstepm=estepm;   
 6336: 
 6337:   hstepm=hstepm/stepm; 
 6338:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6339:                                fractional in yp1 */
 6340:   anprojmean=yp;
 6341:   yp2=modf((yp1*12),&yp);
 6342:   mprojmean=yp;
 6343:   yp1=modf((yp2*30.5),&yp);
 6344:   jprojmean=yp;
 6345:   if(jprojmean==0) jprojmean=1;
 6346:   if(mprojmean==0) jprojmean=1;
 6347: 
 6348:   i1=cptcoveff;
 6349:   if (cptcovn < 1){i1=1;}
 6350:   
 6351:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6352:   
 6353:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 6354: 
 6355: /* 	      if (h==(int)(YEARM*yearp)){ */
 6356:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 6357:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6358:       k=k+1;
 6359:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6360:       for(j=1;j<=cptcoveff;j++) {
 6361: 	fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6362:       }
 6363:       fprintf(ficresf," yearproj age");
 6364:       for(j=1; j<=nlstate+ndeath;j++){ 
 6365: 	for(i=1; i<=nlstate;i++) 	      
 6366:           fprintf(ficresf," p%d%d",i,j);
 6367: 	fprintf(ficresf," p.%d",j);
 6368:       }
 6369:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 6370: 	fprintf(ficresf,"\n");
 6371: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 6372:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6373: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6374: 	  nhstepm = nhstepm/hstepm; 
 6375: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6376: 	  oldm=oldms;savm=savms;
 6377: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
 6378: 	
 6379: 	  for (h=0; h<=nhstepm; h++){
 6380: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 6381:               fprintf(ficresf,"\n");
 6382:               for(j=1;j<=cptcoveff;j++) 
 6383:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6384: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 6385: 	    } 
 6386: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6387: 	      ppij=0.;
 6388: 	      for(i=1; i<=nlstate;i++) {
 6389: 		if (mobilav==1) 
 6390: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 6391: 		else {
 6392: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 6393: 		}
 6394: 		if (h*hstepm/YEARM*stepm== yearp) {
 6395: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 6396: 		}
 6397: 	      } /* end i */
 6398: 	      if (h*hstepm/YEARM*stepm==yearp) {
 6399: 		fprintf(ficresf," %.3f", ppij);
 6400: 	      }
 6401: 	    }/* end j */
 6402: 	  } /* end h */
 6403: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6404: 	} /* end agec */
 6405:       } /* end yearp */
 6406:     } /* end cptcod */
 6407:   } /* end  cptcov */
 6408:        
 6409:   fclose(ficresf);
 6410:   printf("End of Computing forecasting \n");
 6411:   fprintf(ficlog,"End of Computing forecasting\n");
 6412: 
 6413: }
 6414: 
 6415: /* /\************** Back Forecasting ******************\/ */
 6416: /* 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){ */
 6417: /*   /\* back1, year, month, day of starting backection  */
 6418: /*      agemin, agemax range of age */
 6419: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 6420: /*      anback2 year of en of backection (same day and month as back1). */
 6421: /*   *\/ */
 6422: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 6423: /*   double agec; /\* generic age *\/ */
 6424: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 6425: /*   double *popeffectif,*popcount; */
 6426: /*   double ***p3mat; */
 6427: /*   /\* double ***mobaverage; *\/ */
 6428: /*   char fileresfb[FILENAMELENGTH]; */
 6429: 	
 6430: /*   agelim=AGESUP; */
 6431: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 6432: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 6433: /*      We still use firstpass and lastpass as another selection. */
 6434: /*   *\/ */
 6435: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 6436: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 6437: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 6438: 	
 6439: /*   strcpy(fileresfb,"FB_");  */
 6440: /*   strcat(fileresfb,fileresu); */
 6441: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 6442: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 6443: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 6444: /*   } */
 6445: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6446: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6447: 	
 6448: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 6449: 	
 6450: /*   /\* if (mobilav!=0) { *\/ */
 6451: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6452: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 6453: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6454: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6455: /*   /\*   } *\/ */
 6456: /*   /\* } *\/ */
 6457: 	
 6458: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 6459: /*   if (stepm<=12) stepsize=1; */
 6460: /*   if(estepm < stepm){ */
 6461: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 6462: /*   } */
 6463: /*   else  hstepm=estepm;    */
 6464: 	
 6465: /*   hstepm=hstepm/stepm;  */
 6466: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 6467: /*                                fractional in yp1 *\/ */
 6468: /*   anprojmean=yp; */
 6469: /*   yp2=modf((yp1*12),&yp); */
 6470: /*   mprojmean=yp; */
 6471: /*   yp1=modf((yp2*30.5),&yp); */
 6472: /*   jprojmean=yp; */
 6473: /*   if(jprojmean==0) jprojmean=1; */
 6474: /*   if(mprojmean==0) jprojmean=1; */
 6475: 	
 6476: /*   i1=cptcoveff; */
 6477: /*   if (cptcovn < 1){i1=1;} */
 6478:   
 6479: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 6480:   
 6481: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 6482: 	
 6483: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 6484: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 6485: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 6486: /*       k=k+1; */
 6487: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 6488: /*       for(j=1;j<=cptcoveff;j++) { */
 6489: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6490: /*       } */
 6491: /*       fprintf(ficresfb," yearbproj age"); */
 6492: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 6493: /* 				for(i=1; i<=nlstate;i++) 	       */
 6494: /*           fprintf(ficresfb," p%d%d",i,j); */
 6495: /* 				fprintf(ficresfb," p.%d",j); */
 6496: /*       } */
 6497: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 6498: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 6499: /* 				fprintf(ficresfb,"\n"); */
 6500: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 6501: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 6502: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 6503: /* 					nhstepm = nhstepm/hstepm;  */
 6504: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6505: /* 					oldm=oldms;savm=savms; */
 6506: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 6507: /* 					for (h=0; h<=nhstepm; h++){ */
 6508: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 6509: /*               fprintf(ficresfb,"\n"); */
 6510: /*               for(j=1;j<=cptcoveff;j++)  */
 6511: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6512: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 6513: /* 						}  */
 6514: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 6515: /* 							ppij=0.; */
 6516: /* 							for(i=1; i<=nlstate;i++) { */
 6517: /* 								if (mobilav==1)  */
 6518: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 6519: /* 								else { */
 6520: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 6521: /* 								} */
 6522: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 6523: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 6524: /* 								} */
 6525: /* 							} /\* end i *\/ */
 6526: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 6527: /* 								fprintf(ficresfb," %.3f", ppij); */
 6528: /* 							} */
 6529: /* 						}/\* end j *\/ */
 6530: /* 					} /\* end h *\/ */
 6531: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6532: /* 				} /\* end agec *\/ */
 6533: /*       } /\* end yearp *\/ */
 6534: /*     } /\* end cptcod *\/ */
 6535: /*   } /\* end  cptcov *\/ */
 6536: 	
 6537: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6538: 	
 6539: /*   fclose(ficresfb); */
 6540: /*   printf("End of Computing Back forecasting \n"); */
 6541: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 6542: 	
 6543: /* } */
 6544: 
 6545: /************** Forecasting *****not tested NB*************/
 6546: 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){
 6547:   
 6548:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 6549:   int *popage;
 6550:   double calagedatem, agelim, kk1, kk2;
 6551:   double *popeffectif,*popcount;
 6552:   double ***p3mat,***tabpop,***tabpopprev;
 6553:   /* double ***mobaverage; */
 6554:   char filerespop[FILENAMELENGTH];
 6555: 
 6556:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6557:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6558:   agelim=AGESUP;
 6559:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 6560:   
 6561:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6562:   
 6563:   
 6564:   strcpy(filerespop,"POP_"); 
 6565:   strcat(filerespop,fileresu);
 6566:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 6567:     printf("Problem with forecast resultfile: %s\n", filerespop);
 6568:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 6569:   }
 6570:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 6571:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 6572: 
 6573:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6574: 
 6575:   /* if (mobilav!=0) { */
 6576:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 6577:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
 6578:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 6579:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 6580:   /*   } */
 6581:   /* } */
 6582: 
 6583:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6584:   if (stepm<=12) stepsize=1;
 6585:   
 6586:   agelim=AGESUP;
 6587:   
 6588:   hstepm=1;
 6589:   hstepm=hstepm/stepm; 
 6590: 	
 6591:   if (popforecast==1) {
 6592:     if((ficpop=fopen(popfile,"r"))==NULL) {
 6593:       printf("Problem with population file : %s\n",popfile);exit(0);
 6594:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 6595:     } 
 6596:     popage=ivector(0,AGESUP);
 6597:     popeffectif=vector(0,AGESUP);
 6598:     popcount=vector(0,AGESUP);
 6599:     
 6600:     i=1;   
 6601:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 6602:     
 6603:     imx=i;
 6604:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 6605:   }
 6606:   
 6607:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 6608:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6609:       k=k+1;
 6610:       fprintf(ficrespop,"\n#******");
 6611:       for(j=1;j<=cptcoveff;j++) {
 6612: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6613:       }
 6614:       fprintf(ficrespop,"******\n");
 6615:       fprintf(ficrespop,"# Age");
 6616:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 6617:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 6618:       
 6619:       for (cpt=0; cpt<=0;cpt++) { 
 6620: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6621: 	
 6622: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6623: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6624: 	  nhstepm = nhstepm/hstepm; 
 6625: 	  
 6626: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6627: 	  oldm=oldms;savm=savms;
 6628: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6629: 	  
 6630: 	  for (h=0; h<=nhstepm; h++){
 6631: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6632: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6633: 	    } 
 6634: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6635: 	      kk1=0.;kk2=0;
 6636: 	      for(i=1; i<=nlstate;i++) {	      
 6637: 		if (mobilav==1) 
 6638: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 6639: 		else {
 6640: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 6641: 		}
 6642: 	      }
 6643: 	      if (h==(int)(calagedatem+12*cpt)){
 6644: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 6645: 		/*fprintf(ficrespop," %.3f", kk1);
 6646: 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 6647: 	      }
 6648: 	    }
 6649: 	    for(i=1; i<=nlstate;i++){
 6650: 	      kk1=0.;
 6651: 	      for(j=1; j<=nlstate;j++){
 6652: 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 6653: 	      }
 6654: 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 6655: 	    }
 6656: 	    
 6657: 	    if (h==(int)(calagedatem+12*cpt))
 6658: 	      for(j=1; j<=nlstate;j++) 
 6659: 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 6660: 	  }
 6661: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6662: 	}
 6663:       }
 6664:       
 6665:       /******/
 6666:       
 6667:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 6668: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6669: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6670: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6671: 	  nhstepm = nhstepm/hstepm; 
 6672: 	  
 6673: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6674: 	  oldm=oldms;savm=savms;
 6675: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6676: 	  for (h=0; h<=nhstepm; h++){
 6677: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6678: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6679: 	    } 
 6680: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6681: 	      kk1=0.;kk2=0;
 6682: 	      for(i=1; i<=nlstate;i++) {	      
 6683: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 6684: 	      }
 6685: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 6686: 	    }
 6687: 	  }
 6688: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6689: 	}
 6690:       }
 6691:     } 
 6692:   }
 6693:   
 6694:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 6695:   
 6696:   if (popforecast==1) {
 6697:     free_ivector(popage,0,AGESUP);
 6698:     free_vector(popeffectif,0,AGESUP);
 6699:     free_vector(popcount,0,AGESUP);
 6700:   }
 6701:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6702:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6703:   fclose(ficrespop);
 6704: } /* End of popforecast */
 6705:  
 6706: int fileappend(FILE *fichier, char *optionfich)
 6707: {
 6708:   if((fichier=fopen(optionfich,"a"))==NULL) {
 6709:     printf("Problem with file: %s\n", optionfich);
 6710:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 6711:     return (0);
 6712:   }
 6713:   fflush(fichier);
 6714:   return (1);
 6715: }
 6716: 
 6717: 
 6718: /**************** function prwizard **********************/
 6719: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 6720: {
 6721: 
 6722:   /* Wizard to print covariance matrix template */
 6723: 
 6724:   char ca[32], cb[32];
 6725:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 6726:   int numlinepar;
 6727: 
 6728:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6729:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6730:   for(i=1; i <=nlstate; i++){
 6731:     jj=0;
 6732:     for(j=1; j <=nlstate+ndeath; j++){
 6733:       if(j==i) continue;
 6734:       jj++;
 6735:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 6736:       printf("%1d%1d",i,j);
 6737:       fprintf(ficparo,"%1d%1d",i,j);
 6738:       for(k=1; k<=ncovmodel;k++){
 6739: 	/* 	  printf(" %lf",param[i][j][k]); */
 6740: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 6741: 	printf(" 0.");
 6742: 	fprintf(ficparo," 0.");
 6743:       }
 6744:       printf("\n");
 6745:       fprintf(ficparo,"\n");
 6746:     }
 6747:   }
 6748:   printf("# Scales (for hessian or gradient estimation)\n");
 6749:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 6750:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 6751:   for(i=1; i <=nlstate; i++){
 6752:     jj=0;
 6753:     for(j=1; j <=nlstate+ndeath; j++){
 6754:       if(j==i) continue;
 6755:       jj++;
 6756:       fprintf(ficparo,"%1d%1d",i,j);
 6757:       printf("%1d%1d",i,j);
 6758:       fflush(stdout);
 6759:       for(k=1; k<=ncovmodel;k++){
 6760: 	/* 	printf(" %le",delti3[i][j][k]); */
 6761: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 6762: 	printf(" 0.");
 6763: 	fprintf(ficparo," 0.");
 6764:       }
 6765:       numlinepar++;
 6766:       printf("\n");
 6767:       fprintf(ficparo,"\n");
 6768:     }
 6769:   }
 6770:   printf("# Covariance matrix\n");
 6771: /* # 121 Var(a12)\n\ */
 6772: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6773: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6774: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6775: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6776: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6777: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6778: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6779:   fflush(stdout);
 6780:   fprintf(ficparo,"# Covariance matrix\n");
 6781:   /* # 121 Var(a12)\n\ */
 6782:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6783:   /* #   ...\n\ */
 6784:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 6785:   
 6786:   for(itimes=1;itimes<=2;itimes++){
 6787:     jj=0;
 6788:     for(i=1; i <=nlstate; i++){
 6789:       for(j=1; j <=nlstate+ndeath; j++){
 6790: 	if(j==i) continue;
 6791: 	for(k=1; k<=ncovmodel;k++){
 6792: 	  jj++;
 6793: 	  ca[0]= k+'a'-1;ca[1]='\0';
 6794: 	  if(itimes==1){
 6795: 	    printf("#%1d%1d%d",i,j,k);
 6796: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 6797: 	  }else{
 6798: 	    printf("%1d%1d%d",i,j,k);
 6799: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 6800: 	    /* 	printf(" %.5le",matcov[i][j]); */
 6801: 	  }
 6802: 	  ll=0;
 6803: 	  for(li=1;li <=nlstate; li++){
 6804: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 6805: 	      if(lj==li) continue;
 6806: 	      for(lk=1;lk<=ncovmodel;lk++){
 6807: 		ll++;
 6808: 		if(ll<=jj){
 6809: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 6810: 		  if(ll<jj){
 6811: 		    if(itimes==1){
 6812: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6813: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6814: 		    }else{
 6815: 		      printf(" 0.");
 6816: 		      fprintf(ficparo," 0.");
 6817: 		    }
 6818: 		  }else{
 6819: 		    if(itimes==1){
 6820: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 6821: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 6822: 		    }else{
 6823: 		      printf(" 0.");
 6824: 		      fprintf(ficparo," 0.");
 6825: 		    }
 6826: 		  }
 6827: 		}
 6828: 	      } /* end lk */
 6829: 	    } /* end lj */
 6830: 	  } /* end li */
 6831: 	  printf("\n");
 6832: 	  fprintf(ficparo,"\n");
 6833: 	  numlinepar++;
 6834: 	} /* end k*/
 6835:       } /*end j */
 6836:     } /* end i */
 6837:   } /* end itimes */
 6838: 
 6839: } /* end of prwizard */
 6840: /******************* Gompertz Likelihood ******************************/
 6841: double gompertz(double x[])
 6842: { 
 6843:   double A,B,L=0.0,sump=0.,num=0.;
 6844:   int i,n=0; /* n is the size of the sample */
 6845: 
 6846:   for (i=0;i<=imx-1 ; i++) {
 6847:     sump=sump+weight[i];
 6848:     /*    sump=sump+1;*/
 6849:     num=num+1;
 6850:   }
 6851:  
 6852:  
 6853:   /* for (i=0; i<=imx; i++) 
 6854:      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]);*/
 6855: 
 6856:   for (i=1;i<=imx ; i++)
 6857:     {
 6858:       if (cens[i] == 1 && wav[i]>1)
 6859: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 6860:       
 6861:       if (cens[i] == 0 && wav[i]>1)
 6862: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 6863: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 6864:       
 6865:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 6866:       if (wav[i] > 1 ) { /* ??? */
 6867: 	L=L+A*weight[i];
 6868: 	/* 	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]);*/
 6869:       }
 6870:     }
 6871: 
 6872:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 6873:  
 6874:   return -2*L*num/sump;
 6875: }
 6876: 
 6877: #ifdef GSL
 6878: /******************* Gompertz_f Likelihood ******************************/
 6879: double gompertz_f(const gsl_vector *v, void *params)
 6880: { 
 6881:   double A,B,LL=0.0,sump=0.,num=0.;
 6882:   double *x= (double *) v->data;
 6883:   int i,n=0; /* n is the size of the sample */
 6884: 
 6885:   for (i=0;i<=imx-1 ; i++) {
 6886:     sump=sump+weight[i];
 6887:     /*    sump=sump+1;*/
 6888:     num=num+1;
 6889:   }
 6890:  
 6891:  
 6892:   /* for (i=0; i<=imx; i++) 
 6893:      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]);*/
 6894:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 6895:   for (i=1;i<=imx ; i++)
 6896:     {
 6897:       if (cens[i] == 1 && wav[i]>1)
 6898: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 6899:       
 6900:       if (cens[i] == 0 && wav[i]>1)
 6901: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 6902: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 6903:       
 6904:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 6905:       if (wav[i] > 1 ) { /* ??? */
 6906: 	LL=LL+A*weight[i];
 6907: 	/* 	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]);*/
 6908:       }
 6909:     }
 6910: 
 6911:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 6912:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 6913:  
 6914:   return -2*LL*num/sump;
 6915: }
 6916: #endif
 6917: 
 6918: /******************* Printing html file ***********/
 6919: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 6920: 		  int lastpass, int stepm, int weightopt, char model[],\
 6921: 		  int imx,  double p[],double **matcov,double agemortsup){
 6922:   int i,k;
 6923: 
 6924:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 6925:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 6926:   for (i=1;i<=2;i++) 
 6927:     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]));
 6928:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 6929:   fprintf(fichtm,"</ul>");
 6930: 
 6931: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 6932: 
 6933:  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>");
 6934: 
 6935:  for (k=agegomp;k<(agemortsup-2);k++) 
 6936:    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]);
 6937: 
 6938:  
 6939:   fflush(fichtm);
 6940: }
 6941: 
 6942: /******************* Gnuplot file **************/
 6943: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 6944: 
 6945:   char dirfileres[132],optfileres[132];
 6946: 
 6947:   int ng;
 6948: 
 6949: 
 6950:   /*#ifdef windows */
 6951:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6952:     /*#endif */
 6953: 
 6954: 
 6955:   strcpy(dirfileres,optionfilefiname);
 6956:   strcpy(optfileres,"vpl");
 6957:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 6958:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 6959:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 6960:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 6961:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 6962: 
 6963: } 
 6964: 
 6965: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 6966: {
 6967: 
 6968:   /*-------- data file ----------*/
 6969:   FILE *fic;
 6970:   char dummy[]="                         ";
 6971:   int i=0, j=0, n=0;
 6972:   int linei, month, year,iout;
 6973:   char line[MAXLINE], linetmp[MAXLINE];
 6974:   char stra[MAXLINE], strb[MAXLINE];
 6975:   char *stratrunc;
 6976:   int lstra;
 6977: 
 6978: 
 6979:   if((fic=fopen(datafile,"r"))==NULL)    {
 6980:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 6981:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 6982:   }
 6983: 
 6984:   i=1;
 6985:   linei=0;
 6986:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 6987:     linei=linei+1;
 6988:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 6989:       if(line[j] == '\t')
 6990: 	line[j] = ' ';
 6991:     }
 6992:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 6993:       ;
 6994:     };
 6995:     line[j+1]=0;  /* Trims blanks at end of line */
 6996:     if(line[0]=='#'){
 6997:       fprintf(ficlog,"Comment line\n%s\n",line);
 6998:       printf("Comment line\n%s\n",line);
 6999:       continue;
 7000:     }
 7001:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7002:     strcpy(line, linetmp);
 7003:   
 7004: 
 7005:     for (j=maxwav;j>=1;j--){
 7006:       cutv(stra, strb, line, ' '); 
 7007:       if(strb[0]=='.') { /* Missing status */
 7008: 	lval=-1;
 7009:       }else{
 7010: 	errno=0;
 7011: 	lval=strtol(strb,&endptr,10); 
 7012:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7013: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7014: 	  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);
 7015: 	  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);
 7016: 	  return 1;
 7017: 	}
 7018:       }
 7019:       s[j][i]=lval;
 7020:       
 7021:       strcpy(line,stra);
 7022:       cutv(stra, strb,line,' ');
 7023:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7024:       }
 7025:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7026: 	month=99;
 7027: 	year=9999;
 7028:       }else{
 7029: 	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);
 7030: 	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);
 7031: 	return 1;
 7032:       }
 7033:       anint[j][i]= (double) year; 
 7034:       mint[j][i]= (double)month; 
 7035:       strcpy(line,stra);
 7036:     } /* ENd Waves */
 7037:     
 7038:     cutv(stra, strb,line,' '); 
 7039:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7040:     }
 7041:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7042:       month=99;
 7043:       year=9999;
 7044:     }else{
 7045:       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);
 7046: 	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);
 7047: 	return 1;
 7048:     }
 7049:     andc[i]=(double) year; 
 7050:     moisdc[i]=(double) month; 
 7051:     strcpy(line,stra);
 7052:     
 7053:     cutv(stra, strb,line,' '); 
 7054:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7055:     }
 7056:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 7057:       month=99;
 7058:       year=9999;
 7059:     }else{
 7060:       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);
 7061:       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);
 7062: 	return 1;
 7063:     }
 7064:     if (year==9999) {
 7065:       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);
 7066:       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);
 7067: 	return 1;
 7068: 
 7069:     }
 7070:     annais[i]=(double)(year);
 7071:     moisnais[i]=(double)(month); 
 7072:     strcpy(line,stra);
 7073:     
 7074:     cutv(stra, strb,line,' '); 
 7075:     errno=0;
 7076:     dval=strtod(strb,&endptr); 
 7077:     if( strb[0]=='\0' || (*endptr != '\0')){
 7078:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 7079:       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);
 7080:       fflush(ficlog);
 7081:       return 1;
 7082:     }
 7083:     weight[i]=dval; 
 7084:     strcpy(line,stra);
 7085:     
 7086:     for (j=ncovcol;j>=1;j--){
 7087:       cutv(stra, strb,line,' '); 
 7088:       if(strb[0]=='.') { /* Missing status */
 7089: 	lval=-1;
 7090:       }else{
 7091: 	errno=0;
 7092: 	lval=strtol(strb,&endptr,10); 
 7093: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7094: 	  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);
 7095: 	  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);
 7096: 	  return 1;
 7097: 	}
 7098:       }
 7099:       if(lval <-1 || lval >1){
 7100: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7101:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7102:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7103:  For example, for multinomial values like 1, 2 and 3,\n \
 7104:  build V1=0 V2=0 for the reference value (1),\n \
 7105:         V1=1 V2=0 for (2) \n \
 7106:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7107:  output of IMaCh is often meaningless.\n \
 7108:  Exiting.\n",lval,linei, i,line,j);
 7109: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7110:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7111:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7112:  For example, for multinomial values like 1, 2 and 3,\n \
 7113:  build V1=0 V2=0 for the reference value (1),\n \
 7114:         V1=1 V2=0 for (2) \n \
 7115:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7116:  output of IMaCh is often meaningless.\n \
 7117:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7118: 	return 1;
 7119:       }
 7120:       covar[j][i]=(double)(lval);
 7121:       strcpy(line,stra);
 7122:     }  
 7123:     lstra=strlen(stra);
 7124:      
 7125:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 7126:       stratrunc = &(stra[lstra-9]);
 7127:       num[i]=atol(stratrunc);
 7128:     }
 7129:     else
 7130:       num[i]=atol(stra);
 7131:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 7132:       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;}*/
 7133:     
 7134:     i=i+1;
 7135:   } /* End loop reading  data */
 7136: 
 7137:   *imax=i-1; /* Number of individuals */
 7138:   fclose(fic);
 7139:  
 7140:   return (0);
 7141:   /* endread: */
 7142:     printf("Exiting readdata: ");
 7143:     fclose(fic);
 7144:     return (1);
 7145: 
 7146: 
 7147: 
 7148: }
 7149: void removespace(char *str) {
 7150:   char *p1 = str, *p2 = str;
 7151:   do
 7152:     while (*p2 == ' ')
 7153:       p2++;
 7154:   while (*p1++ == *p2++);
 7155: }
 7156: 
 7157: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 7158:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 7159:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 7160:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 7161:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 7162:    * - cptcovage number of covariates with age*products =2
 7163:    * - cptcovs number of simple covariates
 7164:    * - 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
 7165:    *     which is a new column after the 9 (ncovcol) variables. 
 7166:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 7167:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 7168:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 7169:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 7170:  */
 7171: {
 7172:   int i, j, k, ks;
 7173:   int  j1, k1, k2;
 7174:   char modelsav[80];
 7175:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 7176:   char *strpt;
 7177: 
 7178:   /*removespace(model);*/
 7179:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 7180:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 7181:     if (strstr(model,"AGE") !=0){
 7182:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 7183:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 7184:       return 1;
 7185:     }
 7186:     if (strstr(model,"v") !=0){
 7187:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 7188:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 7189:       return 1;
 7190:     }
 7191:     strcpy(modelsav,model); 
 7192:     if ((strpt=strstr(model,"age*age")) !=0){
 7193:       printf(" strpt=%s, model=%s\n",strpt, model);
 7194:       if(strpt != model){
 7195:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7196:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7197:  corresponding column of parameters.\n",model);
 7198:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7199:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7200:  corresponding column of parameters.\n",model); fflush(ficlog);
 7201:       return 1;
 7202:     }
 7203: 
 7204:       nagesqr=1;
 7205:       if (strstr(model,"+age*age") !=0)
 7206: 	substrchaine(modelsav, model, "+age*age");
 7207:       else if (strstr(model,"age*age+") !=0)
 7208: 	substrchaine(modelsav, model, "age*age+");
 7209:       else 
 7210: 	substrchaine(modelsav, model, "age*age");
 7211:     }else
 7212:       nagesqr=0;
 7213:     if (strlen(modelsav) >1){
 7214:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 7215:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 7216:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 7217:       cptcovt= j+1; /* Number of total covariates in the model, not including
 7218: 		   * cst, age and age*age 
 7219: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 7220:                   /* including age products which are counted in cptcovage.
 7221: 		  * but the covariates which are products must be treated 
 7222: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 7223:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 7224:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 7225: 
 7226:     
 7227:       /*   Design
 7228:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 7229:        *  <          ncovcol=8                >
 7230:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 7231:        *   k=  1    2      3       4     5       6      7        8
 7232:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 7233:        *  covar[k,i], value of kth covariate if not including age for individual i:
 7234:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 7235:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 7236:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 7237:        *  Tage[++cptcovage]=k
 7238:        *       if products, new covar are created after ncovcol with k1
 7239:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 7240:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 7241:        *  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
 7242:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 7243:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 7244:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 7245:        *  <          ncovcol=8                >
 7246:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 7247:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 7248:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 7249:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7250:        * p Tprod[1]@2={                         6, 5}
 7251:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 7252:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 7253:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 7254:        *How to reorganize?
 7255:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 7256:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7257:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 7258:        * Struct []
 7259:        */
 7260: 
 7261:       /* This loop fills the array Tvar from the string 'model'.*/
 7262:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 7263:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 7264:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 7265:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 7266:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 7267:       /* 	k=1 Tvar[1]=2 (from V2) */
 7268:       /* 	k=5 Tvar[5] */
 7269:       /* for (k=1; k<=cptcovn;k++) { */
 7270:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 7271:       /* 	} */
 7272:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 7273:       /*
 7274:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 7275:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 7276:         Tvar[k]=0;
 7277:       cptcovage=0;
 7278:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 7279: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 7280: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 7281: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 7282: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 7283: 	/*scanf("%d",i);*/
 7284: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 7285: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 7286: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 7287: 	    /* covar is not filled and then is empty */
 7288: 	    cptcovprod--;
 7289: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 7290: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 7291: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 7292: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 7293: 	    /*printf("stre=%s ", stre);*/
 7294: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 7295: 	    cptcovprod--;
 7296: 	    cutl(stre,strb,strc,'V');
 7297: 	    Tvar[k]=atoi(stre);
 7298: 	    cptcovage++;
 7299: 	    Tage[cptcovage]=k;
 7300: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 7301: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 7302: 	    cptcovn++;
 7303: 	    cptcovprodnoage++;k1++;
 7304: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 7305: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 7306: 				   because this model-covariate is a construction we invent a new column
 7307: 				   ncovcol + k1
 7308: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 7309: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 7310: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 7311: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 7312: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 7313: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 7314: 	    k2=k2+2;
 7315: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 7316: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 7317: 	    for (i=1; i<=lastobs;i++){
 7318: 	      /* Computes the new covariate which is a product of
 7319: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 7320: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 7321: 	    }
 7322: 	  } /* End age is not in the model */
 7323: 	} /* End if model includes a product */
 7324: 	else { /* no more sum */
 7325: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 7326: 	  /*  scanf("%d",i);*/
 7327: 	  cutl(strd,strc,strb,'V');
 7328: 	  ks++; /**< Number of simple covariates */
 7329: 	  cptcovn++;
 7330: 	  Tvar[k]=atoi(strd);
 7331: 	}
 7332: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 7333: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 7334: 	  scanf("%d",i);*/
 7335:       } /* end of loop + on total covariates */
 7336:     } /* end if strlen(modelsave == 0) age*age might exist */
 7337:   } /* end if strlen(model == 0) */
 7338:   
 7339:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 7340:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 7341: 
 7342:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 7343:   printf("cptcovprod=%d ", cptcovprod);
 7344:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 7345: 
 7346:   scanf("%d ",i);*/
 7347: 
 7348: 
 7349:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 7350:   /*endread:*/
 7351:     printf("Exiting decodemodel: ");
 7352:     return (1);
 7353: }
 7354: 
 7355: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 7356: {
 7357:   int i, m;
 7358:   int firstone=0;
 7359:   
 7360:   for (i=1; i<=imx; i++) {
 7361:     for(m=2; (m<= maxwav); m++) {
 7362:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 7363: 	anint[m][i]=9999;
 7364: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 7365: 	  s[m][i]=-1;
 7366:       }
 7367:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 7368: 	*nberr = *nberr + 1;
 7369: 	if(firstone == 0){
 7370: 	  firstone=1;
 7371: 	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);
 7372: 	}
 7373: 	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);
 7374: 	s[m][i]=-1;
 7375:       }
 7376:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 7377: 	(*nberr)++;
 7378: 	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]); 
 7379: 	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]); 
 7380: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 7381:       }
 7382:     }
 7383:   }
 7384: 
 7385:   for (i=1; i<=imx; i++)  {
 7386:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 7387:     for(m=firstpass; (m<= lastpass); m++){
 7388:       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 */
 7389: 	if (s[m][i] >= nlstate+1) {
 7390: 	  if(agedc[i]>0){
 7391: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 7392: 	      agev[m][i]=agedc[i];
 7393: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 7394: 	    }else {
 7395: 	      if ((int)andc[i]!=9999){
 7396: 		nbwarn++;
 7397: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 7398: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 7399: 		agev[m][i]=-1;
 7400: 	      }
 7401: 	    }
 7402: 	  } /* agedc > 0 */
 7403: 	} /* end if */
 7404: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 7405: 				 years but with the precision of a month */
 7406: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 7407: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 7408: 	    agev[m][i]=1;
 7409: 	  else if(agev[m][i] < *agemin){ 
 7410: 	    *agemin=agev[m][i];
 7411: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 7412: 	  }
 7413: 	  else if(agev[m][i] >*agemax){
 7414: 	    *agemax=agev[m][i];
 7415: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 7416: 	  }
 7417: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 7418: 	  /*	 agev[m][i] = age[i]+2*m;*/
 7419: 	} /* en if 9*/
 7420: 	else { /* =9 */
 7421: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 7422: 	  agev[m][i]=1;
 7423: 	  s[m][i]=-1;
 7424: 	}
 7425:       }
 7426:       else if(s[m][i]==0) /*= 0 Unknown */
 7427: 	agev[m][i]=1;
 7428:       else{
 7429: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7430: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7431: 	agev[m][i]=0;
 7432:       }
 7433:     } /* End for lastpass */
 7434:   }
 7435:     
 7436:   for (i=1; i<=imx; i++)  {
 7437:     for(m=firstpass; (m<=lastpass); m++){
 7438:       if (s[m][i] > (nlstate+ndeath)) {
 7439: 	(*nberr)++;
 7440: 	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);	
 7441: 	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);	
 7442: 	return 1;
 7443:       }
 7444:     }
 7445:   }
 7446: 
 7447:   /*for (i=1; i<=imx; i++){
 7448:   for (m=firstpass; (m<lastpass); m++){
 7449:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 7450: }
 7451: 
 7452: }*/
 7453: 
 7454: 
 7455:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 7456:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 7457: 
 7458:   return (0);
 7459:  /* endread:*/
 7460:     printf("Exiting calandcheckages: ");
 7461:     return (1);
 7462: }
 7463: 
 7464: #if defined(_MSC_VER)
 7465: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7466: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7467: //#include "stdafx.h"
 7468: //#include <stdio.h>
 7469: //#include <tchar.h>
 7470: //#include <windows.h>
 7471: //#include <iostream>
 7472: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 7473: 
 7474: LPFN_ISWOW64PROCESS fnIsWow64Process;
 7475: 
 7476: BOOL IsWow64()
 7477: {
 7478: 	BOOL bIsWow64 = FALSE;
 7479: 
 7480: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 7481: 	//  (HANDLE, PBOOL);
 7482: 
 7483: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 7484: 
 7485: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 7486: 	const char funcName[] = "IsWow64Process";
 7487: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 7488: 		GetProcAddress(module, funcName);
 7489: 
 7490: 	if (NULL != fnIsWow64Process)
 7491: 	{
 7492: 		if (!fnIsWow64Process(GetCurrentProcess(),
 7493: 			&bIsWow64))
 7494: 			//throw std::exception("Unknown error");
 7495: 			printf("Unknown error\n");
 7496: 	}
 7497: 	return bIsWow64 != FALSE;
 7498: }
 7499: #endif
 7500: 
 7501: void syscompilerinfo(int logged)
 7502:  {
 7503:    /* #include "syscompilerinfo.h"*/
 7504:    /* command line Intel compiler 32bit windows, XP compatible:*/
 7505:    /* /GS /W3 /Gy
 7506:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 7507:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 7508:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 7509:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 7510:    */ 
 7511:    /* 64 bits */
 7512:    /*
 7513:      /GS /W3 /Gy
 7514:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 7515:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 7516:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 7517:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 7518:    /* Optimization are useless and O3 is slower than O2 */
 7519:    /*
 7520:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 7521:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 7522:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 7523:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 7524:    */
 7525:    /* Link is */ /* /OUT:"visual studio
 7526:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 7527:       /PDB:"visual studio
 7528:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 7529:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 7530:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 7531:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 7532:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 7533:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 7534:       uiAccess='false'"
 7535:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 7536:       /NOLOGO /TLBID:1
 7537:    */
 7538: #if defined __INTEL_COMPILER
 7539: #if defined(__GNUC__)
 7540: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 7541: #endif
 7542: #elif defined(__GNUC__) 
 7543: #ifndef  __APPLE__
 7544: #include <gnu/libc-version.h>  /* Only on gnu */
 7545: #endif
 7546:    struct utsname sysInfo;
 7547:    int cross = CROSS;
 7548:    if (cross){
 7549: 	   printf("Cross-");
 7550: 	   if(logged) fprintf(ficlog, "Cross-");
 7551:    }
 7552: #endif
 7553: 
 7554: #include <stdint.h>
 7555: 
 7556:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 7557: #if defined(__clang__)
 7558:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 7559: #endif
 7560: #if defined(__ICC) || defined(__INTEL_COMPILER)
 7561:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 7562: #endif
 7563: #if defined(__GNUC__) || defined(__GNUG__)
 7564:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 7565: #endif
 7566: #if defined(__HP_cc) || defined(__HP_aCC)
 7567:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 7568: #endif
 7569: #if defined(__IBMC__) || defined(__IBMCPP__)
 7570:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 7571: #endif
 7572: #if defined(_MSC_VER)
 7573:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 7574: #endif
 7575: #if defined(__PGI)
 7576:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 7577: #endif
 7578: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 7579:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 7580: #endif
 7581:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 7582:    
 7583: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 7584: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 7585:     // Windows (x64 and x86)
 7586:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 7587: #elif __unix__ // all unices, not all compilers
 7588:     // Unix
 7589:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 7590: #elif __linux__
 7591:     // linux
 7592:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 7593: #elif __APPLE__
 7594:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 7595:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 7596: #endif
 7597: 
 7598: /*  __MINGW32__	  */
 7599: /*  __CYGWIN__	 */
 7600: /* __MINGW64__  */
 7601: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 7602: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 7603: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 7604: /* _WIN64  // Defined for applications for Win64. */
 7605: /* _M_X64 // Defined for compilations that target x64 processors. */
 7606: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 7607: 
 7608: #if UINTPTR_MAX == 0xffffffff
 7609:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 7610: #elif UINTPTR_MAX == 0xffffffffffffffff
 7611:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 7612: #else
 7613:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 7614: #endif
 7615: 
 7616: #if defined(__GNUC__)
 7617: # if defined(__GNUC_PATCHLEVEL__)
 7618: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7619:                             + __GNUC_MINOR__ * 100 \
 7620:                             + __GNUC_PATCHLEVEL__)
 7621: # else
 7622: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7623:                             + __GNUC_MINOR__ * 100)
 7624: # endif
 7625:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 7626:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 7627: 
 7628:    if (uname(&sysInfo) != -1) {
 7629:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7630: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7631:    }
 7632:    else
 7633:       perror("uname() error");
 7634:    //#ifndef __INTEL_COMPILER 
 7635: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 7636:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 7637:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 7638: #endif
 7639: #endif
 7640: 
 7641:    //   void main()
 7642:    //   {
 7643: #if defined(_MSC_VER)
 7644:    if (IsWow64()){
 7645: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7646: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7647:    }
 7648:    else{
 7649: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7650: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7651:    }
 7652:    //	   printf("\nPress Enter to continue...");
 7653:    //	   getchar();
 7654:    //   }
 7655: 
 7656: #endif
 7657:    
 7658: 
 7659:  }
 7660: 
 7661:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 7662:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7663:   int i, j, k, i1 ;
 7664:   /* double ftolpl = 1.e-10; */
 7665:   double age, agebase, agelim;
 7666:   double tot;
 7667: 
 7668:   strcpy(filerespl,"PL_");
 7669:   strcat(filerespl,fileresu);
 7670:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 7671:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7672:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7673:   }
 7674:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7675:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7676:   pstamp(ficrespl);
 7677:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7678:   fprintf(ficrespl,"#Age ");
 7679:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 7680:   fprintf(ficrespl,"\n");
 7681:   
 7682:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7683: 
 7684:     agebase=ageminpar;
 7685:     agelim=agemaxpar;
 7686: 
 7687:     i1=pow(2,cptcoveff);
 7688:     if (cptcovn < 1){i1=1;}
 7689: 
 7690:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7691:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7692:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7693: 	k=k+1;
 7694: 	/* to clean */
 7695: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7696: 	fprintf(ficrespl,"#******");
 7697: 	printf("#******");
 7698: 	fprintf(ficlog,"#******");
 7699: 	for(j=1;j<=cptcoveff;j++) {
 7700: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7701: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7702: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7703: 	}
 7704: 	fprintf(ficrespl,"******\n");
 7705: 	printf("******\n");
 7706: 	fprintf(ficlog,"******\n");
 7707: 
 7708: 	fprintf(ficrespl,"#Age ");
 7709: 	for(j=1;j<=cptcoveff;j++) {
 7710: 	  fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7711: 	}
 7712: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 7713: 	fprintf(ficrespl,"Total Years_to_converge\n");
 7714: 	
 7715: 	for (age=agebase; age<=agelim; age++){
 7716: 	/* for (age=agebase; age<=agebase; age++){ */
 7717: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 7718: 	  fprintf(ficrespl,"%.0f ",age );
 7719: 	  for(j=1;j<=cptcoveff;j++)
 7720: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7721: 	  tot=0.;
 7722: 	  for(i=1; i<=nlstate;i++){
 7723: 	    tot +=  prlim[i][i];
 7724: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 7725: 	  }
 7726: 	  fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 7727: 	} /* Age */
 7728: 	/* was end of cptcod */
 7729:     } /* cptcov */
 7730: 	return 0;
 7731: }
 7732: 
 7733: 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){
 7734: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 7735: 	
 7736: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 7737:    * at any age between ageminpar and agemaxpar
 7738: 	 */
 7739:   int i, j, k, i1 ;
 7740:   /* double ftolpl = 1.e-10; */
 7741:   double age, agebase, agelim;
 7742:   double tot;
 7743:   /* double ***mobaverage; */
 7744:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 7745: 
 7746:   strcpy(fileresplb,"PLB_");
 7747:   strcat(fileresplb,fileresu);
 7748:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 7749:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7750:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7751:   }
 7752:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7753:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7754:   pstamp(ficresplb);
 7755:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7756:   fprintf(ficresplb,"#Age ");
 7757:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 7758:   fprintf(ficresplb,"\n");
 7759:   
 7760:   
 7761:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7762:   
 7763:   agebase=ageminpar;
 7764:   agelim=agemaxpar;
 7765:   
 7766:   
 7767:   i1=pow(2,cptcoveff);
 7768:   if (cptcovn < 1){i1=1;}
 7769:   
 7770:   for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7771:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7772:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7773:     k=k+1;
 7774:     /* to clean */
 7775:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7776:     fprintf(ficresplb,"#******");
 7777:     printf("#******");
 7778:     fprintf(ficlog,"#******");
 7779:     for(j=1;j<=cptcoveff;j++) {
 7780:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7781:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7782:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7783:     }
 7784:     fprintf(ficresplb,"******\n");
 7785:     printf("******\n");
 7786:     fprintf(ficlog,"******\n");
 7787:     
 7788:     fprintf(ficresplb,"#Age ");
 7789:     for(j=1;j<=cptcoveff;j++) {
 7790:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7791:     }
 7792:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 7793:     fprintf(ficresplb,"Total Years_to_converge\n");
 7794:     
 7795:     
 7796:     for (age=agebase; age<=agelim; age++){
 7797:       /* for (age=agebase; age<=agebase; age++){ */
 7798:       if(mobilavproj > 0){
 7799: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 7800: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 7801: 	bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
 7802:       }else if (mobilavproj == 0){
 7803: 	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);
 7804: 	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);
 7805: 	exit(1);
 7806:       }else{
 7807: 	/* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 7808: 	bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
 7809:       }
 7810:       fprintf(ficresplb,"%.0f ",age );
 7811:       for(j=1;j<=cptcoveff;j++)
 7812: 	fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7813:       tot=0.;
 7814:       for(i=1; i<=nlstate;i++){
 7815: 	tot +=  bprlim[i][i];
 7816: 	fprintf(ficresplb," %.5f", bprlim[i][i]);
 7817:       }
 7818:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 7819:     } /* Age */
 7820:     /* was end of cptcod */
 7821:   } /* cptcov */
 7822:   
 7823:   /* hBijx(p, bage, fage); */
 7824:   /* fclose(ficrespijb); */
 7825:   
 7826:   return 0;
 7827: }
 7828:  
 7829: int hPijx(double *p, int bage, int fage){
 7830:     /*------------- h Pij x at various ages ------------*/
 7831: 
 7832:   int stepsize;
 7833:   int agelim;
 7834:   int hstepm;
 7835:   int nhstepm;
 7836:   int h, i, i1, j, k;
 7837: 
 7838:   double agedeb;
 7839:   double ***p3mat;
 7840: 
 7841:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 7842:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 7843:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 7844:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 7845:     }
 7846:     printf("Computing pij: result on file '%s' \n", filerespij);
 7847:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 7848:   
 7849:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 7850:     /*if (stepm<=24) stepsize=2;*/
 7851: 
 7852:     agelim=AGESUP;
 7853:     hstepm=stepsize*YEARM; /* Every year of age */
 7854:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 7855: 		
 7856:     /* hstepm=1;   aff par mois*/
 7857:     pstamp(ficrespij);
 7858:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 7859:     i1= pow(2,cptcoveff);
 7860: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7861: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 7862: 		/*  	k=k+1;  */
 7863:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7864:       fprintf(ficrespij,"\n#****** ");
 7865:       for(j=1;j<=cptcoveff;j++) 
 7866: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7867:       fprintf(ficrespij,"******\n");
 7868:       
 7869:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 7870: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7871: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7872: 	
 7873: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 7874: 	
 7875: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7876: 	oldm=oldms;savm=savms;
 7877: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 7878: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 7879: 	for(i=1; i<=nlstate;i++)
 7880: 	  for(j=1; j<=nlstate+ndeath;j++)
 7881: 	    fprintf(ficrespij," %1d-%1d",i,j);
 7882: 	fprintf(ficrespij,"\n");
 7883: 	for (h=0; h<=nhstepm; h++){
 7884: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 7885: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 7886: 	  for(i=1; i<=nlstate;i++)
 7887: 	    for(j=1; j<=nlstate+ndeath;j++)
 7888: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 7889: 	  fprintf(ficrespij,"\n");
 7890: 	}
 7891: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7892: 	fprintf(ficrespij,"\n");
 7893:       }
 7894:       /*}*/
 7895:     }
 7896:     return 0;
 7897: }
 7898:  
 7899:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 7900:     /*------------- h Bij x at various ages ------------*/
 7901: 
 7902:   int stepsize;
 7903:   /* int agelim; */
 7904: 	int ageminl;
 7905:   int hstepm;
 7906:   int nhstepm;
 7907:   int h, i, i1, j, k;
 7908: 	
 7909:   double agedeb;
 7910:   double ***p3mat;
 7911: 	
 7912:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 7913:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 7914:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 7915:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 7916:   }
 7917:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 7918:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 7919:   
 7920:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 7921:   /*if (stepm<=24) stepsize=2;*/
 7922:   
 7923:   /* agelim=AGESUP; */
 7924:   ageminl=30;
 7925:   hstepm=stepsize*YEARM; /* Every year of age */
 7926:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 7927:   
 7928:   /* hstepm=1;   aff par mois*/
 7929:   pstamp(ficrespijb);
 7930:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 7931:   i1= pow(2,cptcoveff);
 7932:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7933:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 7934:   /*  	k=k+1;  */
 7935:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7936:     fprintf(ficrespijb,"\n#****** ");
 7937:     for(j=1;j<=cptcoveff;j++)
 7938:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7939:     fprintf(ficrespijb,"******\n");
 7940:     
 7941:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 7942:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 7943:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 7944:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 7945:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 7946:       
 7947:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 7948:       
 7949:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7950:       /* oldm=oldms;savm=savms; */
 7951:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7952:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 7953:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 7954:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 7955:       for(i=1; i<=nlstate;i++)
 7956: 	for(j=1; j<=nlstate+ndeath;j++)
 7957: 	  fprintf(ficrespijb," %1d-%1d",i,j);
 7958:       fprintf(ficrespijb,"\n");
 7959:       for (h=0; h<=nhstepm; h++){
 7960: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 7961: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 7962: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 7963: 	for(i=1; i<=nlstate;i++)
 7964: 	  for(j=1; j<=nlstate+ndeath;j++)
 7965: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 7966: 	fprintf(ficrespijb,"\n");
 7967:       }
 7968:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7969:       fprintf(ficrespijb,"\n");
 7970:     }
 7971:     /*}*/
 7972:   }
 7973:   return 0;
 7974:  } /*  hBijx */
 7975: 
 7976: 
 7977: /***********************************************/
 7978: /**************** Main Program *****************/
 7979: /***********************************************/
 7980: 
 7981: int main(int argc, char *argv[])
 7982: {
 7983: #ifdef GSL
 7984:   const gsl_multimin_fminimizer_type *T;
 7985:   size_t iteri = 0, it;
 7986:   int rval = GSL_CONTINUE;
 7987:   int status = GSL_SUCCESS;
 7988:   double ssval;
 7989: #endif
 7990:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 7991:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 7992:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 7993:   int jj, ll, li, lj, lk;
 7994:   int numlinepar=0; /* Current linenumber of parameter file */
 7995:   int num_filled;
 7996:   int itimes;
 7997:   int NDIM=2;
 7998:   int vpopbased=0;
 7999: 
 8000:   char ca[32], cb[32];
 8001:   /*  FILE *fichtm; *//* Html File */
 8002:   /* FILE *ficgp;*/ /*Gnuplot File */
 8003:   struct stat info;
 8004:   double agedeb=0.;
 8005: 
 8006:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 8007: 	double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 8008: 
 8009:   double fret;
 8010:   double dum=0.; /* Dummy variable */
 8011:   double ***p3mat;
 8012:   /* double ***mobaverage; */
 8013: 
 8014:   char line[MAXLINE];
 8015:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 8016: 
 8017:   char model[MAXLINE], modeltemp[MAXLINE];
 8018:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 8019:   char *tok, *val; /* pathtot */
 8020:   int firstobs=1, lastobs=10;
 8021:   int c,  h , cpt, c2;
 8022:   int jl=0;
 8023:   int i1, j1, jk, stepsize=0;
 8024:   int count=0;
 8025: 
 8026:   int *tab; 
 8027:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 8028:   int backcast=0;
 8029:   int mobilav=0,popforecast=0;
 8030:   int hstepm=0, nhstepm=0;
 8031:   int agemortsup;
 8032:   float  sumlpop=0.;
 8033:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 8034:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 8035: 
 8036:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 8037:   double ftolpl=FTOL;
 8038:   double **prlim;
 8039:   double **bprlim;
 8040:   double ***param; /* Matrix of parameters */
 8041:   double  *p;
 8042:   double **matcov; /* Matrix of covariance */
 8043:   double **hess; /* Hessian matrix */
 8044:   double ***delti3; /* Scale */
 8045:   double *delti; /* Scale */
 8046:   double ***eij, ***vareij;
 8047:   double **varpl; /* Variances of prevalence limits by age */
 8048:   double *epj, vepp;
 8049: 
 8050:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 8051:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 8052: 
 8053:   double **ximort;
 8054:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 8055:   int *dcwave;
 8056: 
 8057:   char z[1]="c";
 8058: 
 8059:   /*char  *strt;*/
 8060:   char strtend[80];
 8061: 
 8062: 
 8063: /*   setlocale (LC_ALL, ""); */
 8064: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 8065: /*   textdomain (PACKAGE); */
 8066: /*   setlocale (LC_CTYPE, ""); */
 8067: /*   setlocale (LC_MESSAGES, ""); */
 8068: 
 8069:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 8070:   rstart_time = time(NULL);  
 8071:   /*  (void) gettimeofday(&start_time,&tzp);*/
 8072:   start_time = *localtime(&rstart_time);
 8073:   curr_time=start_time;
 8074:   /*tml = *localtime(&start_time.tm_sec);*/
 8075:   /* strcpy(strstart,asctime(&tml)); */
 8076:   strcpy(strstart,asctime(&start_time));
 8077: 
 8078: /*  printf("Localtime (at start)=%s",strstart); */
 8079: /*  tp.tm_sec = tp.tm_sec +86400; */
 8080: /*  tm = *localtime(&start_time.tm_sec); */
 8081: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 8082: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 8083: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 8084: /*   tp.tm_sec = mktime(&tmg); */
 8085: /*   strt=asctime(&tmg); */
 8086: /*   printf("Time(after) =%s",strstart);  */
 8087: /*  (void) time (&time_value);
 8088: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 8089: *  tm = *localtime(&time_value);
 8090: *  strstart=asctime(&tm);
 8091: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 8092: */
 8093: 
 8094:   nberr=0; /* Number of errors and warnings */
 8095:   nbwarn=0;
 8096: #ifdef WIN32
 8097:   _getcwd(pathcd, size);
 8098: #else
 8099:   getcwd(pathcd, size);
 8100: #endif
 8101:   syscompilerinfo(0);
 8102:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 8103:   if(argc <=1){
 8104:     printf("\nEnter the parameter file name: ");
 8105:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 8106:       printf("ERROR Empty parameter file name\n");
 8107:       goto end;
 8108:     }
 8109:     i=strlen(pathr);
 8110:     if(pathr[i-1]=='\n')
 8111:       pathr[i-1]='\0';
 8112:     i=strlen(pathr);
 8113:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 8114:       pathr[i-1]='\0';
 8115:     }
 8116:     i=strlen(pathr);
 8117:     if( i==0 ){
 8118:       printf("ERROR Empty parameter file name\n");
 8119:       goto end;
 8120:     }
 8121:     for (tok = pathr; tok != NULL; ){
 8122:       printf("Pathr |%s|\n",pathr);
 8123:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 8124:       printf("val= |%s| pathr=%s\n",val,pathr);
 8125:       strcpy (pathtot, val);
 8126:       if(pathr[0] == '\0') break; /* Dirty */
 8127:     }
 8128:   }
 8129:   else{
 8130:     strcpy(pathtot,argv[1]);
 8131:   }
 8132:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 8133:   /*cygwin_split_path(pathtot,path,optionfile);
 8134:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 8135:   /* cutv(path,optionfile,pathtot,'\\');*/
 8136: 
 8137:   /* Split argv[0], imach program to get pathimach */
 8138:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 8139:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8140:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8141:  /*   strcpy(pathimach,argv[0]); */
 8142:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 8143:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 8144:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 8145: #ifdef WIN32
 8146:   _chdir(path); /* Can be a relative path */
 8147:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 8148: #else
 8149:   chdir(path); /* Can be a relative path */
 8150:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 8151: #endif
 8152:   printf("Current directory %s!\n",pathcd);
 8153:   strcpy(command,"mkdir ");
 8154:   strcat(command,optionfilefiname);
 8155:   if((outcmd=system(command)) != 0){
 8156:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 8157:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 8158:     /* fclose(ficlog); */
 8159: /*     exit(1); */
 8160:   }
 8161: /*   if((imk=mkdir(optionfilefiname))<0){ */
 8162: /*     perror("mkdir"); */
 8163: /*   } */
 8164: 
 8165:   /*-------- arguments in the command line --------*/
 8166: 
 8167:   /* Main Log file */
 8168:   strcat(filelog, optionfilefiname);
 8169:   strcat(filelog,".log");    /* */
 8170:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 8171:     printf("Problem with logfile %s\n",filelog);
 8172:     goto end;
 8173:   }
 8174:   fprintf(ficlog,"Log filename:%s\n",filelog);
 8175:   fprintf(ficlog,"Version %s %s",version,fullversion);
 8176:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 8177:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 8178:  path=%s \n\
 8179:  optionfile=%s\n\
 8180:  optionfilext=%s\n\
 8181:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 8182: 
 8183:   syscompilerinfo(1);
 8184: 
 8185:   printf("Local time (at start):%s",strstart);
 8186:   fprintf(ficlog,"Local time (at start): %s",strstart);
 8187:   fflush(ficlog);
 8188: /*   (void) gettimeofday(&curr_time,&tzp); */
 8189: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 8190: 
 8191:   /* */
 8192:   strcpy(fileres,"r");
 8193:   strcat(fileres, optionfilefiname);
 8194:   strcat(fileresu, optionfilefiname); /* Without r in front */
 8195:   strcat(fileres,".txt");    /* Other files have txt extension */
 8196:   strcat(fileresu,".txt");    /* Other files have txt extension */
 8197: 
 8198:   /* Main ---------arguments file --------*/
 8199: 
 8200:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 8201:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8202:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8203:     fflush(ficlog);
 8204:     /* goto end; */
 8205:     exit(70); 
 8206:   }
 8207: 
 8208: 
 8209: 
 8210:   strcpy(filereso,"o");
 8211:   strcat(filereso,fileresu);
 8212:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 8213:     printf("Problem with Output resultfile: %s\n", filereso);
 8214:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 8215:     fflush(ficlog);
 8216:     goto end;
 8217:   }
 8218: 
 8219:   /* Reads comments: lines beginning with '#' */
 8220:   numlinepar=0;
 8221: 
 8222:     /* First parameter line */
 8223:   while(fgets(line, MAXLINE, ficpar)) {
 8224:     /* If line starts with a # it is a comment */
 8225:     if (line[0] == '#') {
 8226:       numlinepar++;
 8227:       fputs(line,stdout);
 8228:       fputs(line,ficparo);
 8229:       fputs(line,ficlog);
 8230:       continue;
 8231:     }else
 8232:       break;
 8233:   }
 8234:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 8235: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 8236:     if (num_filled != 5) {
 8237:       printf("Should be 5 parameters\n");
 8238:     }
 8239:     numlinepar++;
 8240:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 8241:   }
 8242:   /* Second parameter line */
 8243:   while(fgets(line, MAXLINE, ficpar)) {
 8244:     /* If line starts with a # it is a comment */
 8245:     if (line[0] == '#') {
 8246:       numlinepar++;
 8247:       fputs(line,stdout);
 8248:       fputs(line,ficparo);
 8249:       fputs(line,ficlog);
 8250:       continue;
 8251:     }else
 8252:       break;
 8253:   }
 8254:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
 8255: 			&ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 8256:     if (num_filled != 8) {
 8257:       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");
 8258:       printf("but line=%s\n",line);
 8259:     }
 8260:     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);
 8261:   }
 8262:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 8263:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 8264:   /* Third parameter line */
 8265:   while(fgets(line, MAXLINE, ficpar)) {
 8266:     /* If line starts with a # it is a comment */
 8267:     if (line[0] == '#') {
 8268:       numlinepar++;
 8269:       fputs(line,stdout);
 8270:       fputs(line,ficparo);
 8271:       fputs(line,ficlog);
 8272:       continue;
 8273:     }else
 8274:       break;
 8275:   }
 8276:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 8277:     if (num_filled == 0)
 8278:             model[0]='\0';
 8279:     else if (num_filled != 1){
 8280:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8281:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8282:       model[0]='\0';
 8283:       goto end;
 8284:     }
 8285:     else{
 8286:       if (model[0]=='+'){
 8287: 	for(i=1; i<=strlen(model);i++)
 8288: 	  modeltemp[i-1]=model[i];
 8289: 	strcpy(model,modeltemp); 
 8290:       }
 8291:     }
 8292:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 8293:     printf("model=1+age+%s\n",model);fflush(stdout);
 8294:   }
 8295:   /* 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); */
 8296:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 8297:   /* 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); */
 8298:   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);
 8299:   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);
 8300:   fflush(ficlog);
 8301:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 8302:   if(model[0]=='#'){
 8303:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 8304:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 8305:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 8306:     if(mle != -1){
 8307:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 8308:       exit(1);
 8309:     }
 8310:   }
 8311:   while((c=getc(ficpar))=='#' && c!= EOF){
 8312:     ungetc(c,ficpar);
 8313:     fgets(line, MAXLINE, ficpar);
 8314:     numlinepar++;
 8315:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 8316:       z[0]=line[1];
 8317:     }
 8318:     /* printf("****line [1] = %c \n",line[1]); */
 8319:     fputs(line, stdout);
 8320:     //puts(line);
 8321:     fputs(line,ficparo);
 8322:     fputs(line,ficlog);
 8323:   }
 8324:   ungetc(c,ficpar);
 8325: 
 8326:    
 8327:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 8328:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 8329:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 8330:      v1+v2*age+v2*v3 makes cptcovn = 3
 8331:   */
 8332:   if (strlen(model)>1) 
 8333:     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*/
 8334:   else
 8335:     ncovmodel=2; /* Constant and age */
 8336:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 8337:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 8338:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 8339:     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);
 8340:     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);
 8341:     fflush(stdout);
 8342:     fclose (ficlog);
 8343:     goto end;
 8344:   }
 8345:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8346:   delti=delti3[1][1];
 8347:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 8348:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 8349:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8350:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8351:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8352:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 8353:     fclose (ficparo);
 8354:     fclose (ficlog);
 8355:     goto end;
 8356:     exit(0);
 8357:   }
 8358:   else if(mle==-3) { /* Main Wizard */
 8359:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8360:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8361:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8362:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8363:     matcov=matrix(1,npar,1,npar);
 8364:     hess=matrix(1,npar,1,npar);
 8365:   }
 8366:   else{
 8367:     /* Read guessed parameters */
 8368:     /* Reads comments: lines beginning with '#' */
 8369:     while((c=getc(ficpar))=='#' && c!= EOF){
 8370:       ungetc(c,ficpar);
 8371:       fgets(line, MAXLINE, ficpar);
 8372:       numlinepar++;
 8373:       fputs(line,stdout);
 8374:       fputs(line,ficparo);
 8375:       fputs(line,ficlog);
 8376:     }
 8377:     ungetc(c,ficpar);
 8378:     
 8379:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8380:     for(i=1; i <=nlstate; i++){
 8381:       j=0;
 8382:       for(jj=1; jj <=nlstate+ndeath; jj++){
 8383: 	if(jj==i) continue;
 8384: 	j++;
 8385: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 8386: 	if ((i1 != i) || (j1 != jj)){
 8387: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 8388: It might be a problem of design; if ncovcol and the model are correct\n \
 8389: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 8390: 	  exit(1);
 8391: 	}
 8392: 	fprintf(ficparo,"%1d%1d",i1,j1);
 8393: 	if(mle==1)
 8394: 	  printf("%1d%1d",i,jj);
 8395: 	fprintf(ficlog,"%1d%1d",i,jj);
 8396: 	for(k=1; k<=ncovmodel;k++){
 8397: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 8398: 	  if(mle==1){
 8399: 	    printf(" %lf",param[i][j][k]);
 8400: 	    fprintf(ficlog," %lf",param[i][j][k]);
 8401: 	  }
 8402: 	  else
 8403: 	    fprintf(ficlog," %lf",param[i][j][k]);
 8404: 	  fprintf(ficparo," %lf",param[i][j][k]);
 8405: 	}
 8406: 	fscanf(ficpar,"\n");
 8407: 	numlinepar++;
 8408: 	if(mle==1)
 8409: 	  printf("\n");
 8410: 	fprintf(ficlog,"\n");
 8411: 	fprintf(ficparo,"\n");
 8412:       }
 8413:     }  
 8414:     fflush(ficlog);
 8415: 
 8416:     /* Reads scales values */
 8417:     p=param[1][1];
 8418:     
 8419:     /* Reads comments: lines beginning with '#' */
 8420:     while((c=getc(ficpar))=='#' && c!= EOF){
 8421:       ungetc(c,ficpar);
 8422:       fgets(line, MAXLINE, ficpar);
 8423:       numlinepar++;
 8424:       fputs(line,stdout);
 8425:       fputs(line,ficparo);
 8426:       fputs(line,ficlog);
 8427:     }
 8428:     ungetc(c,ficpar);
 8429: 
 8430:     for(i=1; i <=nlstate; i++){
 8431:       for(j=1; j <=nlstate+ndeath-1; j++){
 8432: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 8433: 	if ( (i1-i) * (j1-j) != 0){
 8434: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 8435: 	  exit(1);
 8436: 	}
 8437: 	printf("%1d%1d",i,j);
 8438: 	fprintf(ficparo,"%1d%1d",i1,j1);
 8439: 	fprintf(ficlog,"%1d%1d",i1,j1);
 8440: 	for(k=1; k<=ncovmodel;k++){
 8441: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 8442: 	  printf(" %le",delti3[i][j][k]);
 8443: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 8444: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 8445: 	}
 8446: 	fscanf(ficpar,"\n");
 8447: 	numlinepar++;
 8448: 	printf("\n");
 8449: 	fprintf(ficparo,"\n");
 8450: 	fprintf(ficlog,"\n");
 8451:       }
 8452:     }
 8453:     fflush(ficlog);
 8454: 
 8455:     /* Reads covariance matrix */
 8456:     delti=delti3[1][1];
 8457: 
 8458: 
 8459:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 8460:   
 8461:     /* Reads comments: lines beginning with '#' */
 8462:     while((c=getc(ficpar))=='#' && c!= EOF){
 8463:       ungetc(c,ficpar);
 8464:       fgets(line, MAXLINE, ficpar);
 8465:       numlinepar++;
 8466:       fputs(line,stdout);
 8467:       fputs(line,ficparo);
 8468:       fputs(line,ficlog);
 8469:     }
 8470:     ungetc(c,ficpar);
 8471:   
 8472:     matcov=matrix(1,npar,1,npar);
 8473:     hess=matrix(1,npar,1,npar);
 8474:     for(i=1; i <=npar; i++)
 8475:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 8476:       
 8477:     /* Scans npar lines */
 8478:     for(i=1; i <=npar; i++){
 8479:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
 8480:       if(count != 3){
 8481: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8482: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8483: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8484: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8485: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8486: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8487: 	exit(1);
 8488:       }else
 8489: 	if(mle==1)
 8490: 	  printf("%1d%1d%1d",i1,j1,jk);
 8491:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
 8492:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
 8493:       for(j=1; j <=i; j++){
 8494: 	fscanf(ficpar," %le",&matcov[i][j]);
 8495: 	if(mle==1){
 8496: 	  printf(" %.5le",matcov[i][j]);
 8497: 	}
 8498: 	fprintf(ficlog," %.5le",matcov[i][j]);
 8499: 	fprintf(ficparo," %.5le",matcov[i][j]);
 8500:       }
 8501:       fscanf(ficpar,"\n");
 8502:       numlinepar++;
 8503:       if(mle==1)
 8504: 	printf("\n");
 8505:       fprintf(ficlog,"\n");
 8506:       fprintf(ficparo,"\n");
 8507:     }
 8508:     /* End of read covariance matrix npar lines */
 8509:     for(i=1; i <=npar; i++)
 8510:       for(j=i+1;j<=npar;j++)
 8511: 	matcov[i][j]=matcov[j][i];
 8512:     
 8513:     if(mle==1)
 8514:       printf("\n");
 8515:     fprintf(ficlog,"\n");
 8516:     
 8517:     fflush(ficlog);
 8518:     
 8519:     /*-------- Rewriting parameter file ----------*/
 8520:     strcpy(rfileres,"r");    /* "Rparameterfile */
 8521:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 8522:     strcat(rfileres,".");    /* */
 8523:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 8524:     if((ficres =fopen(rfileres,"w"))==NULL) {
 8525:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 8526:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 8527:     }
 8528:     fprintf(ficres,"#%s\n",version);
 8529:   }    /* End of mle != -3 */
 8530:   
 8531:   /*  Main data
 8532:    */
 8533:   n= lastobs;
 8534:   num=lvector(1,n);
 8535:   moisnais=vector(1,n);
 8536:   annais=vector(1,n);
 8537:   moisdc=vector(1,n);
 8538:   andc=vector(1,n);
 8539:   agedc=vector(1,n);
 8540:   cod=ivector(1,n);
 8541:   weight=vector(1,n);
 8542:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 8543:   mint=matrix(1,maxwav,1,n);
 8544:   anint=matrix(1,maxwav,1,n);
 8545:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 8546:   tab=ivector(1,NCOVMAX);
 8547:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8548:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8549: 
 8550:   /* Reads data from file datafile */
 8551:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 8552:     goto end;
 8553: 
 8554:   /* Calculation of the number of parameters from char model */
 8555:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 8556: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 8557: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 8558: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 8559: 	k=1 Tvar[1]=2 (from V2)
 8560:     */
 8561:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 8562:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 8563:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 8564:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 8565:   */
 8566:   /* For model-covariate k tells which data-covariate to use but
 8567:     because this model-covariate is a construction we invent a new column
 8568:     ncovcol + k1
 8569:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 8570:     Tvar[3=V1*V4]=4+1 etc */
 8571:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 8572:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 8573:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 8574:   */
 8575:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 8576:   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
 8577: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 8578: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 8579:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 8580: 			 4 covariates (3 plus signs)
 8581: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 8582: 		      */  
 8583: 
 8584: /* Main decodemodel */
 8585: 
 8586: 
 8587:   if(decodemodel(model, lastobs) == 1)
 8588:     goto end;
 8589: 
 8590:   if((double)(lastobs-imx)/(double)imx > 1.10){
 8591:     nbwarn++;
 8592:     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); 
 8593:     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); 
 8594:   }
 8595:     /*  if(mle==1){*/
 8596:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 8597:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 8598:   }
 8599: 
 8600:     /*-calculation of age at interview from date of interview and age at death -*/
 8601:   agev=matrix(1,maxwav,1,imx);
 8602: 
 8603:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 8604:     goto end;
 8605: 
 8606: 
 8607:   agegomp=(int)agemin;
 8608:   free_vector(moisnais,1,n);
 8609:   free_vector(annais,1,n);
 8610:   /* free_matrix(mint,1,maxwav,1,n);
 8611:      free_matrix(anint,1,maxwav,1,n);*/
 8612:   /* free_vector(moisdc,1,n); */
 8613:   /* free_vector(andc,1,n); */
 8614:   /* */
 8615:   
 8616:   wav=ivector(1,imx);
 8617:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8618:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8619:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
 8620:   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.*/
 8621:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
 8622:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
 8623:    
 8624:   /* Concatenates waves */
 8625:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 8626:      Death is a valid wave (if date is known).
 8627:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
 8628:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 8629:      and mw[mi+1][i]. dh depends on stepm.
 8630:   */
 8631: 
 8632:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 8633:   /* */
 8634:  
 8635:   free_vector(moisdc,1,n);
 8636:   free_vector(andc,1,n);
 8637: 
 8638:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 8639: 
 8640:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 8641:   ncodemax[1]=1;
 8642:   Ndum =ivector(-1,NCOVMAX);  
 8643:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 8644:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 8645:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 8646:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 8647:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 8648: 
 8649:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 8650:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 8651:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 8652:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 8653:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 8654:    * (currently 0 or 1) in the data.
 8655:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 8656:    * corresponding modality (h,j).
 8657:    */
 8658: 
 8659:   h=0;
 8660: 
 8661: 
 8662:   /*if (cptcovn > 0) */
 8663:       
 8664:  
 8665:   m=pow(2,cptcoveff);
 8666:  
 8667: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 8668: 	   * For k=4 covariates, h goes from 1 to m=2**k
 8669: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 8670:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8671: 	   *     h\k   1     2     3     4
 8672: 	   *______________________________  
 8673: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 8674: 	   *     2     2     1     1     1
 8675: 	   *     3 i=2 1     2     1     1
 8676: 	   *     4     2     2     1     1
 8677: 	   *     5 i=3 1 i=2 1     2     1
 8678: 	   *     6     2     1     2     1
 8679: 	   *     7 i=4 1     2     2     1
 8680: 	   *     8     2     2     2     1
 8681: 	   *     9 i=5 1 i=3 1 i=2 1     2
 8682: 	   *    10     2     1     1     2
 8683: 	   *    11 i=6 1     2     1     2
 8684: 	   *    12     2     2     1     2
 8685: 	   *    13 i=7 1 i=4 1     2     2    
 8686: 	   *    14     2     1     2     2
 8687: 	   *    15 i=8 1     2     2     2
 8688: 	   *    16     2     2     2     2
 8689: 	   */
 8690:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 8691:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 8692:      * and the value of each covariate?
 8693:      * V1=1, V2=1, V3=2, V4=1 ?
 8694:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 8695:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 8696:      * In order to get the real value in the data, we use nbcode
 8697:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 8698:      * We are keeping this crazy system in order to be able (in the future?) 
 8699:      * to have more than 2 values (0 or 1) for a covariate.
 8700:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8701:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 8702:      *              bbbbbbbb
 8703:      *              76543210     
 8704:      *   h-1        00000101 (6-1=5)
 8705:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
 8706:      *           &
 8707:      *     1        00000001 (1)
 8708:      *              00000001        = 1 & ((h-1) >> (k-1))
 8709:      *          +1= 00000010 =2 
 8710:      *
 8711:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 8712:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 8713:      *    >>k'            11
 8714:      *          &   00000001
 8715:      *            = 00000001
 8716:      *      +1    = 00000010=2    =  codtabm(14,3)   
 8717:      * Reverse h=6 and m=16?
 8718:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 8719:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 8720:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 8721:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 8722:      * V3=decodtabm(14,3,2**4)=2
 8723:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 8724:      *(h-1) >> (j-1)    0011 =13 >> 2
 8725:      *          &1 000000001
 8726:      *           = 000000001
 8727:      *         +1= 000000010 =2
 8728:      *                  2211
 8729:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 8730:      *                  V3=2
 8731:      */
 8732: 
 8733:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
 8734:   /*   /\* printf("h=%2d ", h); *\/ */
 8735:   /*    /\* for(k=1; k <=10; k++){ *\/ */
 8736:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
 8737:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
 8738:   /*    /\* } *\/ */
 8739:   /*    /\* printf("\n"); *\/ */
 8740:   /* } */
 8741:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
 8742:   /*   for(i=1; i <=pow(2,cptcoveff-k);i++){ /\* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 *\/  */
 8743:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
 8744:   /* 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
 8745:   /* 	  h++; */
 8746:   /* 	  if (h>m)  */
 8747:   /* 	    h=1; */
 8748:   /* 	  codtab[h][k]=j; */
 8749:   /* 	  /\* codtab[12][3]=1; *\/ */
 8750:   /* 	  /\*codtab[h][Tvar[k]]=j;*\/ */
 8751:   /* 	  /\* printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]); *\/ */
 8752:   /* 	}  */
 8753:   /*     } */
 8754:   /*   } */
 8755:   /* }  */
 8756:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 8757:      codtab[1][2]=1;codtab[2][2]=2; */
 8758:   /* for(i=1; i <=m ;i++){  */
 8759:   /*    for(k=1; k <=cptcovn; k++){ */
 8760:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
 8761:   /*    } */
 8762:   /*    printf("\n"); */
 8763:   /* } */
 8764:   /*   scanf("%d",i);*/
 8765: 
 8766:  free_ivector(Ndum,-1,NCOVMAX);
 8767: 
 8768: 
 8769:     
 8770:   /* Initialisation of ----------- gnuplot -------------*/
 8771:   strcpy(optionfilegnuplot,optionfilefiname);
 8772:   if(mle==-3)
 8773:     strcat(optionfilegnuplot,"-MORT_");
 8774:   strcat(optionfilegnuplot,".gp");
 8775: 
 8776:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 8777:     printf("Problem with file %s",optionfilegnuplot);
 8778:   }
 8779:   else{
 8780:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 8781:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 8782:     //fprintf(ficgp,"set missing 'NaNq'\n");
 8783:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 8784:   }
 8785:   /*  fclose(ficgp);*/
 8786: 
 8787: 
 8788:   /* Initialisation of --------- index.htm --------*/
 8789: 
 8790:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 8791:   if(mle==-3)
 8792:     strcat(optionfilehtm,"-MORT_");
 8793:   strcat(optionfilehtm,".htm");
 8794:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 8795:     printf("Problem with %s \n",optionfilehtm);
 8796:     exit(0);
 8797:   }
 8798: 
 8799:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 8800:   strcat(optionfilehtmcov,"-cov.htm");
 8801:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 8802:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 8803:   }
 8804:   else{
 8805:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 8806: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8807: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 8808: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 8809:   }
 8810: 
 8811:   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>  \
 8812: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8813: <font size=\"2\">IMaCh-%s <br> %s</font> \
 8814: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8815: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 8816: \n\
 8817: <hr  size=\"2\" color=\"#EC5E5E\">\
 8818:  <ul><li><h4>Parameter files</h4>\n\
 8819:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 8820:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 8821:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 8822:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 8823:  - Date and time at start: %s</ul>\n",\
 8824: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 8825: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 8826: 	  fileres,fileres,\
 8827: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 8828:   fflush(fichtm);
 8829: 
 8830:   strcpy(pathr,path);
 8831:   strcat(pathr,optionfilefiname);
 8832: #ifdef WIN32
 8833:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 8834: #else
 8835:   chdir(optionfilefiname); /* Move to directory named optionfile */
 8836: #endif
 8837: 	  
 8838:   
 8839:   /* Calculates basic frequencies. Computes observed prevalence at single age
 8840:      and prints on file fileres'p'. */
 8841:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
 8842: 	      firstpass, lastpass,  stepm,  weightopt, model);
 8843: 
 8844:   fprintf(fichtm,"\n");
 8845:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 8846: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 8847: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 8848: 	  imx,agemin,agemax,jmin,jmax,jmean);
 8849:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8850:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8851:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8852:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8853:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 8854: 
 8855:   /* For Powell, parameters are in a vector p[] starting at p[1]
 8856:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 8857:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 8858: 
 8859:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 8860:   /* For mortality only */
 8861:   if (mle==-3){
 8862:     ximort=matrix(1,NDIM,1,NDIM); 
 8863:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 8864:     cens=ivector(1,n);
 8865:     ageexmed=vector(1,n);
 8866:     agecens=vector(1,n);
 8867:     dcwave=ivector(1,n);
 8868:  
 8869:     for (i=1; i<=imx; i++){
 8870:       dcwave[i]=-1;
 8871:       for (m=firstpass; m<=lastpass; m++)
 8872: 				if (s[m][i]>nlstate) {
 8873: 					dcwave[i]=m;
 8874: 					/*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 8875: 					break;
 8876: 				}
 8877:     }
 8878: 		
 8879:     for (i=1; i<=imx; i++) {
 8880:       if (wav[i]>0){
 8881: 				ageexmed[i]=agev[mw[1][i]][i];
 8882: 				j=wav[i];
 8883: 				agecens[i]=1.; 
 8884: 				
 8885: 				if (ageexmed[i]> 1 && wav[i] > 0){
 8886: 					agecens[i]=agev[mw[j][i]][i];
 8887: 					cens[i]= 1;
 8888: 				}else if (ageexmed[i]< 1) 
 8889: 					cens[i]= -1;
 8890: 				if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 8891: 					cens[i]=0 ;
 8892:       }
 8893:       else cens[i]=-1;
 8894:     }
 8895:     
 8896:     for (i=1;i<=NDIM;i++) {
 8897:       for (j=1;j<=NDIM;j++)
 8898: 				ximort[i][j]=(i == j ? 1.0 : 0.0);
 8899:     }
 8900:     
 8901:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 8902:     /*printf("%lf %lf", p[1], p[2]);*/
 8903:     
 8904:     
 8905: #ifdef GSL
 8906:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 8907: #else
 8908:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 8909: #endif
 8910:     strcpy(filerespow,"POW-MORT_"); 
 8911:     strcat(filerespow,fileresu);
 8912:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 8913:       printf("Problem with resultfile: %s\n", filerespow);
 8914:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 8915:     }
 8916: #ifdef GSL
 8917:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 8918: #else
 8919:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 8920: #endif
 8921:     /*  for (i=1;i<=nlstate;i++)
 8922: 	for(j=1;j<=nlstate+ndeath;j++)
 8923: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 8924:     */
 8925:     fprintf(ficrespow,"\n");
 8926: #ifdef GSL
 8927:     /* gsl starts here */ 
 8928:     T = gsl_multimin_fminimizer_nmsimplex;
 8929:     gsl_multimin_fminimizer *sfm = NULL;
 8930:     gsl_vector *ss, *x;
 8931:     gsl_multimin_function minex_func;
 8932: 
 8933:     /* Initial vertex size vector */
 8934:     ss = gsl_vector_alloc (NDIM);
 8935:     
 8936:     if (ss == NULL){
 8937:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 8938:     }
 8939:     /* Set all step sizes to 1 */
 8940:     gsl_vector_set_all (ss, 0.001);
 8941: 
 8942:     /* Starting point */
 8943:     
 8944:     x = gsl_vector_alloc (NDIM);
 8945:     
 8946:     if (x == NULL){
 8947:       gsl_vector_free(ss);
 8948:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 8949:     }
 8950:   
 8951:     /* Initialize method and iterate */
 8952:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 8953:     /*     gsl_vector_set(x, 0, 0.0268); */
 8954:     /*     gsl_vector_set(x, 1, 0.083); */
 8955:     gsl_vector_set(x, 0, p[1]);
 8956:     gsl_vector_set(x, 1, p[2]);
 8957: 
 8958:     minex_func.f = &gompertz_f;
 8959:     minex_func.n = NDIM;
 8960:     minex_func.params = (void *)&p; /* ??? */
 8961:     
 8962:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 8963:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 8964:     
 8965:     printf("Iterations beginning .....\n\n");
 8966:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 8967: 
 8968:     iteri=0;
 8969:     while (rval == GSL_CONTINUE){
 8970:       iteri++;
 8971:       status = gsl_multimin_fminimizer_iterate(sfm);
 8972:       
 8973:       if (status) printf("error: %s\n", gsl_strerror (status));
 8974:       fflush(0);
 8975:       
 8976:       if (status) 
 8977:         break;
 8978:       
 8979:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 8980:       ssval = gsl_multimin_fminimizer_size (sfm);
 8981:       
 8982:       if (rval == GSL_SUCCESS)
 8983:         printf ("converged to a local maximum at\n");
 8984:       
 8985:       printf("%5d ", iteri);
 8986:       for (it = 0; it < NDIM; it++){
 8987: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 8988:       }
 8989:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 8990:     }
 8991:     
 8992:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 8993:     
 8994:     gsl_vector_free(x); /* initial values */
 8995:     gsl_vector_free(ss); /* inital step size */
 8996:     for (it=0; it<NDIM; it++){
 8997:       p[it+1]=gsl_vector_get(sfm->x,it);
 8998:       fprintf(ficrespow," %.12lf", p[it]);
 8999:     }
 9000:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 9001: #endif
 9002: #ifdef POWELL
 9003:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 9004: #endif  
 9005:     fclose(ficrespow);
 9006:     
 9007:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
 9008: 
 9009:     for(i=1; i <=NDIM; i++)
 9010:       for(j=i+1;j<=NDIM;j++)
 9011: 	matcov[i][j]=matcov[j][i];
 9012:     
 9013:     printf("\nCovariance matrix\n ");
 9014:     fprintf(ficlog,"\nCovariance matrix\n ");
 9015:     for(i=1; i <=NDIM; i++) {
 9016:       for(j=1;j<=NDIM;j++){ 
 9017: 	printf("%f ",matcov[i][j]);
 9018: 	fprintf(ficlog,"%f ",matcov[i][j]);
 9019:       }
 9020:       printf("\n ");  fprintf(ficlog,"\n ");
 9021:     }
 9022:     
 9023:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 9024:     for (i=1;i<=NDIM;i++) {
 9025:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9026:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9027:     }
 9028:     lsurv=vector(1,AGESUP);
 9029:     lpop=vector(1,AGESUP);
 9030:     tpop=vector(1,AGESUP);
 9031:     lsurv[agegomp]=100000;
 9032:     
 9033:     for (k=agegomp;k<=AGESUP;k++) {
 9034:       agemortsup=k;
 9035:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 9036:     }
 9037:     
 9038:     for (k=agegomp;k<agemortsup;k++)
 9039:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 9040:     
 9041:     for (k=agegomp;k<agemortsup;k++){
 9042:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 9043:       sumlpop=sumlpop+lpop[k];
 9044:     }
 9045:     
 9046:     tpop[agegomp]=sumlpop;
 9047:     for (k=agegomp;k<(agemortsup-3);k++){
 9048:       /*  tpop[k+1]=2;*/
 9049:       tpop[k+1]=tpop[k]-lpop[k];
 9050:     }
 9051:     
 9052:     
 9053:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 9054:     for (k=agegomp;k<(agemortsup-2);k++) 
 9055:       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]);
 9056:     
 9057:     
 9058:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9059:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
 9060:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9061: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9062: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9063:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9064: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9065: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9066:     }else
 9067:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 9068:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
 9069: 		     stepm, weightopt,\
 9070: 		     model,imx,p,matcov,agemortsup);
 9071:     
 9072:     free_vector(lsurv,1,AGESUP);
 9073:     free_vector(lpop,1,AGESUP);
 9074:     free_vector(tpop,1,AGESUP);
 9075: #ifdef GSL
 9076:     free_ivector(cens,1,n);
 9077:     free_vector(agecens,1,n);
 9078:     free_ivector(dcwave,1,n);
 9079:     free_matrix(ximort,1,NDIM,1,NDIM);
 9080: #endif
 9081:   } /* Endof if mle==-3 mortality only */
 9082:   /* Standard  */
 9083:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
 9084:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9085:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9086:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9087:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9088:     for (k=1; k<=npar;k++)
 9089:       printf(" %d %8.5f",k,p[k]);
 9090:     printf("\n");
 9091:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
 9092:       /* mlikeli uses func not funcone */
 9093:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 9094:     }
 9095:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
 9096:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9097:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9098:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9099:     }
 9100:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
 9101:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9102:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9103:     for (k=1; k<=npar;k++)
 9104:       printf(" %d %8.5f",k,p[k]);
 9105:     printf("\n");
 9106:     
 9107:     /*--------- results files --------------*/
 9108:     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);
 9109:     
 9110:     
 9111:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9112:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9113:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9114:     for(i=1,jk=1; i <=nlstate; i++){
 9115:       for(k=1; k <=(nlstate+ndeath); k++){
 9116: 	if (k != i) {
 9117: 	  printf("%d%d ",i,k);
 9118: 	  fprintf(ficlog,"%d%d ",i,k);
 9119: 	  fprintf(ficres,"%1d%1d ",i,k);
 9120: 	  for(j=1; j <=ncovmodel; j++){
 9121: 	    printf("%12.7f ",p[jk]);
 9122: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 9123: 	    fprintf(ficres,"%12.7f ",p[jk]);
 9124: 	    jk++; 
 9125: 	  }
 9126: 	  printf("\n");
 9127: 	  fprintf(ficlog,"\n");
 9128: 	  fprintf(ficres,"\n");
 9129: 	}
 9130:       }
 9131:     }
 9132:     if(mle != 0){
 9133:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
 9134:       ftolhess=ftol; /* Usually correct */
 9135:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
 9136:       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");
 9137:       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");
 9138:       for(i=1,jk=1; i <=nlstate; i++){
 9139: 	for(k=1; k <=(nlstate+ndeath); k++){
 9140: 	  if (k != i) {
 9141: 	    printf("%d%d ",i,k);
 9142: 	    fprintf(ficlog,"%d%d ",i,k);
 9143: 	    for(j=1; j <=ncovmodel; j++){
 9144: 	      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]));
 9145: 	      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]));
 9146: 	      jk++; 
 9147: 	    }
 9148: 	    printf("\n");
 9149: 	    fprintf(ficlog,"\n");
 9150: 	  }
 9151: 	}
 9152:       }
 9153:     } /* end of hesscov and Wald tests */
 9154: 
 9155:     /*  */
 9156:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 9157:     printf("# Scales (for hessian or gradient estimation)\n");
 9158:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 9159:     for(i=1,jk=1; i <=nlstate; i++){
 9160:       for(j=1; j <=nlstate+ndeath; j++){
 9161: 	if (j!=i) {
 9162: 	  fprintf(ficres,"%1d%1d",i,j);
 9163: 	  printf("%1d%1d",i,j);
 9164: 	  fprintf(ficlog,"%1d%1d",i,j);
 9165: 	  for(k=1; k<=ncovmodel;k++){
 9166: 	    printf(" %.5e",delti[jk]);
 9167: 	    fprintf(ficlog," %.5e",delti[jk]);
 9168: 	    fprintf(ficres," %.5e",delti[jk]);
 9169: 	    jk++;
 9170: 	  }
 9171: 	  printf("\n");
 9172: 	  fprintf(ficlog,"\n");
 9173: 	  fprintf(ficres,"\n");
 9174: 	}
 9175:       }
 9176:     }
 9177:     
 9178:     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");
 9179:     if(mle >= 1) /* To big for the screen */
 9180:       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");
 9181:     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");
 9182:     /* # 121 Var(a12)\n\ */
 9183:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 9184:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 9185:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 9186:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 9187:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 9188:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 9189:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 9190:     
 9191:     
 9192:     /* Just to have a covariance matrix which will be more understandable
 9193:        even is we still don't want to manage dictionary of variables
 9194:     */
 9195:     for(itimes=1;itimes<=2;itimes++){
 9196:       jj=0;
 9197:       for(i=1; i <=nlstate; i++){
 9198: 	for(j=1; j <=nlstate+ndeath; j++){
 9199: 	  if(j==i) continue;
 9200: 	  for(k=1; k<=ncovmodel;k++){
 9201: 	    jj++;
 9202: 	    ca[0]= k+'a'-1;ca[1]='\0';
 9203: 	    if(itimes==1){
 9204: 	      if(mle>=1)
 9205: 		printf("#%1d%1d%d",i,j,k);
 9206: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 9207: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 9208: 	    }else{
 9209: 	      if(mle>=1)
 9210: 		printf("%1d%1d%d",i,j,k);
 9211: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 9212: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 9213: 	    }
 9214: 	    ll=0;
 9215: 	    for(li=1;li <=nlstate; li++){
 9216: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 9217: 		if(lj==li) continue;
 9218: 		for(lk=1;lk<=ncovmodel;lk++){
 9219: 		  ll++;
 9220: 		  if(ll<=jj){
 9221: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 9222: 		    if(ll<jj){
 9223: 		      if(itimes==1){
 9224: 			if(mle>=1)
 9225: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9226: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9227: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9228: 		      }else{
 9229: 			if(mle>=1)
 9230: 			  printf(" %.5e",matcov[jj][ll]); 
 9231: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 9232: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 9233: 		      }
 9234: 		    }else{
 9235: 		      if(itimes==1){
 9236: 			if(mle>=1)
 9237: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 9238: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 9239: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 9240: 		      }else{
 9241: 			if(mle>=1)
 9242: 			  printf(" %.7e",matcov[jj][ll]); 
 9243: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
 9244: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
 9245: 		      }
 9246: 		    }
 9247: 		  }
 9248: 		} /* end lk */
 9249: 	      } /* end lj */
 9250: 	    } /* end li */
 9251: 	    if(mle>=1)
 9252: 	      printf("\n");
 9253: 	    fprintf(ficlog,"\n");
 9254: 	    fprintf(ficres,"\n");
 9255: 	    numlinepar++;
 9256: 	  } /* end k*/
 9257: 	} /*end j */
 9258:       } /* end i */
 9259:     } /* end itimes */
 9260:     
 9261:     fflush(ficlog);
 9262:     fflush(ficres);
 9263:       while(fgets(line, MAXLINE, ficpar)) {
 9264:     /* If line starts with a # it is a comment */
 9265:     if (line[0] == '#') {
 9266:       numlinepar++;
 9267:       fputs(line,stdout);
 9268:       fputs(line,ficparo);
 9269:       fputs(line,ficlog);
 9270:       continue;
 9271:     }else
 9272:       break;
 9273:   }
 9274: 
 9275:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
 9276:     /*   ungetc(c,ficpar); */
 9277:     /*   fgets(line, MAXLINE, ficpar); */
 9278:     /*   fputs(line,stdout); */
 9279:     /*   fputs(line,ficparo); */
 9280:     /* } */
 9281:     /* ungetc(c,ficpar); */
 9282:     
 9283:     estepm=0;
 9284:     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){
 9285: 
 9286:     if (num_filled != 6) {
 9287:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
 9288:       printf("but line=%s\n",line);
 9289:       goto end;
 9290:     }
 9291:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
 9292:   }
 9293:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9294:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9295: 
 9296:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
 9297:     if (estepm==0 || estepm < stepm) estepm=stepm;
 9298:     if (fage <= 2) {
 9299:       bage = ageminpar;
 9300:       fage = agemaxpar;
 9301:     }
 9302:     
 9303:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 9304:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9305:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9306: 
 9307:     /* Other stuffs, more or less useful */    
 9308:     while((c=getc(ficpar))=='#' && c!= EOF){
 9309:       ungetc(c,ficpar);
 9310:       fgets(line, MAXLINE, ficpar);
 9311:       fputs(line,stdout);
 9312:       fputs(line,ficparo);
 9313:     }
 9314:     ungetc(c,ficpar);
 9315:     
 9316:     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);
 9317:     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);
 9318:     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);
 9319:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 9320:     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);
 9321:     
 9322:     while((c=getc(ficpar))=='#' && c!= EOF){
 9323:       ungetc(c,ficpar);
 9324:       fgets(line, MAXLINE, ficpar);
 9325:       fputs(line,stdout);
 9326:       fputs(line,ficparo);
 9327:     }
 9328:     ungetc(c,ficpar);
 9329:     
 9330:     
 9331:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 9332:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 9333:     
 9334:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 9335:     fprintf(ficlog,"pop_based=%d\n",popbased);
 9336:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 9337:     fprintf(ficres,"pop_based=%d\n",popbased);   
 9338:     
 9339:     while((c=getc(ficpar))=='#' && c!= EOF){
 9340:       ungetc(c,ficpar);
 9341:       fgets(line, MAXLINE, ficpar);
 9342:       fputs(line,stdout);
 9343:       fputs(line,ficparo);
 9344:     }
 9345:     ungetc(c,ficpar);
 9346:     
 9347:     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);
 9348:     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);
 9349:     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);
 9350:     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);
 9351:     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);
 9352:     /* day and month of proj2 are not used but only year anproj2.*/
 9353:     
 9354:     while((c=getc(ficpar))=='#' && c!= EOF){
 9355:       ungetc(c,ficpar);
 9356:       fgets(line, MAXLINE, ficpar);
 9357:       fputs(line,stdout);
 9358:       fputs(line,ficparo);
 9359:     }
 9360:     ungetc(c,ficpar);
 9361:     
 9362:     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);
 9363:     fscanf(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);
 9364:     fscanf(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);
 9365:     fscanf(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);
 9366:     /* day and month of proj2 are not used but only year anproj2.*/
 9367:     
 9368:     
 9369:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 9370:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 9371:     
 9372:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9373:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
 9374:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9375: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9376: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9377:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9378: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9379: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9380:     }else
 9381:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
 9382:     
 9383:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
 9384: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
 9385: 		 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
 9386:       
 9387:    /*------------ free_vector  -------------*/
 9388:    /*  chdir(path); */
 9389:  
 9390:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
 9391:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
 9392:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
 9393:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
 9394:     free_lvector(num,1,n);
 9395:     free_vector(agedc,1,n);
 9396:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 9397:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 9398:     fclose(ficparo);
 9399:     fclose(ficres);
 9400: 
 9401: 
 9402:     /* Other results (useful)*/
 9403: 
 9404: 
 9405:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9406:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 9407:     prlim=matrix(1,nlstate,1,nlstate);
 9408:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 9409:     fclose(ficrespl);
 9410: 
 9411:     /*------------- h Pij x at various ages ------------*/
 9412:     /*#include "hpijx.h"*/
 9413:     hPijx(p, bage, fage);
 9414:     fclose(ficrespij);
 9415: 
 9416: 		ncovcombmax=  pow(2,cptcoveff);
 9417:   /*-------------- Variance of one-step probabilities---*/
 9418:     k=1;
 9419:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 9420: 
 9421: 		/* Prevalence for each covariates in probs[age][status][cov] */
 9422:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9423:     for(i=1;i<=AGESUP;i++)
 9424:       for(j=1;j<=nlstate;j++)
 9425: 				for(k=1;k<=ncovcombmax;k++)
 9426: 					probs[i][j][k]=0.;
 9427: 		prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 9428: 		if (mobilav!=0 ||mobilavproj !=0 ) {
 9429: 			mobaverage= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9430: 			if (mobilav!=0) {
 9431: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
 9432: 					fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 9433: 					printf(" Error in movingaverage mobilav=%d\n",mobilav);
 9434: 				}
 9435: 			}
 9436: 			/* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
 9437: 			/* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 9438: 			else if (mobilavproj !=0) {
 9439: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
 9440: 					fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9441: 					printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9442: 				}
 9443: 			}
 9444: 		}/* end if moving average */
 9445: 
 9446:     /*---------- Forecasting ------------------*/
 9447:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 9448:     if(prevfcast==1){
 9449:       /*    if(stepm ==1){*/
 9450:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 9451:     }
 9452:     if(backcast==1){
 9453: 		ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9454: 		ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9455: 		ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
 9456: 
 9457: 			/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9458: 			/*#include "prevlim.h"*/  /* Use ficresplb, ficlog */
 9459: 			bprlim=matrix(1,nlstate,1,nlstate);
 9460: 			back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
 9461: 			fclose(ficresplb);
 9462: 
 9463: 			hBijx(p, bage, fage, mobaverage);
 9464: 			fclose(ficrespijb);
 9465: 			free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9466: 
 9467:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
 9468: 			free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9469: 			free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9470: 			free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9471: 		}
 9472:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 9473:   /* if (mobilavproj!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 9474: 
 9475:     /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 9476:     /*      }  */
 9477:     /*      else{ */
 9478:     /*        erreur=108; */
 9479:     /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 9480:     /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 9481:     /*      } */
 9482:     
 9483:  
 9484:     /* ------ Other prevalence ratios------------ */
 9485: 
 9486:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 9487: 
 9488:     /* prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 9489:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
 9490: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 9491:     */
 9492:     free_ivector(wav,1,imx);
 9493:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
 9494:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
 9495:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
 9496: 		
 9497: 		
 9498: 		/*   if (mobilav!=0) { */
 9499: 		/*     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 9500: 		/*     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 9501: 		/* fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 9502: 		/* printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 9503: 		/*     } */
 9504: 		/*   } */
 9505: 		
 9506: 		
 9507:     /*---------- Health expectancies, no variances ------------*/
 9508: 		
 9509:     strcpy(filerese,"E_");
 9510:     strcat(filerese,fileresu);
 9511:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 9512:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9513:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9514:     }
 9515:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
 9516:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
 9517:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9518:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9519: 		
 9520:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9521: 			fprintf(ficreseij,"\n#****** ");
 9522: 			for(j=1;j<=cptcoveff;j++) {
 9523: 				fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9524: 			}
 9525: 			fprintf(ficreseij,"******\n");
 9526: 			
 9527: 			eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9528: 			oldm=oldms;savm=savms;
 9529: 			evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 9530:       
 9531: 			free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9532:       /*}*/
 9533:     }
 9534:     fclose(ficreseij);
 9535:     printf("done evsij\n");fflush(stdout);
 9536:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
 9537: 		
 9538:     /*---------- Health expectancies and variances ------------*/
 9539: 		
 9540: 		
 9541:     strcpy(filerest,"T_");
 9542:     strcat(filerest,fileresu);
 9543:     if((ficrest=fopen(filerest,"w"))==NULL) {
 9544:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 9545:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 9546:     }
 9547:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
 9548:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
 9549: 		
 9550: 
 9551:     strcpy(fileresstde,"STDE_");
 9552:     strcat(fileresstde,fileresu);
 9553:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 9554:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9555:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9556:     }
 9557:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9558:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9559: 
 9560:     strcpy(filerescve,"CVE_");
 9561:     strcat(filerescve,fileresu);
 9562:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 9563:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9564:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9565:     }
 9566:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9567:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9568: 
 9569:     strcpy(fileresv,"V_");
 9570:     strcat(fileresv,fileresu);
 9571:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 9572:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 9573:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 9574:     }
 9575:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
 9576:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
 9577: 
 9578:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9579:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9580:           
 9581:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9582:       fprintf(ficrest,"\n#****** ");
 9583:       for(j=1;j<=cptcoveff;j++) 
 9584: 				fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9585:       fprintf(ficrest,"******\n");
 9586:       
 9587:       fprintf(ficresstdeij,"\n#****** ");
 9588:       fprintf(ficrescveij,"\n#****** ");
 9589:       for(j=1;j<=cptcoveff;j++) {
 9590: 				fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9591: 				fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9592:       }
 9593:       fprintf(ficresstdeij,"******\n");
 9594:       fprintf(ficrescveij,"******\n");
 9595:       
 9596:       fprintf(ficresvij,"\n#****** ");
 9597:       for(j=1;j<=cptcoveff;j++) 
 9598: 				fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9599:       fprintf(ficresvij,"******\n");
 9600:       
 9601:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9602:       oldm=oldms;savm=savms;
 9603:       printf(" cvevsij %d, ",k);
 9604:       fprintf(ficlog, " cvevsij %d, ",k);
 9605:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
 9606:       printf(" end cvevsij \n ");
 9607:       fprintf(ficlog, " end cvevsij \n ");
 9608:       
 9609:       /*
 9610:        */
 9611:       /* goto endfree; */
 9612:       
 9613:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9614:       pstamp(ficrest);
 9615:       
 9616:       
 9617:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 9618: 				oldm=oldms;savm=savms; /* ZZ Segmentation fault */
 9619: 				cptcod= 0; /* To be deleted */
 9620: 				printf("varevsij %d \n",vpopbased);
 9621: 				fprintf(ficlog, "varevsij %d \n",vpopbased);
 9622: 				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 */
 9623: 				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 ");
 9624: 				if(vpopbased==1)
 9625: 					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);
 9626: 				else
 9627: 					fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 9628: 				fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
 9629: 				for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 9630: 				fprintf(ficrest,"\n");
 9631: 				/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
 9632: 				epj=vector(1,nlstate+1);
 9633: 				printf("Computing age specific period (stable) prevalences in each health state \n");
 9634: 				fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
 9635: 				for(age=bage; age <=fage ;age++){
 9636: 					prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
 9637: 					if (vpopbased==1) {
 9638: 						if(mobilav ==0){
 9639: 							for(i=1; i<=nlstate;i++)
 9640: 								prlim[i][i]=probs[(int)age][i][k];
 9641: 						}else{ /* mobilav */ 
 9642: 							for(i=1; i<=nlstate;i++)
 9643: 								prlim[i][i]=mobaverage[(int)age][i][k];
 9644: 						}
 9645: 					}
 9646: 					
 9647: 					fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
 9648: 					/* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
 9649: 					/* printf(" age %4.0f ",age); */
 9650: 					for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 9651: 						for(i=1, epj[j]=0.;i <=nlstate;i++) {
 9652: 							epj[j] += prlim[i][i]*eij[i][j][(int)age];
 9653: 							/*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 9654: 							/* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
 9655: 						}
 9656: 						epj[nlstate+1] +=epj[j];
 9657: 					}
 9658: 					/* printf(" age %4.0f \n",age); */
 9659: 					
 9660: 					for(i=1, vepp=0.;i <=nlstate;i++)
 9661: 						for(j=1;j <=nlstate;j++)
 9662: 							vepp += vareij[i][j][(int)age];
 9663: 					fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 9664: 					for(j=1;j <=nlstate;j++){
 9665: 						fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 9666: 					}
 9667: 					fprintf(ficrest,"\n");
 9668: 				}
 9669:       } /* End vpopbased */
 9670:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9671:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9672:       free_vector(epj,1,nlstate+1);
 9673:       printf("done \n");fflush(stdout);
 9674:       fprintf(ficlog,"done\n");fflush(ficlog);
 9675:       
 9676:       /*}*/
 9677:     } /* End k */
 9678:     free_vector(weight,1,n);
 9679:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 9680:     free_imatrix(s,1,maxwav+1,1,n);
 9681:     free_matrix(anint,1,maxwav,1,n); 
 9682:     free_matrix(mint,1,maxwav,1,n);
 9683:     free_ivector(cod,1,n);
 9684:     free_ivector(tab,1,NCOVMAX);
 9685:     fclose(ficresstdeij);
 9686:     fclose(ficrescveij);
 9687:     fclose(ficresvij);
 9688:     fclose(ficrest);
 9689:     printf("done Health expectancies\n");fflush(stdout);
 9690:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
 9691:     fclose(ficpar);
 9692:   
 9693:     /*------- Variance of period (stable) prevalence------*/   
 9694: 
 9695:     strcpy(fileresvpl,"VPL_");
 9696:     strcat(fileresvpl,fileresu);
 9697:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 9698:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 9699:       exit(0);
 9700:     }
 9701:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
 9702:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
 9703: 
 9704:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9705:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9706:           
 9707:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9708:     	fprintf(ficresvpl,"\n#****** ");
 9709: 			for(j=1;j<=cptcoveff;j++) 
 9710: 				fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9711: 			fprintf(ficresvpl,"******\n");
 9712:       
 9713: 			varpl=matrix(1,nlstate,(int) bage, (int) fage);
 9714: 			oldm=oldms;savm=savms;
 9715: 			varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
 9716: 			free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 9717:       /*}*/
 9718:     }
 9719: 		
 9720:     fclose(ficresvpl);
 9721:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
 9722:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
 9723: 
 9724:     /*---------- End : free ----------------*/
 9725:     if (mobilav!=0 ||mobilavproj !=0) free_ma3x(mobaverage,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
 9726:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9727:   }  /* mle==-3 arrives here for freeing */
 9728:  /* endfree:*/
 9729:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9730:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 9731:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9732:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9733:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9734:     free_matrix(covar,0,NCOVMAX,1,n);
 9735:     free_matrix(matcov,1,npar,1,npar);
 9736:     free_matrix(hess,1,npar,1,npar);
 9737:     /*free_vector(delti,1,npar);*/
 9738:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9739:     free_matrix(agev,1,maxwav,1,imx);
 9740:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 9741: 
 9742:     free_ivector(ncodemax,1,NCOVMAX);
 9743:     free_ivector(ncodemaxwundef,1,NCOVMAX);
 9744:     free_ivector(Tvar,1,NCOVMAX);
 9745:     free_ivector(Tprod,1,NCOVMAX);
 9746:     free_ivector(Tvaraff,1,NCOVMAX);
 9747:     free_ivector(Tage,1,NCOVMAX);
 9748: 
 9749:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 9750:     /* free_imatrix(codtab,1,100,1,10); */
 9751:   fflush(fichtm);
 9752:   fflush(ficgp);
 9753:   
 9754: 
 9755:   if((nberr >0) || (nbwarn>0)){
 9756:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
 9757:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
 9758:   }else{
 9759:     printf("End of Imach\n");
 9760:     fprintf(ficlog,"End of Imach\n");
 9761:   }
 9762:   printf("See log file on %s\n",filelog);
 9763:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 9764:   /*(void) gettimeofday(&end_time,&tzp);*/
 9765:   rend_time = time(NULL);  
 9766:   end_time = *localtime(&rend_time);
 9767:   /* tml = *localtime(&end_time.tm_sec); */
 9768:   strcpy(strtend,asctime(&end_time));
 9769:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 9770:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 9771:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9772: 
 9773:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9774:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9775:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9776:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 9777: /*   if(fileappend(fichtm,optionfilehtm)){ */
 9778:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9779:   fclose(fichtm);
 9780:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9781:   fclose(fichtmcov);
 9782:   fclose(ficgp);
 9783:   fclose(ficlog);
 9784:   /*------ End -----------*/
 9785: 
 9786: 
 9787:    printf("Before Current directory %s!\n",pathcd);
 9788: #ifdef WIN32
 9789:    if (_chdir(pathcd) != 0)
 9790: 	   printf("Can't move to directory %s!\n",path);
 9791:    if(_getcwd(pathcd,MAXLINE) > 0)
 9792: #else
 9793:    if(chdir(pathcd) != 0)
 9794: 	   printf("Can't move to directory %s!\n", path);
 9795:    if (getcwd(pathcd, MAXLINE) > 0)
 9796: #endif 
 9797:     printf("Current directory %s!\n",pathcd);
 9798:   /*strcat(plotcmd,CHARSEPARATOR);*/
 9799:   sprintf(plotcmd,"gnuplot");
 9800: #ifdef _WIN32
 9801:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 9802: #endif
 9803:   if(!stat(plotcmd,&info)){
 9804:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9805:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 9806:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 9807:     }else
 9808:       strcpy(pplotcmd,plotcmd);
 9809: #ifdef __unix
 9810:     strcpy(plotcmd,GNUPLOTPROGRAM);
 9811:     if(!stat(plotcmd,&info)){
 9812:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9813:     }else
 9814:       strcpy(pplotcmd,plotcmd);
 9815: #endif
 9816:   }else
 9817:     strcpy(pplotcmd,plotcmd);
 9818:   
 9819:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 9820:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 9821: 
 9822:   if((outcmd=system(plotcmd)) != 0){
 9823:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 9824:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 9825:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 9826:     if((outcmd=system(plotcmd)) != 0)
 9827:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 9828:   }
 9829:   printf(" Successful, please wait...");
 9830:   while (z[0] != 'q') {
 9831:     /* chdir(path); */
 9832:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 9833:     scanf("%s",z);
 9834: /*     if (z[0] == 'c') system("./imach"); */
 9835:     if (z[0] == 'e') {
 9836: #ifdef __APPLE__
 9837:       sprintf(pplotcmd, "open %s", optionfilehtm);
 9838: #elif __linux
 9839:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 9840: #else
 9841:       sprintf(pplotcmd, "%s", optionfilehtm);
 9842: #endif
 9843:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 9844:       system(pplotcmd);
 9845:     }
 9846:     else if (z[0] == 'g') system(plotcmd);
 9847:     else if (z[0] == 'q') exit(0);
 9848:   }
 9849:   end:
 9850:   while (z[0] != 'q') {
 9851:     printf("\nType  q for exiting: "); fflush(stdout);
 9852:     scanf("%s",z);
 9853:   }
 9854: }

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