File:  [Local Repository] / imach / src / imach.c
Revision 1.217: download - view: text, annotated - select for diffs
Wed Dec 23 17:18:31 2015 UTC (8 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Experimental backcast

    1: /* $Id: imach.c,v 1.217 2015/12/23 17:18:31 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.217  2015/12/23 17:18:31  brouard
    5:   Summary: Experimental backcast
    6: 
    7:   Revision 1.216  2015/12/18 17:32:11  brouard
    8:   Summary: 0.98r4 Warning and status=-2
    9: 
   10:   Version 0.98r4 is now:
   11:    - displaying an error when status is -1, date of interview unknown and date of death known;
   12:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   13:   Older changes concerning s=-2, dating from 2005 have been supersed.
   14: 
   15:   Revision 1.215  2015/12/16 08:52:24  brouard
   16:   Summary: 0.98r4 working
   17: 
   18:   Revision 1.214  2015/12/16 06:57:54  brouard
   19:   Summary: temporary not working
   20: 
   21:   Revision 1.213  2015/12/11 18:22:17  brouard
   22:   Summary: 0.98r4
   23: 
   24:   Revision 1.212  2015/11/21 12:47:24  brouard
   25:   Summary: minor typo
   26: 
   27:   Revision 1.211  2015/11/21 12:41:11  brouard
   28:   Summary: 0.98r3 with some graph of projected cross-sectional
   29: 
   30:   Author: Nicolas Brouard
   31: 
   32:   Revision 1.210  2015/11/18 17:41:20  brouard
   33:   Summary: Start working on projected prevalences
   34: 
   35:   Revision 1.209  2015/11/17 22:12:03  brouard
   36:   Summary: Adding ftolpl parameter
   37:   Author: N Brouard
   38: 
   39:   We had difficulties to get smoothed confidence intervals. It was due
   40:   to the period prevalence which wasn't computed accurately. The inner
   41:   parameter ftolpl is now an outer parameter of the .imach parameter
   42:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   43:   computation are long.
   44: 
   45:   Revision 1.208  2015/11/17 14:31:57  brouard
   46:   Summary: temporary
   47: 
   48:   Revision 1.207  2015/10/27 17:36:57  brouard
   49:   *** empty log message ***
   50: 
   51:   Revision 1.206  2015/10/24 07:14:11  brouard
   52:   *** empty log message ***
   53: 
   54:   Revision 1.205  2015/10/23 15:50:53  brouard
   55:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   56: 
   57:   Revision 1.204  2015/10/01 16:20:26  brouard
   58:   Summary: Some new graphs of contribution to likelihood
   59: 
   60:   Revision 1.203  2015/09/30 17:45:14  brouard
   61:   Summary: looking at better estimation of the hessian
   62: 
   63:   Also a better criteria for convergence to the period prevalence And
   64:   therefore adding the number of years needed to converge. (The
   65:   prevalence in any alive state shold sum to one
   66: 
   67:   Revision 1.202  2015/09/22 19:45:16  brouard
   68:   Summary: Adding some overall graph on contribution to likelihood. Might change
   69: 
   70:   Revision 1.201  2015/09/15 17:34:58  brouard
   71:   Summary: 0.98r0
   72: 
   73:   - Some new graphs like suvival functions
   74:   - Some bugs fixed like model=1+age+V2.
   75: 
   76:   Revision 1.200  2015/09/09 16:53:55  brouard
   77:   Summary: Big bug thanks to Flavia
   78: 
   79:   Even model=1+age+V2. did not work anymore
   80: 
   81:   Revision 1.199  2015/09/07 14:09:23  brouard
   82:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
   83: 
   84:   Revision 1.198  2015/09/03 07:14:39  brouard
   85:   Summary: 0.98q5 Flavia
   86: 
   87:   Revision 1.197  2015/09/01 18:24:39  brouard
   88:   *** empty log message ***
   89: 
   90:   Revision 1.196  2015/08/18 23:17:52  brouard
   91:   Summary: 0.98q5
   92: 
   93:   Revision 1.195  2015/08/18 16:28:39  brouard
   94:   Summary: Adding a hack for testing purpose
   95: 
   96:   After reading the title, ftol and model lines, if the comment line has
   97:   a q, starting with #q, the answer at the end of the run is quit. It
   98:   permits to run test files in batch with ctest. The former workaround was
   99:   $ echo q | imach foo.imach
  100: 
  101:   Revision 1.194  2015/08/18 13:32:00  brouard
  102:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  103: 
  104:   Revision 1.193  2015/08/04 07:17:42  brouard
  105:   Summary: 0.98q4
  106: 
  107:   Revision 1.192  2015/07/16 16:49:02  brouard
  108:   Summary: Fixing some outputs
  109: 
  110:   Revision 1.191  2015/07/14 10:00:33  brouard
  111:   Summary: Some fixes
  112: 
  113:   Revision 1.190  2015/05/05 08:51:13  brouard
  114:   Summary: Adding digits in output parameters (7 digits instead of 6)
  115: 
  116:   Fix 1+age+.
  117: 
  118:   Revision 1.189  2015/04/30 14:45:16  brouard
  119:   Summary: 0.98q2
  120: 
  121:   Revision 1.188  2015/04/30 08:27:53  brouard
  122:   *** empty log message ***
  123: 
  124:   Revision 1.187  2015/04/29 09:11:15  brouard
  125:   *** empty log message ***
  126: 
  127:   Revision 1.186  2015/04/23 12:01:52  brouard
  128:   Summary: V1*age is working now, version 0.98q1
  129: 
  130:   Some codes had been disabled in order to simplify and Vn*age was
  131:   working in the optimization phase, ie, giving correct MLE parameters,
  132:   but, as usual, outputs were not correct and program core dumped.
  133: 
  134:   Revision 1.185  2015/03/11 13:26:42  brouard
  135:   Summary: Inclusion of compile and links command line for Intel Compiler
  136: 
  137:   Revision 1.184  2015/03/11 11:52:39  brouard
  138:   Summary: Back from Windows 8. Intel Compiler
  139: 
  140:   Revision 1.183  2015/03/10 20:34:32  brouard
  141:   Summary: 0.98q0, trying with directest, mnbrak fixed
  142: 
  143:   We use directest instead of original Powell test; probably no
  144:   incidence on the results, but better justifications;
  145:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  146:   wrong results.
  147: 
  148:   Revision 1.182  2015/02/12 08:19:57  brouard
  149:   Summary: Trying to keep directest which seems simpler and more general
  150:   Author: Nicolas Brouard
  151: 
  152:   Revision 1.181  2015/02/11 23:22:24  brouard
  153:   Summary: Comments on Powell added
  154: 
  155:   Author:
  156: 
  157:   Revision 1.180  2015/02/11 17:33:45  brouard
  158:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  159: 
  160:   Revision 1.179  2015/01/04 09:57:06  brouard
  161:   Summary: back to OS/X
  162: 
  163:   Revision 1.178  2015/01/04 09:35:48  brouard
  164:   *** empty log message ***
  165: 
  166:   Revision 1.177  2015/01/03 18:40:56  brouard
  167:   Summary: Still testing ilc32 on OSX
  168: 
  169:   Revision 1.176  2015/01/03 16:45:04  brouard
  170:   *** empty log message ***
  171: 
  172:   Revision 1.175  2015/01/03 16:33:42  brouard
  173:   *** empty log message ***
  174: 
  175:   Revision 1.174  2015/01/03 16:15:49  brouard
  176:   Summary: Still in cross-compilation
  177: 
  178:   Revision 1.173  2015/01/03 12:06:26  brouard
  179:   Summary: trying to detect cross-compilation
  180: 
  181:   Revision 1.172  2014/12/27 12:07:47  brouard
  182:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  183: 
  184:   Revision 1.171  2014/12/23 13:26:59  brouard
  185:   Summary: Back from Visual C
  186: 
  187:   Still problem with utsname.h on Windows
  188: 
  189:   Revision 1.170  2014/12/23 11:17:12  brouard
  190:   Summary: Cleaning some \%% back to %%
  191: 
  192:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  193: 
  194:   Revision 1.169  2014/12/22 23:08:31  brouard
  195:   Summary: 0.98p
  196: 
  197:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  198: 
  199:   Revision 1.168  2014/12/22 15:17:42  brouard
  200:   Summary: update
  201: 
  202:   Revision 1.167  2014/12/22 13:50:56  brouard
  203:   Summary: Testing uname and compiler version and if compiled 32 or 64
  204: 
  205:   Testing on Linux 64
  206: 
  207:   Revision 1.166  2014/12/22 11:40:47  brouard
  208:   *** empty log message ***
  209: 
  210:   Revision 1.165  2014/12/16 11:20:36  brouard
  211:   Summary: After compiling on Visual C
  212: 
  213:   * imach.c (Module): Merging 1.61 to 1.162
  214: 
  215:   Revision 1.164  2014/12/16 10:52:11  brouard
  216:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  217: 
  218:   * imach.c (Module): Merging 1.61 to 1.162
  219: 
  220:   Revision 1.163  2014/12/16 10:30:11  brouard
  221:   * imach.c (Module): Merging 1.61 to 1.162
  222: 
  223:   Revision 1.162  2014/09/25 11:43:39  brouard
  224:   Summary: temporary backup 0.99!
  225: 
  226:   Revision 1.1  2014/09/16 11:06:58  brouard
  227:   Summary: With some code (wrong) for nlopt
  228: 
  229:   Author:
  230: 
  231:   Revision 1.161  2014/09/15 20:41:41  brouard
  232:   Summary: Problem with macro SQR on Intel compiler
  233: 
  234:   Revision 1.160  2014/09/02 09:24:05  brouard
  235:   *** empty log message ***
  236: 
  237:   Revision 1.159  2014/09/01 10:34:10  brouard
  238:   Summary: WIN32
  239:   Author: Brouard
  240: 
  241:   Revision 1.158  2014/08/27 17:11:51  brouard
  242:   *** empty log message ***
  243: 
  244:   Revision 1.157  2014/08/27 16:26:55  brouard
  245:   Summary: Preparing windows Visual studio version
  246:   Author: Brouard
  247: 
  248:   In order to compile on Visual studio, time.h is now correct and time_t
  249:   and tm struct should be used. difftime should be used but sometimes I
  250:   just make the differences in raw time format (time(&now).
  251:   Trying to suppress #ifdef LINUX
  252:   Add xdg-open for __linux in order to open default browser.
  253: 
  254:   Revision 1.156  2014/08/25 20:10:10  brouard
  255:   *** empty log message ***
  256: 
  257:   Revision 1.155  2014/08/25 18:32:34  brouard
  258:   Summary: New compile, minor changes
  259:   Author: Brouard
  260: 
  261:   Revision 1.154  2014/06/20 17:32:08  brouard
  262:   Summary: Outputs now all graphs of convergence to period prevalence
  263: 
  264:   Revision 1.153  2014/06/20 16:45:46  brouard
  265:   Summary: If 3 live state, convergence to period prevalence on same graph
  266:   Author: Brouard
  267: 
  268:   Revision 1.152  2014/06/18 17:54:09  brouard
  269:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  270: 
  271:   Revision 1.151  2014/06/18 16:43:30  brouard
  272:   *** empty log message ***
  273: 
  274:   Revision 1.150  2014/06/18 16:42:35  brouard
  275:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  276:   Author: brouard
  277: 
  278:   Revision 1.149  2014/06/18 15:51:14  brouard
  279:   Summary: Some fixes in parameter files errors
  280:   Author: Nicolas Brouard
  281: 
  282:   Revision 1.148  2014/06/17 17:38:48  brouard
  283:   Summary: Nothing new
  284:   Author: Brouard
  285: 
  286:   Just a new packaging for OS/X version 0.98nS
  287: 
  288:   Revision 1.147  2014/06/16 10:33:11  brouard
  289:   *** empty log message ***
  290: 
  291:   Revision 1.146  2014/06/16 10:20:28  brouard
  292:   Summary: Merge
  293:   Author: Brouard
  294: 
  295:   Merge, before building revised version.
  296: 
  297:   Revision 1.145  2014/06/10 21:23:15  brouard
  298:   Summary: Debugging with valgrind
  299:   Author: Nicolas Brouard
  300: 
  301:   Lot of changes in order to output the results with some covariates
  302:   After the Edimburgh REVES conference 2014, it seems mandatory to
  303:   improve the code.
  304:   No more memory valgrind error but a lot has to be done in order to
  305:   continue the work of splitting the code into subroutines.
  306:   Also, decodemodel has been improved. Tricode is still not
  307:   optimal. nbcode should be improved. Documentation has been added in
  308:   the source code.
  309: 
  310:   Revision 1.143  2014/01/26 09:45:38  brouard
  311:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  312: 
  313:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  314:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  315: 
  316:   Revision 1.142  2014/01/26 03:57:36  brouard
  317:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  318: 
  319:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  320: 
  321:   Revision 1.141  2014/01/26 02:42:01  brouard
  322:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  323: 
  324:   Revision 1.140  2011/09/02 10:37:54  brouard
  325:   Summary: times.h is ok with mingw32 now.
  326: 
  327:   Revision 1.139  2010/06/14 07:50:17  brouard
  328:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  329:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  330: 
  331:   Revision 1.138  2010/04/30 18:19:40  brouard
  332:   *** empty log message ***
  333: 
  334:   Revision 1.137  2010/04/29 18:11:38  brouard
  335:   (Module): Checking covariates for more complex models
  336:   than V1+V2. A lot of change to be done. Unstable.
  337: 
  338:   Revision 1.136  2010/04/26 20:30:53  brouard
  339:   (Module): merging some libgsl code. Fixing computation
  340:   of likelione (using inter/intrapolation if mle = 0) in order to
  341:   get same likelihood as if mle=1.
  342:   Some cleaning of code and comments added.
  343: 
  344:   Revision 1.135  2009/10/29 15:33:14  brouard
  345:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  346: 
  347:   Revision 1.134  2009/10/29 13:18:53  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.133  2009/07/06 10:21:25  brouard
  351:   just nforces
  352: 
  353:   Revision 1.132  2009/07/06 08:22:05  brouard
  354:   Many tings
  355: 
  356:   Revision 1.131  2009/06/20 16:22:47  brouard
  357:   Some dimensions resccaled
  358: 
  359:   Revision 1.130  2009/05/26 06:44:34  brouard
  360:   (Module): Max Covariate is now set to 20 instead of 8. A
  361:   lot of cleaning with variables initialized to 0. Trying to make
  362:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  363: 
  364:   Revision 1.129  2007/08/31 13:49:27  lievre
  365:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  366: 
  367:   Revision 1.128  2006/06/30 13:02:05  brouard
  368:   (Module): Clarifications on computing e.j
  369: 
  370:   Revision 1.127  2006/04/28 18:11:50  brouard
  371:   (Module): Yes the sum of survivors was wrong since
  372:   imach-114 because nhstepm was no more computed in the age
  373:   loop. Now we define nhstepma in the age loop.
  374:   (Module): In order to speed up (in case of numerous covariates) we
  375:   compute health expectancies (without variances) in a first step
  376:   and then all the health expectancies with variances or standard
  377:   deviation (needs data from the Hessian matrices) which slows the
  378:   computation.
  379:   In the future we should be able to stop the program is only health
  380:   expectancies and graph are needed without standard deviations.
  381: 
  382:   Revision 1.126  2006/04/28 17:23:28  brouard
  383:   (Module): Yes the sum of survivors was wrong since
  384:   imach-114 because nhstepm was no more computed in the age
  385:   loop. Now we define nhstepma in the age loop.
  386:   Version 0.98h
  387: 
  388:   Revision 1.125  2006/04/04 15:20:31  lievre
  389:   Errors in calculation of health expectancies. Age was not initialized.
  390:   Forecasting file added.
  391: 
  392:   Revision 1.124  2006/03/22 17:13:53  lievre
  393:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  394:   The log-likelihood is printed in the log file
  395: 
  396:   Revision 1.123  2006/03/20 10:52:43  brouard
  397:   * imach.c (Module): <title> changed, corresponds to .htm file
  398:   name. <head> headers where missing.
  399: 
  400:   * imach.c (Module): Weights can have a decimal point as for
  401:   English (a comma might work with a correct LC_NUMERIC environment,
  402:   otherwise the weight is truncated).
  403:   Modification of warning when the covariates values are not 0 or
  404:   1.
  405:   Version 0.98g
  406: 
  407:   Revision 1.122  2006/03/20 09:45:41  brouard
  408:   (Module): Weights can have a decimal point as for
  409:   English (a comma might work with a correct LC_NUMERIC environment,
  410:   otherwise the weight is truncated).
  411:   Modification of warning when the covariates values are not 0 or
  412:   1.
  413:   Version 0.98g
  414: 
  415:   Revision 1.121  2006/03/16 17:45:01  lievre
  416:   * imach.c (Module): Comments concerning covariates added
  417: 
  418:   * imach.c (Module): refinements in the computation of lli if
  419:   status=-2 in order to have more reliable computation if stepm is
  420:   not 1 month. Version 0.98f
  421: 
  422:   Revision 1.120  2006/03/16 15:10:38  lievre
  423:   (Module): refinements in the computation of lli if
  424:   status=-2 in order to have more reliable computation if stepm is
  425:   not 1 month. Version 0.98f
  426: 
  427:   Revision 1.119  2006/03/15 17:42:26  brouard
  428:   (Module): Bug if status = -2, the loglikelihood was
  429:   computed as likelihood omitting the logarithm. Version O.98e
  430: 
  431:   Revision 1.118  2006/03/14 18:20:07  brouard
  432:   (Module): varevsij Comments added explaining the second
  433:   table of variances if popbased=1 .
  434:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  435:   (Module): Function pstamp added
  436:   (Module): Version 0.98d
  437: 
  438:   Revision 1.117  2006/03/14 17:16:22  brouard
  439:   (Module): varevsij Comments added explaining the second
  440:   table of variances if popbased=1 .
  441:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  442:   (Module): Function pstamp added
  443:   (Module): Version 0.98d
  444: 
  445:   Revision 1.116  2006/03/06 10:29:27  brouard
  446:   (Module): Variance-covariance wrong links and
  447:   varian-covariance of ej. is needed (Saito).
  448: 
  449:   Revision 1.115  2006/02/27 12:17:45  brouard
  450:   (Module): One freematrix added in mlikeli! 0.98c
  451: 
  452:   Revision 1.114  2006/02/26 12:57:58  brouard
  453:   (Module): Some improvements in processing parameter
  454:   filename with strsep.
  455: 
  456:   Revision 1.113  2006/02/24 14:20:24  brouard
  457:   (Module): Memory leaks checks with valgrind and:
  458:   datafile was not closed, some imatrix were not freed and on matrix
  459:   allocation too.
  460: 
  461:   Revision 1.112  2006/01/30 09:55:26  brouard
  462:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  463: 
  464:   Revision 1.111  2006/01/25 20:38:18  brouard
  465:   (Module): Lots of cleaning and bugs added (Gompertz)
  466:   (Module): Comments can be added in data file. Missing date values
  467:   can be a simple dot '.'.
  468: 
  469:   Revision 1.110  2006/01/25 00:51:50  brouard
  470:   (Module): Lots of cleaning and bugs added (Gompertz)
  471: 
  472:   Revision 1.109  2006/01/24 19:37:15  brouard
  473:   (Module): Comments (lines starting with a #) are allowed in data.
  474: 
  475:   Revision 1.108  2006/01/19 18:05:42  lievre
  476:   Gnuplot problem appeared...
  477:   To be fixed
  478: 
  479:   Revision 1.107  2006/01/19 16:20:37  brouard
  480:   Test existence of gnuplot in imach path
  481: 
  482:   Revision 1.106  2006/01/19 13:24:36  brouard
  483:   Some cleaning and links added in html output
  484: 
  485:   Revision 1.105  2006/01/05 20:23:19  lievre
  486:   *** empty log message ***
  487: 
  488:   Revision 1.104  2005/09/30 16:11:43  lievre
  489:   (Module): sump fixed, loop imx fixed, and simplifications.
  490:   (Module): If the status is missing at the last wave but we know
  491:   that the person is alive, then we can code his/her status as -2
  492:   (instead of missing=-1 in earlier versions) and his/her
  493:   contributions to the likelihood is 1 - Prob of dying from last
  494:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  495:   the healthy state at last known wave). Version is 0.98
  496: 
  497:   Revision 1.103  2005/09/30 15:54:49  lievre
  498:   (Module): sump fixed, loop imx fixed, and simplifications.
  499: 
  500:   Revision 1.102  2004/09/15 17:31:30  brouard
  501:   Add the possibility to read data file including tab characters.
  502: 
  503:   Revision 1.101  2004/09/15 10:38:38  brouard
  504:   Fix on curr_time
  505: 
  506:   Revision 1.100  2004/07/12 18:29:06  brouard
  507:   Add version for Mac OS X. Just define UNIX in Makefile
  508: 
  509:   Revision 1.99  2004/06/05 08:57:40  brouard
  510:   *** empty log message ***
  511: 
  512:   Revision 1.98  2004/05/16 15:05:56  brouard
  513:   New version 0.97 . First attempt to estimate force of mortality
  514:   directly from the data i.e. without the need of knowing the health
  515:   state at each age, but using a Gompertz model: log u =a + b*age .
  516:   This is the basic analysis of mortality and should be done before any
  517:   other analysis, in order to test if the mortality estimated from the
  518:   cross-longitudinal survey is different from the mortality estimated
  519:   from other sources like vital statistic data.
  520: 
  521:   The same imach parameter file can be used but the option for mle should be -3.
  522: 
  523:   Agnès, who wrote this part of the code, tried to keep most of the
  524:   former routines in order to include the new code within the former code.
  525: 
  526:   The output is very simple: only an estimate of the intercept and of
  527:   the slope with 95% confident intervals.
  528: 
  529:   Current limitations:
  530:   A) Even if you enter covariates, i.e. with the
  531:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  532:   B) There is no computation of Life Expectancy nor Life Table.
  533: 
  534:   Revision 1.97  2004/02/20 13:25:42  lievre
  535:   Version 0.96d. Population forecasting command line is (temporarily)
  536:   suppressed.
  537: 
  538:   Revision 1.96  2003/07/15 15:38:55  brouard
  539:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  540:   rewritten within the same printf. Workaround: many printfs.
  541: 
  542:   Revision 1.95  2003/07/08 07:54:34  brouard
  543:   * imach.c (Repository):
  544:   (Repository): Using imachwizard code to output a more meaningful covariance
  545:   matrix (cov(a12,c31) instead of numbers.
  546: 
  547:   Revision 1.94  2003/06/27 13:00:02  brouard
  548:   Just cleaning
  549: 
  550:   Revision 1.93  2003/06/25 16:33:55  brouard
  551:   (Module): On windows (cygwin) function asctime_r doesn't
  552:   exist so I changed back to asctime which exists.
  553:   (Module): Version 0.96b
  554: 
  555:   Revision 1.92  2003/06/25 16:30:45  brouard
  556:   (Module): On windows (cygwin) function asctime_r doesn't
  557:   exist so I changed back to asctime which exists.
  558: 
  559:   Revision 1.91  2003/06/25 15:30:29  brouard
  560:   * imach.c (Repository): Duplicated warning errors corrected.
  561:   (Repository): Elapsed time after each iteration is now output. It
  562:   helps to forecast when convergence will be reached. Elapsed time
  563:   is stamped in powell.  We created a new html file for the graphs
  564:   concerning matrix of covariance. It has extension -cov.htm.
  565: 
  566:   Revision 1.90  2003/06/24 12:34:15  brouard
  567:   (Module): Some bugs corrected for windows. Also, when
  568:   mle=-1 a template is output in file "or"mypar.txt with the design
  569:   of the covariance matrix to be input.
  570: 
  571:   Revision 1.89  2003/06/24 12:30:52  brouard
  572:   (Module): Some bugs corrected for windows. Also, when
  573:   mle=-1 a template is output in file "or"mypar.txt with the design
  574:   of the covariance matrix to be input.
  575: 
  576:   Revision 1.88  2003/06/23 17:54:56  brouard
  577:   * 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.
  578: 
  579:   Revision 1.87  2003/06/18 12:26:01  brouard
  580:   Version 0.96
  581: 
  582:   Revision 1.86  2003/06/17 20:04:08  brouard
  583:   (Module): Change position of html and gnuplot routines and added
  584:   routine fileappend.
  585: 
  586:   Revision 1.85  2003/06/17 13:12:43  brouard
  587:   * imach.c (Repository): Check when date of death was earlier that
  588:   current date of interview. It may happen when the death was just
  589:   prior to the death. In this case, dh was negative and likelihood
  590:   was wrong (infinity). We still send an "Error" but patch by
  591:   assuming that the date of death was just one stepm after the
  592:   interview.
  593:   (Repository): Because some people have very long ID (first column)
  594:   we changed int to long in num[] and we added a new lvector for
  595:   memory allocation. But we also truncated to 8 characters (left
  596:   truncation)
  597:   (Repository): No more line truncation errors.
  598: 
  599:   Revision 1.84  2003/06/13 21:44:43  brouard
  600:   * imach.c (Repository): Replace "freqsummary" at a correct
  601:   place. It differs from routine "prevalence" which may be called
  602:   many times. Probs is memory consuming and must be used with
  603:   parcimony.
  604:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  605: 
  606:   Revision 1.83  2003/06/10 13:39:11  lievre
  607:   *** empty log message ***
  608: 
  609:   Revision 1.82  2003/06/05 15:57:20  brouard
  610:   Add log in  imach.c and  fullversion number is now printed.
  611: 
  612: */
  613: /*
  614:    Interpolated Markov Chain
  615: 
  616:   Short summary of the programme:
  617:   
  618:   This program computes Healthy Life Expectancies from
  619:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  620:   first survey ("cross") where individuals from different ages are
  621:   interviewed on their health status or degree of disability (in the
  622:   case of a health survey which is our main interest) -2- at least a
  623:   second wave of interviews ("longitudinal") which measure each change
  624:   (if any) in individual health status.  Health expectancies are
  625:   computed from the time spent in each health state according to a
  626:   model. More health states you consider, more time is necessary to reach the
  627:   Maximum Likelihood of the parameters involved in the model.  The
  628:   simplest model is the multinomial logistic model where pij is the
  629:   probability to be observed in state j at the second wave
  630:   conditional to be observed in state i at the first wave. Therefore
  631:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  632:   'age' is age and 'sex' is a covariate. If you want to have a more
  633:   complex model than "constant and age", you should modify the program
  634:   where the markup *Covariates have to be included here again* invites
  635:   you to do it.  More covariates you add, slower the
  636:   convergence.
  637: 
  638:   The advantage of this computer programme, compared to a simple
  639:   multinomial logistic model, is clear when the delay between waves is not
  640:   identical for each individual. Also, if a individual missed an
  641:   intermediate interview, the information is lost, but taken into
  642:   account using an interpolation or extrapolation.  
  643: 
  644:   hPijx is the probability to be observed in state i at age x+h
  645:   conditional to the observed state i at age x. The delay 'h' can be
  646:   split into an exact number (nh*stepm) of unobserved intermediate
  647:   states. This elementary transition (by month, quarter,
  648:   semester or year) is modelled as a multinomial logistic.  The hPx
  649:   matrix is simply the matrix product of nh*stepm elementary matrices
  650:   and the contribution of each individual to the likelihood is simply
  651:   hPijx.
  652: 
  653:   Also this programme outputs the covariance matrix of the parameters but also
  654:   of the life expectancies. It also computes the period (stable) prevalence. 
  655:   
  656:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  657:            Institut national d'études démographiques, Paris.
  658:   This software have been partly granted by Euro-REVES, a concerted action
  659:   from the European Union.
  660:   It is copyrighted identically to a GNU software product, ie programme and
  661:   software can be distributed freely for non commercial use. Latest version
  662:   can be accessed at http://euroreves.ined.fr/imach .
  663: 
  664:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  665:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  666:   
  667:   **********************************************************************/
  668: /*
  669:   main
  670:   read parameterfile
  671:   read datafile
  672:   concatwav
  673:   freqsummary
  674:   if (mle >= 1)
  675:     mlikeli
  676:   print results files
  677:   if mle==1 
  678:      computes hessian
  679:   read end of parameter file: agemin, agemax, bage, fage, estepm
  680:       begin-prev-date,...
  681:   open gnuplot file
  682:   open html file
  683:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  684:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  685:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  686:     freexexit2 possible for memory heap.
  687: 
  688:   h Pij x                         | pij_nom  ficrestpij
  689:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  690:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  691:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  692: 
  693:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  694:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  695:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  696:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  697:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  698: 
  699:   forecasting if prevfcast==1 prevforecast call prevalence()
  700:   health expectancies
  701:   Variance-covariance of DFLE
  702:   prevalence()
  703:    movingaverage()
  704:   varevsij() 
  705:   if popbased==1 varevsij(,popbased)
  706:   total life expectancies
  707:   Variance of period (stable) prevalence
  708:  end
  709: */
  710: 
  711: /* #define DEBUG */
  712: /* #define DEBUGBRENT */
  713: /* #define DEBUGLINMIN */
  714: /* #define DEBUGHESS */
  715: #define DEBUGHESSIJ
  716: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
  717: #define POWELL /* Instead of NLOPT */
  718: #define POWELLF1F3 /* Skip test */
  719: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  720: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  721: 
  722: #include <math.h>
  723: #include <stdio.h>
  724: #include <stdlib.h>
  725: #include <string.h>
  726: 
  727: #ifdef _WIN32
  728: #include <io.h>
  729: #include <windows.h>
  730: #include <tchar.h>
  731: #else
  732: #include <unistd.h>
  733: #endif
  734: 
  735: #include <limits.h>
  736: #include <sys/types.h>
  737: 
  738: #if defined(__GNUC__)
  739: #include <sys/utsname.h> /* Doesn't work on Windows */
  740: #endif
  741: 
  742: #include <sys/stat.h>
  743: #include <errno.h>
  744: /* extern int errno; */
  745: 
  746: /* #ifdef LINUX */
  747: /* #include <time.h> */
  748: /* #include "timeval.h" */
  749: /* #else */
  750: /* #include <sys/time.h> */
  751: /* #endif */
  752: 
  753: #include <time.h>
  754: 
  755: #ifdef GSL
  756: #include <gsl/gsl_errno.h>
  757: #include <gsl/gsl_multimin.h>
  758: #endif
  759: 
  760: 
  761: #ifdef NLOPT
  762: #include <nlopt.h>
  763: typedef struct {
  764:   double (* function)(double [] );
  765: } myfunc_data ;
  766: #endif
  767: 
  768: /* #include <libintl.h> */
  769: /* #define _(String) gettext (String) */
  770: 
  771: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  772: 
  773: #define GNUPLOTPROGRAM "gnuplot"
  774: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  775: #define FILENAMELENGTH 132
  776: 
  777: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  778: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  779: 
  780: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  781: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  782: 
  783: #define NINTERVMAX 8
  784: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  785: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  786: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  787: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  788: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  789: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  790: #define MAXN 20000
  791: #define YEARM 12. /**< Number of months per year */
  792: #define AGESUP 130
  793: #define AGEBASE 40
  794: #define AGEOVERFLOW 1.e20
  795: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  796: #ifdef _WIN32
  797: #define DIRSEPARATOR '\\'
  798: #define CHARSEPARATOR "\\"
  799: #define ODIRSEPARATOR '/'
  800: #else
  801: #define DIRSEPARATOR '/'
  802: #define CHARSEPARATOR "/"
  803: #define ODIRSEPARATOR '\\'
  804: #endif
  805: 
  806: /* $Id: imach.c,v 1.217 2015/12/23 17:18:31 brouard Exp $ */
  807: /* $State: Exp $ */
  808: #include "version.h"
  809: char version[]=__IMACH_VERSION__;
  810: 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";
  811: char fullversion[]="$Revision: 1.217 $ $Date: 2015/12/23 17:18:31 $"; 
  812: char strstart[80];
  813: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  814: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  815: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  816: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  817: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  818: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  819: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  820: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  821: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  822: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  823: int cptcov=0; /* Working variable */
  824: int npar=NPARMAX;
  825: int nlstate=2; /* Number of live states */
  826: int ndeath=1; /* Number of dead states */
  827: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  828: int popbased=0;
  829: 
  830: int *wav; /* Number of waves for this individuual 0 is possible */
  831: int maxwav=0; /* Maxim number of waves */
  832: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  833: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  834: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  835: 		   to the likelihood and the sum of weights (done by funcone)*/
  836: int mle=1, weightopt=0;
  837: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  838: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  839: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  840: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  841: int countcallfunc=0;  /* Count the number of calls to func */
  842: double jmean=1; /* Mean space between 2 waves */
  843: double **matprod2(); /* test */
  844: double **oldm, **newm, **savm; /* Working pointers to matrices */
  845: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  846: /*FILE *fic ; */ /* Used in readdata only */
  847: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  848: FILE *ficlog, *ficrespow;
  849: int globpr=0; /* Global variable for printing or not */
  850: double fretone; /* Only one call to likelihood */
  851: long ipmx=0; /* Number of contributions */
  852: double sw; /* Sum of weights */
  853: char filerespow[FILENAMELENGTH];
  854: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  855: FILE *ficresilk;
  856: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  857: FILE *ficresprobmorprev;
  858: FILE *fichtm, *fichtmcov; /* Html File */
  859: FILE *ficreseij;
  860: char filerese[FILENAMELENGTH];
  861: FILE *ficresstdeij;
  862: char fileresstde[FILENAMELENGTH];
  863: FILE *ficrescveij;
  864: char filerescve[FILENAMELENGTH];
  865: FILE  *ficresvij;
  866: char fileresv[FILENAMELENGTH];
  867: FILE  *ficresvpl;
  868: char fileresvpl[FILENAMELENGTH];
  869: char title[MAXLINE];
  870: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
  871: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  872: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  873: char command[FILENAMELENGTH];
  874: int  outcmd=0;
  875: 
  876: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  877: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  878: char filelog[FILENAMELENGTH]; /* Log file */
  879: char filerest[FILENAMELENGTH];
  880: char fileregp[FILENAMELENGTH];
  881: char popfile[FILENAMELENGTH];
  882: 
  883: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  884: 
  885: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  886: /* struct timezone tzp; */
  887: /* extern int gettimeofday(); */
  888: struct tm tml, *gmtime(), *localtime();
  889: 
  890: extern time_t time();
  891: 
  892: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  893: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  894: struct tm tm;
  895: 
  896: char strcurr[80], strfor[80];
  897: 
  898: char *endptr;
  899: long lval;
  900: double dval;
  901: 
  902: #define NR_END 1
  903: #define FREE_ARG char*
  904: #define FTOL 1.0e-10
  905: 
  906: #define NRANSI 
  907: #define ITMAX 200 
  908: 
  909: #define TOL 2.0e-4 
  910: 
  911: #define CGOLD 0.3819660 
  912: #define ZEPS 1.0e-10 
  913: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  914: 
  915: #define GOLD 1.618034 
  916: #define GLIMIT 100.0 
  917: #define TINY 1.0e-20 
  918: 
  919: static double maxarg1,maxarg2;
  920: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  921: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  922:   
  923: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  924: #define rint(a) floor(a+0.5)
  925: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  926: #define mytinydouble 1.0e-16
  927: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  928: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  929: /* static double dsqrarg; */
  930: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  931: static double sqrarg;
  932: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  933: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  934: int agegomp= AGEGOMP;
  935: 
  936: int imx; 
  937: int stepm=1;
  938: /* Stepm, step in month: minimum step interpolation*/
  939: 
  940: int estepm;
  941: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  942: 
  943: int m,nb;
  944: long *num;
  945: int firstpass=0, lastpass=4,*cod, *cens;
  946: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  947: 		   covariate for which somebody answered excluding 
  948: 		   undefined. Usually 2: 0 and 1. */
  949: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  950: 			     covariate for which somebody answered including 
  951: 			     undefined. Usually 3: -1, 0 and 1. */
  952: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  953: double **pmmij, ***probs;
  954: double *ageexmed,*agecens;
  955: double dateintmean=0;
  956: 
  957: double *weight;
  958: int **s; /* Status */
  959: double *agedc;
  960: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  961: 		  * covar=matrix(0,NCOVMAX,1,n); 
  962: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  963: double  idx; 
  964: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  965: int *Tage;
  966: int *Ndum; /** Freq of modality (tricode */
  967: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
  968: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  969: double *lsurv, *lpop, *tpop;
  970: 
  971: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  972: double ftolhess; /**< Tolerance for computing hessian */
  973: 
  974: /**************** split *************************/
  975: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  976: {
  977:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  978:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  979:   */ 
  980:   char	*ss;				/* pointer */
  981:   int	l1=0, l2=0;				/* length counters */
  982: 
  983:   l1 = strlen(path );			/* length of path */
  984:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  985:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  986:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  987:     strcpy( name, path );		/* we got the fullname name because no directory */
  988:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  989:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  990:     /* get current working directory */
  991:     /*    extern  char* getcwd ( char *buf , int len);*/
  992: #ifdef WIN32
  993:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  994: #else
  995: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  996: #endif
  997:       return( GLOCK_ERROR_GETCWD );
  998:     }
  999:     /* got dirc from getcwd*/
 1000:     printf(" DIRC = %s \n",dirc);
 1001:   } else {				/* strip directory from path */
 1002:     ss++;				/* after this, the filename */
 1003:     l2 = strlen( ss );			/* length of filename */
 1004:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1005:     strcpy( name, ss );		/* save file name */
 1006:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1007:     dirc[l1-l2] = '\0';			/* add zero */
 1008:     printf(" DIRC2 = %s \n",dirc);
 1009:   }
 1010:   /* We add a separator at the end of dirc if not exists */
 1011:   l1 = strlen( dirc );			/* length of directory */
 1012:   if( dirc[l1-1] != DIRSEPARATOR ){
 1013:     dirc[l1] =  DIRSEPARATOR;
 1014:     dirc[l1+1] = 0; 
 1015:     printf(" DIRC3 = %s \n",dirc);
 1016:   }
 1017:   ss = strrchr( name, '.' );		/* find last / */
 1018:   if (ss >0){
 1019:     ss++;
 1020:     strcpy(ext,ss);			/* save extension */
 1021:     l1= strlen( name);
 1022:     l2= strlen(ss)+1;
 1023:     strncpy( finame, name, l1-l2);
 1024:     finame[l1-l2]= 0;
 1025:   }
 1026: 
 1027:   return( 0 );				/* we're done */
 1028: }
 1029: 
 1030: 
 1031: /******************************************/
 1032: 
 1033: void replace_back_to_slash(char *s, char*t)
 1034: {
 1035:   int i;
 1036:   int lg=0;
 1037:   i=0;
 1038:   lg=strlen(t);
 1039:   for(i=0; i<= lg; i++) {
 1040:     (s[i] = t[i]);
 1041:     if (t[i]== '\\') s[i]='/';
 1042:   }
 1043: }
 1044: 
 1045: char *trimbb(char *out, char *in)
 1046: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1047:   char *s;
 1048:   s=out;
 1049:   while (*in != '\0'){
 1050:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1051:       in++;
 1052:     }
 1053:     *out++ = *in++;
 1054:   }
 1055:   *out='\0';
 1056:   return s;
 1057: }
 1058: 
 1059: /* char *substrchaine(char *out, char *in, char *chain) */
 1060: /* { */
 1061: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1062: /*   char *s, *t; */
 1063: /*   t=in;s=out; */
 1064: /*   while ((*in != *chain) && (*in != '\0')){ */
 1065: /*     *out++ = *in++; */
 1066: /*   } */
 1067: 
 1068: /*   /\* *in matches *chain *\/ */
 1069: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1070: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1071: /*   } */
 1072: /*   in--; chain--; */
 1073: /*   while ( (*in != '\0')){ */
 1074: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1075: /*     *out++ = *in++; */
 1076: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1077: /*   } */
 1078: /*   *out='\0'; */
 1079: /*   out=s; */
 1080: /*   return out; */
 1081: /* } */
 1082: char *substrchaine(char *out, char *in, char *chain)
 1083: {
 1084:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1085:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1086: 
 1087:   char *strloc;
 1088: 
 1089:   strcpy (out, in); 
 1090:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1091:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1092:   if(strloc != NULL){ 
 1093:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1094:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1095:     /* strcpy (strloc, strloc +strlen(chain));*/
 1096:   }
 1097:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1098:   return out;
 1099: }
 1100: 
 1101: 
 1102: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1103: {
 1104:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1105:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1106:      gives blocc="abcdef" and alocc="ghi2j".
 1107:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1108:   */
 1109:   char *s, *t;
 1110:   t=in;s=in;
 1111:   while ((*in != occ) && (*in != '\0')){
 1112:     *alocc++ = *in++;
 1113:   }
 1114:   if( *in == occ){
 1115:     *(alocc)='\0';
 1116:     s=++in;
 1117:   }
 1118:  
 1119:   if (s == t) {/* occ not found */
 1120:     *(alocc-(in-s))='\0';
 1121:     in=s;
 1122:   }
 1123:   while ( *in != '\0'){
 1124:     *blocc++ = *in++;
 1125:   }
 1126: 
 1127:   *blocc='\0';
 1128:   return t;
 1129: }
 1130: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1131: {
 1132:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1133:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1134:      gives blocc="abcdef2ghi" and alocc="j".
 1135:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1136:   */
 1137:   char *s, *t;
 1138:   t=in;s=in;
 1139:   while (*in != '\0'){
 1140:     while( *in == occ){
 1141:       *blocc++ = *in++;
 1142:       s=in;
 1143:     }
 1144:     *blocc++ = *in++;
 1145:   }
 1146:   if (s == t) /* occ not found */
 1147:     *(blocc-(in-s))='\0';
 1148:   else
 1149:     *(blocc-(in-s)-1)='\0';
 1150:   in=s;
 1151:   while ( *in != '\0'){
 1152:     *alocc++ = *in++;
 1153:   }
 1154: 
 1155:   *alocc='\0';
 1156:   return s;
 1157: }
 1158: 
 1159: int nbocc(char *s, char occ)
 1160: {
 1161:   int i,j=0;
 1162:   int lg=20;
 1163:   i=0;
 1164:   lg=strlen(s);
 1165:   for(i=0; i<= lg; i++) {
 1166:   if  (s[i] == occ ) j++;
 1167:   }
 1168:   return j;
 1169: }
 1170: 
 1171: /* void cutv(char *u,char *v, char*t, char occ) */
 1172: /* { */
 1173: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1174: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1175: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1176: /*   int i,lg,j,p=0; */
 1177: /*   i=0; */
 1178: /*   lg=strlen(t); */
 1179: /*   for(j=0; j<=lg-1; j++) { */
 1180: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1181: /*   } */
 1182: 
 1183: /*   for(j=0; j<p; j++) { */
 1184: /*     (u[j] = t[j]); */
 1185: /*   } */
 1186: /*      u[p]='\0'; */
 1187: 
 1188: /*    for(j=0; j<= lg; j++) { */
 1189: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1190: /*   } */
 1191: /* } */
 1192: 
 1193: #ifdef _WIN32
 1194: char * strsep(char **pp, const char *delim)
 1195: {
 1196:   char *p, *q;
 1197:          
 1198:   if ((p = *pp) == NULL)
 1199:     return 0;
 1200:   if ((q = strpbrk (p, delim)) != NULL)
 1201:   {
 1202:     *pp = q + 1;
 1203:     *q = '\0';
 1204:   }
 1205:   else
 1206:     *pp = 0;
 1207:   return p;
 1208: }
 1209: #endif
 1210: 
 1211: /********************** nrerror ********************/
 1212: 
 1213: void nrerror(char error_text[])
 1214: {
 1215:   fprintf(stderr,"ERREUR ...\n");
 1216:   fprintf(stderr,"%s\n",error_text);
 1217:   exit(EXIT_FAILURE);
 1218: }
 1219: /*********************** vector *******************/
 1220: double *vector(int nl, int nh)
 1221: {
 1222:   double *v;
 1223:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1224:   if (!v) nrerror("allocation failure in vector");
 1225:   return v-nl+NR_END;
 1226: }
 1227: 
 1228: /************************ free vector ******************/
 1229: void free_vector(double*v, int nl, int nh)
 1230: {
 1231:   free((FREE_ARG)(v+nl-NR_END));
 1232: }
 1233: 
 1234: /************************ivector *******************************/
 1235: int *ivector(long nl,long nh)
 1236: {
 1237:   int *v;
 1238:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1239:   if (!v) nrerror("allocation failure in ivector");
 1240:   return v-nl+NR_END;
 1241: }
 1242: 
 1243: /******************free ivector **************************/
 1244: void free_ivector(int *v, long nl, long nh)
 1245: {
 1246:   free((FREE_ARG)(v+nl-NR_END));
 1247: }
 1248: 
 1249: /************************lvector *******************************/
 1250: long *lvector(long nl,long nh)
 1251: {
 1252:   long *v;
 1253:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1254:   if (!v) nrerror("allocation failure in ivector");
 1255:   return v-nl+NR_END;
 1256: }
 1257: 
 1258: /******************free lvector **************************/
 1259: void free_lvector(long *v, long nl, long nh)
 1260: {
 1261:   free((FREE_ARG)(v+nl-NR_END));
 1262: }
 1263: 
 1264: /******************* imatrix *******************************/
 1265: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1266:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1267: { 
 1268:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1269:   int **m; 
 1270:   
 1271:   /* allocate pointers to rows */ 
 1272:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1273:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1274:   m += NR_END; 
 1275:   m -= nrl; 
 1276:   
 1277:   
 1278:   /* allocate rows and set pointers to them */ 
 1279:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1280:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1281:   m[nrl] += NR_END; 
 1282:   m[nrl] -= ncl; 
 1283:   
 1284:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1285:   
 1286:   /* return pointer to array of pointers to rows */ 
 1287:   return m; 
 1288: } 
 1289: 
 1290: /****************** free_imatrix *************************/
 1291: void free_imatrix(m,nrl,nrh,ncl,nch)
 1292:       int **m;
 1293:       long nch,ncl,nrh,nrl; 
 1294:      /* free an int matrix allocated by imatrix() */ 
 1295: { 
 1296:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1297:   free((FREE_ARG) (m+nrl-NR_END)); 
 1298: } 
 1299: 
 1300: /******************* matrix *******************************/
 1301: double **matrix(long nrl, long nrh, long ncl, long nch)
 1302: {
 1303:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1304:   double **m;
 1305: 
 1306:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1307:   if (!m) nrerror("allocation failure 1 in matrix()");
 1308:   m += NR_END;
 1309:   m -= nrl;
 1310: 
 1311:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1312:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1313:   m[nrl] += NR_END;
 1314:   m[nrl] -= ncl;
 1315: 
 1316:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1317:   return m;
 1318:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1319: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1320: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1321:    */
 1322: }
 1323: 
 1324: /*************************free matrix ************************/
 1325: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1326: {
 1327:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1328:   free((FREE_ARG)(m+nrl-NR_END));
 1329: }
 1330: 
 1331: /******************* ma3x *******************************/
 1332: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1333: {
 1334:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1335:   double ***m;
 1336: 
 1337:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1338:   if (!m) nrerror("allocation failure 1 in matrix()");
 1339:   m += NR_END;
 1340:   m -= nrl;
 1341: 
 1342:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1343:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1344:   m[nrl] += NR_END;
 1345:   m[nrl] -= ncl;
 1346: 
 1347:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1348: 
 1349:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1350:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1351:   m[nrl][ncl] += NR_END;
 1352:   m[nrl][ncl] -= nll;
 1353:   for (j=ncl+1; j<=nch; j++) 
 1354:     m[nrl][j]=m[nrl][j-1]+nlay;
 1355:   
 1356:   for (i=nrl+1; i<=nrh; i++) {
 1357:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1358:     for (j=ncl+1; j<=nch; j++) 
 1359:       m[i][j]=m[i][j-1]+nlay;
 1360:   }
 1361:   return m; 
 1362:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1363:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1364:   */
 1365: }
 1366: 
 1367: /*************************free ma3x ************************/
 1368: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1369: {
 1370:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1371:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1372:   free((FREE_ARG)(m+nrl-NR_END));
 1373: }
 1374: 
 1375: /*************** function subdirf ***********/
 1376: char *subdirf(char fileres[])
 1377: {
 1378:   /* Caution optionfilefiname is hidden */
 1379:   strcpy(tmpout,optionfilefiname);
 1380:   strcat(tmpout,"/"); /* Add to the right */
 1381:   strcat(tmpout,fileres);
 1382:   return tmpout;
 1383: }
 1384: 
 1385: /*************** function subdirf2 ***********/
 1386: char *subdirf2(char fileres[], char *preop)
 1387: {
 1388:   
 1389:   /* Caution optionfilefiname is hidden */
 1390:   strcpy(tmpout,optionfilefiname);
 1391:   strcat(tmpout,"/");
 1392:   strcat(tmpout,preop);
 1393:   strcat(tmpout,fileres);
 1394:   return tmpout;
 1395: }
 1396: 
 1397: /*************** function subdirf3 ***********/
 1398: char *subdirf3(char fileres[], char *preop, char *preop2)
 1399: {
 1400:   
 1401:   /* Caution optionfilefiname is hidden */
 1402:   strcpy(tmpout,optionfilefiname);
 1403:   strcat(tmpout,"/");
 1404:   strcat(tmpout,preop);
 1405:   strcat(tmpout,preop2);
 1406:   strcat(tmpout,fileres);
 1407:   return tmpout;
 1408: }
 1409:  
 1410: /*************** function subdirfext ***********/
 1411: char *subdirfext(char fileres[], char *preop, char *postop)
 1412: {
 1413:   
 1414:   strcpy(tmpout,preop);
 1415:   strcat(tmpout,fileres);
 1416:   strcat(tmpout,postop);
 1417:   return tmpout;
 1418: }
 1419: 
 1420: /*************** function subdirfext3 ***********/
 1421: char *subdirfext3(char fileres[], char *preop, char *postop)
 1422: {
 1423:   
 1424:   /* Caution optionfilefiname is hidden */
 1425:   strcpy(tmpout,optionfilefiname);
 1426:   strcat(tmpout,"/");
 1427:   strcat(tmpout,preop);
 1428:   strcat(tmpout,fileres);
 1429:   strcat(tmpout,postop);
 1430:   return tmpout;
 1431: }
 1432:  
 1433: char *asc_diff_time(long time_sec, char ascdiff[])
 1434: {
 1435:   long sec_left, days, hours, minutes;
 1436:   days = (time_sec) / (60*60*24);
 1437:   sec_left = (time_sec) % (60*60*24);
 1438:   hours = (sec_left) / (60*60) ;
 1439:   sec_left = (sec_left) %(60*60);
 1440:   minutes = (sec_left) /60;
 1441:   sec_left = (sec_left) % (60);
 1442:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1443:   return ascdiff;
 1444: }
 1445: 
 1446: /***************** f1dim *************************/
 1447: extern int ncom; 
 1448: extern double *pcom,*xicom;
 1449: extern double (*nrfunc)(double []); 
 1450:  
 1451: double f1dim(double x) 
 1452: { 
 1453:   int j; 
 1454:   double f;
 1455:   double *xt; 
 1456:  
 1457:   xt=vector(1,ncom); 
 1458:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1459:   f=(*nrfunc)(xt); 
 1460:   free_vector(xt,1,ncom); 
 1461:   return f; 
 1462: } 
 1463: 
 1464: /*****************brent *************************/
 1465: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1466: {
 1467:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1468:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1469:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1470:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1471:    * returned function value. 
 1472:   */
 1473:   int iter; 
 1474:   double a,b,d,etemp;
 1475:   double fu=0,fv,fw,fx;
 1476:   double ftemp=0.;
 1477:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1478:   double e=0.0; 
 1479:  
 1480:   a=(ax < cx ? ax : cx); 
 1481:   b=(ax > cx ? ax : cx); 
 1482:   x=w=v=bx; 
 1483:   fw=fv=fx=(*f)(x); 
 1484:   for (iter=1;iter<=ITMAX;iter++) { 
 1485:     xm=0.5*(a+b); 
 1486:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1487:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1488:     printf(".");fflush(stdout);
 1489:     fprintf(ficlog,".");fflush(ficlog);
 1490: #ifdef DEBUGBRENT
 1491:     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);
 1492:     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);
 1493:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1494: #endif
 1495:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1496:       *xmin=x; 
 1497:       return fx; 
 1498:     } 
 1499:     ftemp=fu;
 1500:     if (fabs(e) > tol1) { 
 1501:       r=(x-w)*(fx-fv); 
 1502:       q=(x-v)*(fx-fw); 
 1503:       p=(x-v)*q-(x-w)*r; 
 1504:       q=2.0*(q-r); 
 1505:       if (q > 0.0) p = -p; 
 1506:       q=fabs(q); 
 1507:       etemp=e; 
 1508:       e=d; 
 1509:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1510: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1511:       else { 
 1512: 	d=p/q; 
 1513: 	u=x+d; 
 1514: 	if (u-a < tol2 || b-u < tol2) 
 1515: 	  d=SIGN(tol1,xm-x); 
 1516:       } 
 1517:     } else { 
 1518:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1519:     } 
 1520:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1521:     fu=(*f)(u); 
 1522:     if (fu <= fx) { 
 1523:       if (u >= x) a=x; else b=x; 
 1524:       SHFT(v,w,x,u) 
 1525:       SHFT(fv,fw,fx,fu) 
 1526:     } else { 
 1527:       if (u < x) a=u; else b=u; 
 1528:       if (fu <= fw || w == x) { 
 1529: 	v=w; 
 1530: 	w=u; 
 1531: 	fv=fw; 
 1532: 	fw=fu; 
 1533:       } else if (fu <= fv || v == x || v == w) { 
 1534: 	v=u; 
 1535: 	fv=fu; 
 1536:       } 
 1537:     } 
 1538:   } 
 1539:   nrerror("Too many iterations in brent"); 
 1540:   *xmin=x; 
 1541:   return fx; 
 1542: } 
 1543: 
 1544: /****************** mnbrak ***********************/
 1545: 
 1546: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1547: 	    double (*func)(double)) 
 1548: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1549: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1550: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1551: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1552:    */
 1553:   double ulim,u,r,q, dum;
 1554:   double fu; 
 1555: 
 1556:   double scale=10.;
 1557:   int iterscale=0;
 1558: 
 1559:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1560:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1561: 
 1562: 
 1563:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1564:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1565:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1566:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1567:   /* } */
 1568: 
 1569:   if (*fb > *fa) { 
 1570:     SHFT(dum,*ax,*bx,dum) 
 1571:     SHFT(dum,*fb,*fa,dum) 
 1572:   } 
 1573:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1574:   *fc=(*func)(*cx); 
 1575: #ifdef DEBUG
 1576:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1577:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1578: #endif
 1579:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1580:     r=(*bx-*ax)*(*fb-*fc); 
 1581:     q=(*bx-*cx)*(*fb-*fa); 
 1582:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1583:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1584:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1585:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1586:       fu=(*func)(u); 
 1587: #ifdef DEBUG
 1588:       /* f(x)=A(x-u)**2+f(u) */
 1589:       double A, fparabu; 
 1590:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1591:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1592:       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);
 1593:       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);
 1594:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1595:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1596:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1597:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1598: #endif 
 1599: #ifdef MNBRAKORIGINAL
 1600: #else
 1601: /*       if (fu > *fc) { */
 1602: /* #ifdef DEBUG */
 1603: /*       printf("mnbrak4  fu > fc \n"); */
 1604: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1605: /* #endif */
 1606: /* 	/\* 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 *\\/  *\/ */
 1607: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1608: /* 	dum=u; /\* Shifting c and u *\/ */
 1609: /* 	u = *cx; */
 1610: /* 	*cx = dum; */
 1611: /* 	dum = fu; */
 1612: /* 	fu = *fc; */
 1613: /* 	*fc =dum; */
 1614: /*       } else { /\* end *\/ */
 1615: /* #ifdef DEBUG */
 1616: /*       printf("mnbrak3  fu < fc \n"); */
 1617: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1618: /* #endif */
 1619: /* 	dum=u; /\* Shifting c and u *\/ */
 1620: /* 	u = *cx; */
 1621: /* 	*cx = dum; */
 1622: /* 	dum = fu; */
 1623: /* 	fu = *fc; */
 1624: /* 	*fc =dum; */
 1625: /*       } */
 1626: #ifdef DEBUG
 1627:       printf("mnbrak34  fu < or >= fc \n");
 1628:       fprintf(ficlog, "mnbrak34 fu < fc\n");
 1629: #endif
 1630:       dum=u; /* Shifting c and u */
 1631:       u = *cx;
 1632:       *cx = dum;
 1633:       dum = fu;
 1634:       fu = *fc;
 1635:       *fc =dum;
 1636: #endif
 1637:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1638: #ifdef DEBUG
 1639:       printf("mnbrak2  u after c but before ulim\n");
 1640:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1641: #endif
 1642:       fu=(*func)(u); 
 1643:       if (fu < *fc) { 
 1644: #ifdef DEBUG
 1645:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1646:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1647: #endif
 1648: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1649: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1650:       } 
 1651:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1652: #ifdef DEBUG
 1653:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1654:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1655: #endif
 1656:       u=ulim; 
 1657:       fu=(*func)(u); 
 1658:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1659: #ifdef DEBUG
 1660:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1661:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1662: #endif
 1663:       u=(*cx)+GOLD*(*cx-*bx); 
 1664:       fu=(*func)(u); 
 1665:     } /* end tests */
 1666:     SHFT(*ax,*bx,*cx,u) 
 1667:     SHFT(*fa,*fb,*fc,fu) 
 1668: #ifdef DEBUG
 1669:       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);
 1670:       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);
 1671: #endif
 1672:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1673: } 
 1674: 
 1675: /*************** linmin ************************/
 1676: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1677: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1678: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1679: the value of func at the returned location p . This is actually all accomplished by calling the
 1680: routines mnbrak and brent .*/
 1681: int ncom; 
 1682: double *pcom,*xicom;
 1683: double (*nrfunc)(double []); 
 1684:  
 1685: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1686: { 
 1687:   double brent(double ax, double bx, double cx, 
 1688: 	       double (*f)(double), double tol, double *xmin); 
 1689:   double f1dim(double x); 
 1690:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1691: 	      double *fc, double (*func)(double)); 
 1692:   int j; 
 1693:   double xx,xmin,bx,ax; 
 1694:   double fx,fb,fa;
 1695: 
 1696: #ifdef LINMINORIGINAL
 1697: #else
 1698:   double scale=10., axs, xxs; /* Scale added for infinity */
 1699: #endif
 1700:   
 1701:   ncom=n; 
 1702:   pcom=vector(1,n); 
 1703:   xicom=vector(1,n); 
 1704:   nrfunc=func; 
 1705:   for (j=1;j<=n;j++) { 
 1706:     pcom[j]=p[j]; 
 1707:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1708:   } 
 1709: 
 1710: #ifdef LINMINORIGINAL
 1711:   xx=1.;
 1712: #else
 1713:   axs=0.0;
 1714:   xxs=1.;
 1715:   do{
 1716:     xx= xxs;
 1717: #endif
 1718:     ax=0.;
 1719:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1720:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1721:     /* 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))   */
 1722:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1723:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1724:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1725:     /* 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]]*/
 1726: #ifdef LINMINORIGINAL
 1727: #else
 1728:     if (fx != fx){
 1729:   	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1730: 	printf("|");
 1731: 	fprintf(ficlog,"|");
 1732: #ifdef DEBUGLINMIN
 1733:   	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);
 1734: #endif
 1735:     }
 1736:   }while(fx != fx);
 1737: #endif
 1738:   
 1739: #ifdef DEBUGLINMIN
 1740:   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);
 1741:   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);
 1742: #endif
 1743:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1744:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1745:   /* fmin = f(p[j] + xmin * xi[j]) */
 1746:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1747:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1748: #ifdef DEBUG
 1749:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1750:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1751: #endif
 1752: #ifdef DEBUGLINMIN
 1753:   printf("linmin end ");
 1754:   fprintf(ficlog,"linmin end ");
 1755: #endif
 1756:   for (j=1;j<=n;j++) { 
 1757: #ifdef LINMINORIGINAL
 1758:     xi[j] *= xmin; 
 1759: #else
 1760: #ifdef DEBUGLINMIN
 1761:     if(xxs <1.0)
 1762:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1763: #endif
 1764:     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) */
 1765: #ifdef DEBUGLINMIN
 1766:     if(xxs <1.0)
 1767:       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 );
 1768: #endif
 1769: #endif
 1770:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1771:   } 
 1772: #ifdef DEBUGLINMIN
 1773:   printf("\n");
 1774:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1775:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1776:   for (j=1;j<=n;j++) { 
 1777:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1778:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1779:     if(j % ncovmodel == 0){
 1780:       printf("\n");
 1781:       fprintf(ficlog,"\n");
 1782:     }
 1783:   }
 1784: #else
 1785: #endif
 1786:   free_vector(xicom,1,n); 
 1787:   free_vector(pcom,1,n); 
 1788: } 
 1789: 
 1790: 
 1791: /*************** powell ************************/
 1792: /*
 1793: Minimization of a function func of n variables. Input consists of an initial starting point
 1794: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1795: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1796: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1797: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1798: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1799:  */
 1800: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1801: 	    double (*func)(double [])) 
 1802: { 
 1803:   void linmin(double p[], double xi[], int n, double *fret, 
 1804: 	      double (*func)(double [])); 
 1805:   int i,ibig,j; 
 1806:   double del,t,*pt,*ptt,*xit;
 1807:   double directest;
 1808:   double fp,fptt;
 1809:   double *xits;
 1810:   int niterf, itmp;
 1811: 
 1812:   pt=vector(1,n); 
 1813:   ptt=vector(1,n); 
 1814:   xit=vector(1,n); 
 1815:   xits=vector(1,n); 
 1816:   *fret=(*func)(p); 
 1817:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1818:   rcurr_time = time(NULL);  
 1819:   for (*iter=1;;++(*iter)) { 
 1820:     fp=(*fret); /* From former iteration or initial value */
 1821:     ibig=0; 
 1822:     del=0.0; 
 1823:     rlast_time=rcurr_time;
 1824:     /* (void) gettimeofday(&curr_time,&tzp); */
 1825:     rcurr_time = time(NULL);  
 1826:     curr_time = *localtime(&rcurr_time);
 1827:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1828:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1829: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1830:     for (i=1;i<=n;i++) {
 1831:       printf(" %d %.12f",i, p[i]);
 1832:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1833:       fprintf(ficrespow," %.12lf", p[i]);
 1834:     }
 1835:     printf("\n");
 1836:     fprintf(ficlog,"\n");
 1837:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1838:     if(*iter <=3){
 1839:       tml = *localtime(&rcurr_time);
 1840:       strcpy(strcurr,asctime(&tml));
 1841:       rforecast_time=rcurr_time; 
 1842:       itmp = strlen(strcurr);
 1843:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1844: 	strcurr[itmp-1]='\0';
 1845:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1846:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1847:       for(niterf=10;niterf<=30;niterf+=10){
 1848: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1849: 	forecast_time = *localtime(&rforecast_time);
 1850: 	strcpy(strfor,asctime(&forecast_time));
 1851: 	itmp = strlen(strfor);
 1852: 	if(strfor[itmp-1]=='\n')
 1853: 	strfor[itmp-1]='\0';
 1854: 	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);
 1855: 	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);
 1856:       }
 1857:     }
 1858:     for (i=1;i<=n;i++) { /* For each direction i */
 1859:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1860:       fptt=(*fret); 
 1861: #ifdef DEBUG
 1862:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1863:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1864: #endif
 1865:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1866:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1867:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1868: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1869:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1870: 	/* because that direction will be replaced unless the gain del is small */
 1871: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1872: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1873: 	/* with the new direction. */
 1874: 	del=fabs(fptt-(*fret)); 
 1875: 	ibig=i; 
 1876:       } 
 1877: #ifdef DEBUG
 1878:       printf("%d %.12e",i,(*fret));
 1879:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1880:       for (j=1;j<=n;j++) {
 1881: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1882: 	printf(" x(%d)=%.12e",j,xit[j]);
 1883: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1884:       }
 1885:       for(j=1;j<=n;j++) {
 1886: 	printf(" p(%d)=%.12e",j,p[j]);
 1887: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1888:       }
 1889:       printf("\n");
 1890:       fprintf(ficlog,"\n");
 1891: #endif
 1892:     } /* end loop on each direction i */
 1893:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1894:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1895:     /* New value of last point Pn is not computed, P(n-1) */
 1896:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1897:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1898:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1899:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1900:       /* decreased of more than 3.84  */
 1901:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1902:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1903:       /* By adding 10 parameters more the gain should be 18.31 */
 1904: 
 1905:       /* Starting the program with initial values given by a former maximization will simply change */
 1906:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1907:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1908:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1909: #ifdef DEBUG
 1910:       int k[2],l;
 1911:       k[0]=1;
 1912:       k[1]=-1;
 1913:       printf("Max: %.12e",(*func)(p));
 1914:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1915:       for (j=1;j<=n;j++) {
 1916: 	printf(" %.12e",p[j]);
 1917: 	fprintf(ficlog," %.12e",p[j]);
 1918:       }
 1919:       printf("\n");
 1920:       fprintf(ficlog,"\n");
 1921:       for(l=0;l<=1;l++) {
 1922: 	for (j=1;j<=n;j++) {
 1923: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1924: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1925: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1926: 	}
 1927: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1928: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1929:       }
 1930: #endif
 1931: 
 1932: 
 1933:       free_vector(xit,1,n); 
 1934:       free_vector(xits,1,n); 
 1935:       free_vector(ptt,1,n); 
 1936:       free_vector(pt,1,n); 
 1937:       return; 
 1938:     } /* enough precision */ 
 1939:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1940:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1941:       ptt[j]=2.0*p[j]-pt[j]; 
 1942:       xit[j]=p[j]-pt[j]; 
 1943:       pt[j]=p[j]; 
 1944:     } 
 1945:     fptt=(*func)(ptt); /* f_3 */
 1946: #ifdef POWELLF1F3
 1947: #else
 1948:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1949: #endif
 1950:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1951:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1952:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1953:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1954:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1955:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1956:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1957: #ifdef NRCORIGINAL
 1958:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1959: #else
 1960:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1961:       t= t- del*SQR(fp-fptt);
 1962: #endif
 1963:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 1964: #ifdef DEBUG
 1965:       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);
 1966:       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);
 1967:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1968: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1969:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1970: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1971:       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);
 1972:       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);
 1973: #endif
 1974: #ifdef POWELLORIGINAL
 1975:       if (t < 0.0) { /* Then we use it for new direction */
 1976: #else
 1977:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1978: 	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);
 1979:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1980:         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);
 1981:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1982:       } 
 1983:       if (directest < 0.0) { /* Then we use it for new direction */
 1984: #endif
 1985: #ifdef DEBUGLINMIN
 1986: 	printf("Before linmin in direction P%d-P0\n",n);
 1987: 	for (j=1;j<=n;j++) { 
 1988: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1989: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1990: 	  if(j % ncovmodel == 0){
 1991: 	    printf("\n");
 1992: 	    fprintf(ficlog,"\n");
 1993: 	  }
 1994: 	}
 1995: #endif
 1996: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 1997: #ifdef DEBUGLINMIN
 1998: 	for (j=1;j<=n;j++) { 
 1999: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2000: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2001: 	  if(j % ncovmodel == 0){
 2002: 	    printf("\n");
 2003: 	    fprintf(ficlog,"\n");
 2004: 	  }
 2005: 	}
 2006: #endif
 2007: 	for (j=1;j<=n;j++) { 
 2008: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2009: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2010: 	}
 2011: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2012: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2013: 
 2014: #ifdef DEBUG
 2015: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2016: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2017: 	for(j=1;j<=n;j++){
 2018: 	  printf(" %.12e",xit[j]);
 2019: 	  fprintf(ficlog," %.12e",xit[j]);
 2020: 	}
 2021: 	printf("\n");
 2022: 	fprintf(ficlog,"\n");
 2023: #endif
 2024:       } /* end of t or directest negative */
 2025: #ifdef POWELLF1F3
 2026: #else
 2027:     } /* end if (fptt < fp)  */
 2028: #endif
 2029:   } /* loop iteration */ 
 2030: } 
 2031: 
 2032: /**** Prevalence limit (stable or period prevalence)  ****************/
 2033: 
 2034: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2035: {
 2036:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 2037:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2038:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2039:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2040:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2041:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2042:   /* Initial matrix pimij */
 2043:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2044:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2045:   /*  0,                   0                  , 1} */
 2046:   /*
 2047:    * and after some iteration: */
 2048:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2049:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2050:   /*  0,                   0                  , 1} */
 2051:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2052:   /* {0.51571254859325999, 0.4842874514067399, */
 2053:   /*  0.51326036147820708, 0.48673963852179264} */
 2054:   /* If we start from prlim again, prlim tends to a constant matrix */
 2055: 
 2056:   int i, ii,j,k;
 2057:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2058:   /* double **matprod2(); */ /* test */
 2059:   double **out, cov[NCOVMAX+1], **pmij();
 2060:   double **newm;
 2061:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2062:   int ncvloop=0;
 2063:   
 2064:   min=vector(1,nlstate);
 2065:   max=vector(1,nlstate);
 2066:   meandiff=vector(1,nlstate);
 2067: 
 2068:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2069:     for (j=1;j<=nlstate+ndeath;j++){
 2070:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2071:     }
 2072:   
 2073:   cov[1]=1.;
 2074:   
 2075:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2076:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2077:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2078:     ncvloop++;
 2079:     newm=savm;
 2080:     /* Covariates have to be included here again */
 2081:     cov[2]=agefin;
 2082:     if(nagesqr==1)
 2083:       cov[3]= agefin*agefin;;
 2084:     for (k=1; k<=cptcovn;k++) {
 2085:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2086:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2087:       /* 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])]); */
 2088:     }
 2089:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2090:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2091:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2092:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2093:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2094:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2095:     
 2096:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2097:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2098:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2099:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2100:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2101:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2102:     
 2103:     savm=oldm;
 2104:     oldm=newm;
 2105: 
 2106:     for(j=1; j<=nlstate; j++){
 2107:       max[j]=0.;
 2108:       min[j]=1.;
 2109:     }
 2110:     for(i=1;i<=nlstate;i++){
 2111:       sumnew=0;
 2112:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2113:       for(j=1; j<=nlstate; j++){ 
 2114: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2115: 	max[j]=FMAX(max[j],prlim[i][j]);
 2116: 	min[j]=FMIN(min[j],prlim[i][j]);
 2117:       }
 2118:     }
 2119: 
 2120:     maxmax=0.;
 2121:     for(j=1; j<=nlstate; j++){
 2122:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2123:       maxmax=FMAX(maxmax,meandiff[j]);
 2124:       /* 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); */
 2125:     } /* j loop */
 2126:     *ncvyear= (int)age- (int)agefin;
 2127:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2128:     if(maxmax < ftolpl){
 2129:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2130:       free_vector(min,1,nlstate);
 2131:       free_vector(max,1,nlstate);
 2132:       free_vector(meandiff,1,nlstate);
 2133:       return prlim;
 2134:     }
 2135:   } /* age loop */
 2136:     /* After some age loop it doesn't converge */
 2137:   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\
 2138: 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);
 2139:   /* 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); */
 2140:   free_vector(min,1,nlstate);
 2141:   free_vector(max,1,nlstate);
 2142:   free_vector(meandiff,1,nlstate);
 2143:   
 2144:   return prlim; /* should not reach here */
 2145: }
 2146: 
 2147: 
 2148:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2149: 
 2150: double **bprevalim(double **bprlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2151: {
 2152:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 2153:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2154:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2155:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2156:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2157:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2158:   /* Initial matrix pimij */
 2159:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2160:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2161:   /*  0,                   0                  , 1} */
 2162:   /*
 2163:    * and after some iteration: */
 2164:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2165:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2166:   /*  0,                   0                  , 1} */
 2167:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2168:   /* {0.51571254859325999, 0.4842874514067399, */
 2169:   /*  0.51326036147820708, 0.48673963852179264} */
 2170:   /* If we start from prlim again, prlim tends to a constant matrix */
 2171: 
 2172:   int i, ii,j,k;
 2173:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2174:   /* double **matprod2(); */ /* test */
 2175:   double **out, cov[NCOVMAX+1], **bmij();
 2176:   double **newm;
 2177:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2178:   int ncvloop=0;
 2179:   
 2180:   min=vector(1,nlstate);
 2181:   max=vector(1,nlstate);
 2182:   meandiff=vector(1,nlstate);
 2183: 
 2184:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2185:     for (j=1;j<=nlstate+ndeath;j++){
 2186:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2187:     }
 2188:   
 2189:   cov[1]=1.;
 2190:   
 2191:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2192:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2193:   for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){
 2194:     ncvloop++;
 2195:     newm=savm;
 2196:     /* Covariates have to be included here again */
 2197:     cov[2]=agefin;
 2198:     if(nagesqr==1)
 2199:       cov[3]= agefin*agefin;;
 2200:     for (k=1; k<=cptcovn;k++) {
 2201:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2202:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2203:       /* 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])]); */
 2204:     }
 2205:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2206:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2207:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2208:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2209:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2210:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2211:     
 2212:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2213:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2214:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2215:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2216:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2217:     out=matprod2(newm, oldm ,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate)); /* Bug Valgrind */
 2218:     
 2219:     savm=oldm;
 2220:     oldm=newm;
 2221: 
 2222:     for(j=1; j<=nlstate; j++){
 2223:       max[j]=0.;
 2224:       min[j]=1.;
 2225:     }
 2226:       /* sumnew=0; */
 2227:       /* for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k]; */
 2228:     for(j=1; j<=nlstate; j++){ 
 2229:       for(i=1;i<=nlstate;i++){
 2230: 	/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2231: 	bprlim[i][j]= newm[i][j];
 2232: 	max[i]=FMAX(max[i],bprlim[i][j]);
 2233: 	min[i]=FMIN(min[i],bprlim[i][j]);
 2234:       }
 2235:     }
 2236: 
 2237:     maxmax=0.;
 2238:     for(i=1; i<=nlstate; i++){
 2239:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2240:       maxmax=FMAX(maxmax,meandiff[i]);
 2241:       /* 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); */
 2242:     } /* j loop */
 2243:     *ncvyear= -( (int)age- (int)agefin);
 2244:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2245:     if(maxmax < ftolpl){
 2246:       printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);
 2247:       free_vector(min,1,nlstate);
 2248:       free_vector(max,1,nlstate);
 2249:       free_vector(meandiff,1,nlstate);
 2250:       return bprlim;
 2251:     }
 2252:   } /* age loop */
 2253:     /* After some age loop it doesn't converge */
 2254:   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\
 2255: 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);
 2256:   /* 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); */
 2257:   free_vector(min,1,nlstate);
 2258:   free_vector(max,1,nlstate);
 2259:   free_vector(meandiff,1,nlstate);
 2260:   
 2261:   return bprlim; /* should not reach here */
 2262: }
 2263: 
 2264: /*************** transition probabilities ***************/ 
 2265: 
 2266: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2267: {
 2268:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2269:      computes the probability to be observed in state j being in state i by appying the
 2270:      model to the ncovmodel covariates (including constant and age).
 2271:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2272:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2273:      ncth covariate in the global vector x is given by the formula:
 2274:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2275:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2276:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2277:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2278:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2279:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2280:   */
 2281:   double s1, lnpijopii;
 2282:   /*double t34;*/
 2283:   int i,j, nc, ii, jj;
 2284: 
 2285:     for(i=1; i<= nlstate; i++){
 2286:       for(j=1; j<i;j++){
 2287: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2288: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 2289: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2290: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2291: 	}
 2292: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2293: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2294:       }
 2295:       for(j=i+1; j<=nlstate+ndeath;j++){
 2296: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2297: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2298: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2299: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2300: 	}
 2301: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2302:       }
 2303:     }
 2304:     
 2305:     for(i=1; i<= nlstate; i++){
 2306:       s1=0;
 2307:       for(j=1; j<i; j++){
 2308: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2309: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2310:       }
 2311:       for(j=i+1; j<=nlstate+ndeath; j++){
 2312: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2313: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2314:       }
 2315:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2316:       ps[i][i]=1./(s1+1.);
 2317:       /* Computing other pijs */
 2318:       for(j=1; j<i; j++)
 2319: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2320:       for(j=i+1; j<=nlstate+ndeath; j++)
 2321: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2322:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2323:     } /* end i */
 2324:     
 2325:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2326:       for(jj=1; jj<= nlstate+ndeath; jj++){
 2327: 	ps[ii][jj]=0;
 2328: 	ps[ii][ii]=1;
 2329:       }
 2330:     }
 2331:     
 2332:     
 2333:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2334:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2335:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2336:     /*   } */
 2337:     /*   printf("\n "); */
 2338:     /* } */
 2339:     /* printf("\n ");printf("%lf ",cov[2]);*/
 2340:     /*
 2341:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2342:       goto end;*/
 2343:     return ps;
 2344: }
 2345: 
 2346: /*************** transition probabilities ***************/ 
 2347: 
 2348: double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2349: {
 2350:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2351:      computes the probability to be observed in state j being in state i by appying the
 2352:      model to the ncovmodel covariates (including constant and age).
 2353:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2354:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2355:      ncth covariate in the global vector x is given by the formula:
 2356:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2357:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2358:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2359:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2360:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2361:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2362:   */
 2363:   double s1, lnpijopii;
 2364:   /*double t34;*/
 2365:   int i,j, nc, ii, jj;
 2366: 
 2367:     for(i=1; i<= nlstate; i++){
 2368:       for(j=1; j<i;j++){
 2369: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2370: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 2371: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2372: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2373: 	}
 2374: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2375: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2376:       }
 2377:       for(j=i+1; j<=nlstate+ndeath;j++){
 2378: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2379: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2380: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2381: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2382: 	}
 2383: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2384:       }
 2385:     }
 2386:     
 2387:     for(i=1; i<= nlstate; i++){
 2388:       s1=0;
 2389:       for(j=1; j<i; j++){
 2390: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2391: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2392:       }
 2393:       for(j=i+1; j<=nlstate+ndeath; j++){
 2394: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2395: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2396:       }
 2397:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2398:       ps[i][i]=1./(s1+1.);
 2399:       /* Computing other pijs */
 2400:       for(j=1; j<i; j++)
 2401: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2402:       for(j=i+1; j<=nlstate+ndeath; j++)
 2403: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2404:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2405:     } /* end i */
 2406:     
 2407:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2408:       for(jj=1; jj<= nlstate+ndeath; jj++){
 2409: 	ps[ii][jj]=0;
 2410: 	ps[ii][ii]=1;
 2411:       }
 2412:     }
 2413:     /* Added for backcast */
 2414:     for(jj=1; jj<= nlstate; jj++){
 2415:       s1=0.;
 2416:       for(ii=1; ii<= nlstate; ii++){
 2417: 	s1+=ps[ii][jj];
 2418:       }
 2419:       for(ii=1; ii<= nlstate; ii++){
 2420: 	ps[ii][jj]=ps[ii][jj]/s1;
 2421:       }
 2422:     }
 2423:      
 2424:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2425:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2426:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2427:     /*   } */
 2428:     /*   printf("\n "); */
 2429:     /* } */
 2430:     /* printf("\n ");printf("%lf ",cov[2]);*/
 2431:     /*
 2432:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2433:       goto end;*/
 2434:     return ps;
 2435: }
 2436: 
 2437: 
 2438: /**************** Product of 2 matrices ******************/
 2439: 
 2440: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2441: {
 2442:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2443:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2444:   /* in, b, out are matrice of pointers which should have been initialized 
 2445:      before: only the contents of out is modified. The function returns
 2446:      a pointer to pointers identical to out */
 2447:   int i, j, k;
 2448:   for(i=nrl; i<= nrh; i++)
 2449:     for(k=ncolol; k<=ncoloh; k++){
 2450:       out[i][k]=0.;
 2451:       for(j=ncl; j<=nch; j++)
 2452:   	out[i][k] +=in[i][j]*b[j][k];
 2453:     }
 2454:   return out;
 2455: }
 2456: 
 2457: 
 2458: /************* Higher Matrix Product ***************/
 2459: 
 2460: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2461: {
 2462:   /* Computes the transition matrix starting at age 'age' over 
 2463:      'nhstepm*hstepm*stepm' months (i.e. until
 2464:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2465:      nhstepm*hstepm matrices. 
 2466:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2467:      (typically every 2 years instead of every month which is too big 
 2468:      for the memory).
 2469:      Model is determined by parameters x and covariates have to be 
 2470:      included manually here. 
 2471: 
 2472:      */
 2473: 
 2474:   int i, j, d, h, k;
 2475:   double **out, cov[NCOVMAX+1];
 2476:   double **newm;
 2477:   double agexact;
 2478:   double agebegin, ageend;
 2479: 
 2480:   /* Hstepm could be zero and should return the unit matrix */
 2481:   for (i=1;i<=nlstate+ndeath;i++)
 2482:     for (j=1;j<=nlstate+ndeath;j++){
 2483:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2484:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2485:     }
 2486:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2487:   for(h=1; h <=nhstepm; h++){
 2488:     for(d=1; d <=hstepm; d++){
 2489:       newm=savm;
 2490:       /* Covariates have to be included here again */
 2491:       cov[1]=1.;
 2492:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2493:       cov[2]=agexact;
 2494:       if(nagesqr==1)
 2495: 	cov[3]= agexact*agexact;
 2496:       for (k=1; k<=cptcovn;k++) 
 2497: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2498: 	/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2499:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2500: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2501: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2502: 	/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2503:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2504: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2505: 	/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2506: 
 2507: 
 2508:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2509:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2510:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2511: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2512:       /* if((int)age == 70){ */
 2513:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2514:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2515:       /* 	  printf("%d pmmij ",i); */
 2516:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2517:       /* 	    printf("%f ",pmmij[i][j]); */
 2518:       /* 	  } */
 2519:       /* 	  printf(" oldm "); */
 2520:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2521:       /* 	    printf("%f ",oldm[i][j]); */
 2522:       /* 	  } */
 2523:       /* 	  printf("\n"); */
 2524:       /* 	} */
 2525:       /* } */
 2526:       savm=oldm;
 2527:       oldm=newm;
 2528:     }
 2529:     for(i=1; i<=nlstate+ndeath; i++)
 2530:       for(j=1;j<=nlstate+ndeath;j++) {
 2531: 	po[i][j][h]=newm[i][j];
 2532: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2533:       }
 2534:     /*printf("h=%d ",h);*/
 2535:   } /* end h */
 2536: /*     printf("\n H=%d \n",h); */
 2537:   return po;
 2538: }
 2539: 
 2540: /************* Higher Back Matrix Product ***************/
 2541: 
 2542: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2543: {
 2544:   /* Computes the transition matrix starting at age 'age' over 
 2545:      'nhstepm*hstepm*stepm' months (i.e. until
 2546:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2547:      nhstepm*hstepm matrices. 
 2548:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2549:      (typically every 2 years instead of every month which is too big 
 2550:      for the memory).
 2551:      Model is determined by parameters x and covariates have to be 
 2552:      included manually here. 
 2553: 
 2554:      */
 2555: 
 2556:   int i, j, d, h, k;
 2557:   double **out, cov[NCOVMAX+1];
 2558:   double **newm;
 2559:   double agexact;
 2560:   double agebegin, ageend;
 2561: 
 2562:   /* Hstepm could be zero and should return the unit matrix */
 2563:   for (i=1;i<=nlstate+ndeath;i++)
 2564:     for (j=1;j<=nlstate+ndeath;j++){
 2565:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2566:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2567:     }
 2568:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2569:   for(h=1; h <=nhstepm; h++){
 2570:     for(d=1; d <=hstepm; d++){
 2571:       newm=savm;
 2572:       /* Covariates have to be included here again */
 2573:       cov[1]=1.;
 2574:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2575:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 2576:       cov[2]=agexact;
 2577:       if(nagesqr==1)
 2578: 	cov[3]= agexact*agexact;
 2579:       for (k=1; k<=cptcovn;k++) 
 2580: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2581: 	/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2582:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2583: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2584: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2585: 	/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2586:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2587: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2588: 	/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2589: 
 2590: 
 2591:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2592:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2593:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2594: 		  oldm);
 2595:       /* if((int)age == 70){ */
 2596:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2597:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2598:       /* 	  printf("%d pmmij ",i); */
 2599:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2600:       /* 	    printf("%f ",pmmij[i][j]); */
 2601:       /* 	  } */
 2602:       /* 	  printf(" oldm "); */
 2603:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2604:       /* 	    printf("%f ",oldm[i][j]); */
 2605:       /* 	  } */
 2606:       /* 	  printf("\n"); */
 2607:       /* 	} */
 2608:       /* } */
 2609:       savm=oldm;
 2610:       oldm=newm;
 2611:     }
 2612:     for(i=1; i<=nlstate+ndeath; i++)
 2613:       for(j=1;j<=nlstate+ndeath;j++) {
 2614: 	po[i][j][h]=newm[i][j];
 2615: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2616:       }
 2617:     /*printf("h=%d ",h);*/
 2618:   } /* end h */
 2619: /*     printf("\n H=%d \n",h); */
 2620:   return po;
 2621: }
 2622: 
 2623: 
 2624: #ifdef NLOPT
 2625:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2626:   double fret;
 2627:   double *xt;
 2628:   int j;
 2629:   myfunc_data *d2 = (myfunc_data *) pd;
 2630: /* xt = (p1-1); */
 2631:   xt=vector(1,n); 
 2632:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2633: 
 2634:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2635:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2636:   printf("Function = %.12lf ",fret);
 2637:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2638:   printf("\n");
 2639:  free_vector(xt,1,n);
 2640:   return fret;
 2641: }
 2642: #endif
 2643: 
 2644: /*************** log-likelihood *************/
 2645: double func( double *x)
 2646: {
 2647:   int i, ii, j, k, mi, d, kk;
 2648:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2649:   double **out;
 2650:   double sw; /* Sum of weights */
 2651:   double lli; /* Individual log likelihood */
 2652:   int s1, s2;
 2653:   double bbh, survp;
 2654:   long ipmx;
 2655:   double agexact;
 2656:   /*extern weight */
 2657:   /* We are differentiating ll according to initial status */
 2658:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2659:   /*for(i=1;i<imx;i++) 
 2660:     printf(" %d\n",s[4][i]);
 2661:   */
 2662: 
 2663:   ++countcallfunc;
 2664: 
 2665:   cov[1]=1.;
 2666: 
 2667:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2668: 
 2669:   if(mle==1){
 2670:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2671:       /* Computes the values of the ncovmodel covariates of the model
 2672: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2673: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2674: 	 to be observed in j being in i according to the model.
 2675:        */
 2676:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2677: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2678:       }
 2679:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2680: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2681: 	 has been calculated etc */
 2682:       for(mi=1; mi<= wav[i]-1; mi++){
 2683: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2684: 	  for (j=1;j<=nlstate+ndeath;j++){
 2685: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2686: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2687: 	  }
 2688: 	for(d=0; d<dh[mi][i]; d++){
 2689: 	  newm=savm;
 2690: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2691: 	  cov[2]=agexact;
 2692: 	  if(nagesqr==1)
 2693: 	    cov[3]= agexact*agexact;
 2694: 	  for (kk=1; kk<=cptcovage;kk++) {
 2695: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2696: 	  }
 2697: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2698: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2699: 	  savm=oldm;
 2700: 	  oldm=newm;
 2701: 	} /* end mult */
 2702:       
 2703: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2704: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2705: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2706: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2707: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2708: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2709: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2710: 	 * probability in order to take into account the bias as a fraction of the way
 2711: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2712: 	 * -stepm/2 to stepm/2 .
 2713: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2714: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2715: 	 */
 2716: 	s1=s[mw[mi][i]][i];
 2717: 	s2=s[mw[mi+1][i]][i];
 2718: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2719: 	/* bias bh is positive if real duration
 2720: 	 * is higher than the multiple of stepm and negative otherwise.
 2721: 	 */
 2722: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2723: 	if( s2 > nlstate){ 
 2724: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2725: 	     then the contribution to the likelihood is the probability to 
 2726: 	     die between last step unit time and current  step unit time, 
 2727: 	     which is also equal to probability to die before dh 
 2728: 	     minus probability to die before dh-stepm . 
 2729: 	     In version up to 0.92 likelihood was computed
 2730: 	as if date of death was unknown. Death was treated as any other
 2731: 	health state: the date of the interview describes the actual state
 2732: 	and not the date of a change in health state. The former idea was
 2733: 	to consider that at each interview the state was recorded
 2734: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2735: 	introduced the exact date of death then we should have modified
 2736: 	the contribution of an exact death to the likelihood. This new
 2737: 	contribution is smaller and very dependent of the step unit
 2738: 	stepm. It is no more the probability to die between last interview
 2739: 	and month of death but the probability to survive from last
 2740: 	interview up to one month before death multiplied by the
 2741: 	probability to die within a month. Thanks to Chris
 2742: 	Jackson for correcting this bug.  Former versions increased
 2743: 	mortality artificially. The bad side is that we add another loop
 2744: 	which slows down the processing. The difference can be up to 10%
 2745: 	lower mortality.
 2746: 	  */
 2747: 	/* If, at the beginning of the maximization mostly, the
 2748: 	   cumulative probability or probability to be dead is
 2749: 	   constant (ie = 1) over time d, the difference is equal to
 2750: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2751: 	   s1 at precedent wave, to be dead a month before current
 2752: 	   wave is equal to probability, being at state s1 at
 2753: 	   precedent wave, to be dead at mont of the current
 2754: 	   wave. Then the observed probability (that this person died)
 2755: 	   is null according to current estimated parameter. In fact,
 2756: 	   it should be very low but not zero otherwise the log go to
 2757: 	   infinity.
 2758: 	*/
 2759: /* #ifdef INFINITYORIGINAL */
 2760: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2761: /* #else */
 2762: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2763: /* 	    lli=log(mytinydouble); */
 2764: /* 	  else */
 2765: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2766: /* #endif */
 2767: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2768: 	  
 2769: 	} else if  ( s2==-1 ) { /* alive */
 2770: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2771: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2772: 	  /*survp += out[s1][j]; */
 2773: 	  lli= log(survp);
 2774: 	}
 2775:  	else if  (s2==-4) { 
 2776: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2777: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2778:  	  lli= log(survp); 
 2779:  	} 
 2780:  	else if  (s2==-5) { 
 2781:  	  for (j=1,survp=0. ; j<=2; j++)  
 2782: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2783:  	  lli= log(survp); 
 2784:  	} 
 2785: 	else{
 2786: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2787: 	  /*  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 */
 2788: 	} 
 2789: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2790: 	/*if(lli ==000.0)*/
 2791: 	/*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); */
 2792:   	ipmx +=1;
 2793: 	sw += weight[i];
 2794: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2795: 	/* if (lli < log(mytinydouble)){ */
 2796: 	/*   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); */
 2797: 	/*   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]); */
 2798: 	/* } */
 2799:       } /* end of wave */
 2800:     } /* end of individual */
 2801:   }  else if(mle==2){
 2802:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2803:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2804:       for(mi=1; mi<= wav[i]-1; mi++){
 2805: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2806: 	  for (j=1;j<=nlstate+ndeath;j++){
 2807: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2808: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2809: 	  }
 2810: 	for(d=0; d<=dh[mi][i]; d++){
 2811: 	  newm=savm;
 2812: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2813: 	  cov[2]=agexact;
 2814: 	  if(nagesqr==1)
 2815: 	    cov[3]= agexact*agexact;
 2816: 	  for (kk=1; kk<=cptcovage;kk++) {
 2817: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2818: 	  }
 2819: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2820: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2821: 	  savm=oldm;
 2822: 	  oldm=newm;
 2823: 	} /* end mult */
 2824:       
 2825: 	s1=s[mw[mi][i]][i];
 2826: 	s2=s[mw[mi+1][i]][i];
 2827: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2828: 	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 */
 2829: 	ipmx +=1;
 2830: 	sw += weight[i];
 2831: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2832:       } /* end of wave */
 2833:     } /* end of individual */
 2834:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2835:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2836:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2837:       for(mi=1; mi<= wav[i]-1; mi++){
 2838: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2839: 	  for (j=1;j<=nlstate+ndeath;j++){
 2840: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2841: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2842: 	  }
 2843: 	for(d=0; d<dh[mi][i]; d++){
 2844: 	  newm=savm;
 2845: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2846: 	  cov[2]=agexact;
 2847: 	  if(nagesqr==1)
 2848: 	    cov[3]= agexact*agexact;
 2849: 	  for (kk=1; kk<=cptcovage;kk++) {
 2850: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2851: 	  }
 2852: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2853: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2854: 	  savm=oldm;
 2855: 	  oldm=newm;
 2856: 	} /* end mult */
 2857:       
 2858: 	s1=s[mw[mi][i]][i];
 2859: 	s2=s[mw[mi+1][i]][i];
 2860: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2861: 	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 */
 2862: 	ipmx +=1;
 2863: 	sw += weight[i];
 2864: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2865:       } /* end of wave */
 2866:     } /* end of individual */
 2867:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2868:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2869:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2870:       for(mi=1; mi<= wav[i]-1; mi++){
 2871: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2872: 	  for (j=1;j<=nlstate+ndeath;j++){
 2873: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2874: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2875: 	  }
 2876: 	for(d=0; d<dh[mi][i]; d++){
 2877: 	  newm=savm;
 2878: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2879: 	  cov[2]=agexact;
 2880: 	  if(nagesqr==1)
 2881: 	    cov[3]= agexact*agexact;
 2882: 	  for (kk=1; kk<=cptcovage;kk++) {
 2883: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2884: 	  }
 2885: 	
 2886: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2887: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2888: 	  savm=oldm;
 2889: 	  oldm=newm;
 2890: 	} /* end mult */
 2891:       
 2892: 	s1=s[mw[mi][i]][i];
 2893: 	s2=s[mw[mi+1][i]][i];
 2894: 	if( s2 > nlstate){ 
 2895: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2896: 	} else if  ( s2==-1 ) { /* alive */
 2897: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2898: 	    survp += out[s1][j];
 2899: 	  lli= log(survp);
 2900: 	}else{
 2901: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2902: 	}
 2903: 	ipmx +=1;
 2904: 	sw += weight[i];
 2905: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2906: /* 	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]); */
 2907:       } /* end of wave */
 2908:     } /* end of individual */
 2909:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2910:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2911:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2912:       for(mi=1; mi<= wav[i]-1; mi++){
 2913: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2914: 	  for (j=1;j<=nlstate+ndeath;j++){
 2915: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2916: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2917: 	  }
 2918: 	for(d=0; d<dh[mi][i]; d++){
 2919: 	  newm=savm;
 2920: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2921: 	  cov[2]=agexact;
 2922: 	  if(nagesqr==1)
 2923: 	    cov[3]= agexact*agexact;
 2924: 	  for (kk=1; kk<=cptcovage;kk++) {
 2925: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2926: 	  }
 2927: 	
 2928: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2929: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2930: 	  savm=oldm;
 2931: 	  oldm=newm;
 2932: 	} /* end mult */
 2933:       
 2934: 	s1=s[mw[mi][i]][i];
 2935: 	s2=s[mw[mi+1][i]][i];
 2936: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2937: 	ipmx +=1;
 2938: 	sw += weight[i];
 2939: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2940: 	/*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]);*/
 2941:       } /* end of wave */
 2942:     } /* end of individual */
 2943:   } /* End of if */
 2944:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2945:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2946:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2947:   return -l;
 2948: }
 2949: 
 2950: /*************** log-likelihood *************/
 2951: double funcone( double *x)
 2952: {
 2953:   /* Same as likeli but slower because of a lot of printf and if */
 2954:   int i, ii, j, k, mi, d, kk;
 2955:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2956:   double **out;
 2957:   double lli; /* Individual log likelihood */
 2958:   double llt;
 2959:   int s1, s2;
 2960:   double bbh, survp;
 2961:   double agexact;
 2962:   double agebegin, ageend;
 2963:   /*extern weight */
 2964:   /* We are differentiating ll according to initial status */
 2965:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2966:   /*for(i=1;i<imx;i++) 
 2967:     printf(" %d\n",s[4][i]);
 2968:   */
 2969:   cov[1]=1.;
 2970: 
 2971:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2972: 
 2973:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2974:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2975:     for(mi=1; mi<= wav[i]-1; mi++){
 2976:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2977: 	for (j=1;j<=nlstate+ndeath;j++){
 2978: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2979: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2980: 	}
 2981:       
 2982:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 2983:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 2984:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 2985: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2986: 	  and mw[mi+1][i]. dh depends on stepm.*/
 2987: 	newm=savm;
 2988: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2989: 	cov[2]=agexact;
 2990: 	if(nagesqr==1)
 2991: 	  cov[3]= agexact*agexact;
 2992: 	for (kk=1; kk<=cptcovage;kk++) {
 2993: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2994: 	}
 2995: 
 2996: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2997: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2998: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2999: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3000: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3001: 	savm=oldm;
 3002: 	oldm=newm;
 3003:       } /* end mult */
 3004:       
 3005:       s1=s[mw[mi][i]][i];
 3006:       s2=s[mw[mi+1][i]][i];
 3007:       /* if(s2==-1){ */
 3008:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3009:       /* 	/\* exit(1); *\/ */
 3010:       /* } */
 3011:       bbh=(double)bh[mi][i]/(double)stepm; 
 3012:       /* bias is positive if real duration
 3013:        * is higher than the multiple of stepm and negative otherwise.
 3014:        */
 3015:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3016: 	lli=log(out[s1][s2] - savm[s1][s2]);
 3017:       } else if  ( s2==-1 ) { /* alive */
 3018: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 3019: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3020: 	lli= log(survp);
 3021:       }else if (mle==1){
 3022: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3023:       } else if(mle==2){
 3024: 	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 */
 3025:       } else if(mle==3){  /* exponential inter-extrapolation */
 3026: 	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 */
 3027:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3028: 	lli=log(out[s1][s2]); /* Original formula */
 3029:       } else{  /* mle=0 back to 1 */
 3030: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3031: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 3032:       } /* End of if */
 3033:       ipmx +=1;
 3034:       sw += weight[i];
 3035:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3036:       /*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]); */
 3037:       if(globpr){
 3038: 	fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
 3039:  %11.6f %11.6f %11.6f ", \
 3040: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3041: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3042: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3043: 	  llt +=ll[k]*gipmx/gsw;
 3044: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3045: 	}
 3046: 	fprintf(ficresilk," %10.6f\n", -llt);
 3047:       }
 3048:     } /* end of wave */
 3049:   } /* end of individual */
 3050:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3051:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3052:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3053:   if(globpr==0){ /* First time we count the contributions and weights */
 3054:     gipmx=ipmx;
 3055:     gsw=sw;
 3056:   }
 3057:   return -l;
 3058: }
 3059: 
 3060: 
 3061: /*************** function likelione ***********/
 3062: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3063: {
 3064:   /* This routine should help understanding what is done with 
 3065:      the selection of individuals/waves and
 3066:      to check the exact contribution to the likelihood.
 3067:      Plotting could be done.
 3068:    */
 3069:   int k;
 3070: 
 3071:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3072:     strcpy(fileresilk,"ILK_"); 
 3073:     strcat(fileresilk,fileresu);
 3074:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3075:       printf("Problem with resultfile: %s\n", fileresilk);
 3076:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3077:     }
 3078:     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");
 3079:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3080:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3081:     for(k=1; k<=nlstate; k++) 
 3082:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3083:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3084:   }
 3085: 
 3086:   *fretone=(*funcone)(p);
 3087:   if(*globpri !=0){
 3088:     fclose(ficresilk);
 3089:     if (mle ==0)
 3090:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3091:     else if(mle >=1)
 3092:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3093:     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));
 3094:     
 3095:       
 3096:     for (k=1; k<= nlstate ; k++) {
 3097:       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> \
 3098: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3099:     }
 3100:     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> \
 3101: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3102:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3103: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3104:     fflush(fichtm);
 3105:   }
 3106:   return;
 3107: }
 3108: 
 3109: 
 3110: /*********** Maximum Likelihood Estimation ***************/
 3111: 
 3112: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3113: {
 3114:   int i,j, iter=0;
 3115:   double **xi;
 3116:   double fret;
 3117:   double fretone; /* Only one call to likelihood */
 3118:   /*  char filerespow[FILENAMELENGTH];*/
 3119: 
 3120: #ifdef NLOPT
 3121:   int creturn;
 3122:   nlopt_opt opt;
 3123:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3124:   double *lb;
 3125:   double minf; /* the minimum objective value, upon return */
 3126:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3127:   myfunc_data dinst, *d = &dinst;
 3128: #endif
 3129: 
 3130: 
 3131:   xi=matrix(1,npar,1,npar);
 3132:   for (i=1;i<=npar;i++)
 3133:     for (j=1;j<=npar;j++)
 3134:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3135:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3136:   strcpy(filerespow,"POW_"); 
 3137:   strcat(filerespow,fileres);
 3138:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3139:     printf("Problem with resultfile: %s\n", filerespow);
 3140:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3141:   }
 3142:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3143:   for (i=1;i<=nlstate;i++)
 3144:     for(j=1;j<=nlstate+ndeath;j++)
 3145:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3146:   fprintf(ficrespow,"\n");
 3147: #ifdef POWELL
 3148:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3149: #endif
 3150: 
 3151: #ifdef NLOPT
 3152: #ifdef NEWUOA
 3153:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3154: #else
 3155:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3156: #endif
 3157:   lb=vector(0,npar-1);
 3158:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3159:   nlopt_set_lower_bounds(opt, lb);
 3160:   nlopt_set_initial_step1(opt, 0.1);
 3161:   
 3162:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3163:   d->function = func;
 3164:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3165:   nlopt_set_min_objective(opt, myfunc, d);
 3166:   nlopt_set_xtol_rel(opt, ftol);
 3167:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3168:     printf("nlopt failed! %d\n",creturn); 
 3169:   }
 3170:   else {
 3171:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3172:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3173:     iter=1; /* not equal */
 3174:   }
 3175:   nlopt_destroy(opt);
 3176: #endif
 3177:   free_matrix(xi,1,npar,1,npar);
 3178:   fclose(ficrespow);
 3179:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3180:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3181:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3182: 
 3183: }
 3184: 
 3185: /**** Computes Hessian and covariance matrix ***/
 3186: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3187: {
 3188:   double  **a,**y,*x,pd;
 3189:   /* double **hess; */
 3190:   int i, j;
 3191:   int *indx;
 3192: 
 3193:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3194:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3195:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3196:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3197:   double gompertz(double p[]);
 3198:   /* hess=matrix(1,npar,1,npar); */
 3199: 
 3200:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3201:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3202:   for (i=1;i<=npar;i++){
 3203:     printf("%d-",i);fflush(stdout);
 3204:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3205:    
 3206:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3207:     
 3208:     /*  printf(" %f ",p[i]);
 3209: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3210:   }
 3211:   
 3212:   for (i=1;i<=npar;i++) {
 3213:     for (j=1;j<=npar;j++)  {
 3214:       if (j>i) { 
 3215: 	printf(".%d-%d",i,j);fflush(stdout);
 3216: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3217: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3218: 	
 3219: 	hess[j][i]=hess[i][j];    
 3220: 	/*printf(" %lf ",hess[i][j]);*/
 3221:       }
 3222:     }
 3223:   }
 3224:   printf("\n");
 3225:   fprintf(ficlog,"\n");
 3226: 
 3227:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3228:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3229:   
 3230:   a=matrix(1,npar,1,npar);
 3231:   y=matrix(1,npar,1,npar);
 3232:   x=vector(1,npar);
 3233:   indx=ivector(1,npar);
 3234:   for (i=1;i<=npar;i++)
 3235:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3236:   ludcmp(a,npar,indx,&pd);
 3237: 
 3238:   for (j=1;j<=npar;j++) {
 3239:     for (i=1;i<=npar;i++) x[i]=0;
 3240:     x[j]=1;
 3241:     lubksb(a,npar,indx,x);
 3242:     for (i=1;i<=npar;i++){ 
 3243:       matcov[i][j]=x[i];
 3244:     }
 3245:   }
 3246: 
 3247:   printf("\n#Hessian matrix#\n");
 3248:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3249:   for (i=1;i<=npar;i++) { 
 3250:     for (j=1;j<=npar;j++) { 
 3251:       printf("%.6e ",hess[i][j]);
 3252:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3253:     }
 3254:     printf("\n");
 3255:     fprintf(ficlog,"\n");
 3256:   }
 3257: 
 3258:   /* printf("\n#Covariance matrix#\n"); */
 3259:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3260:   /* for (i=1;i<=npar;i++) {  */
 3261:   /*   for (j=1;j<=npar;j++) {  */
 3262:   /*     printf("%.6e ",matcov[i][j]); */
 3263:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3264:   /*   } */
 3265:   /*   printf("\n"); */
 3266:   /*   fprintf(ficlog,"\n"); */
 3267:   /* } */
 3268: 
 3269:   /* Recompute Inverse */
 3270:   /* for (i=1;i<=npar;i++) */
 3271:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3272:   /* ludcmp(a,npar,indx,&pd); */
 3273: 
 3274:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3275: 
 3276:   /* for (j=1;j<=npar;j++) { */
 3277:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3278:   /*   x[j]=1; */
 3279:   /*   lubksb(a,npar,indx,x); */
 3280:   /*   for (i=1;i<=npar;i++){  */
 3281:   /*     y[i][j]=x[i]; */
 3282:   /*     printf("%.3e ",y[i][j]); */
 3283:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3284:   /*   } */
 3285:   /*   printf("\n"); */
 3286:   /*   fprintf(ficlog,"\n"); */
 3287:   /* } */
 3288: 
 3289:   /* Verifying the inverse matrix */
 3290: #ifdef DEBUGHESS
 3291:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3292: 
 3293:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3294:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3295: 
 3296:   for (j=1;j<=npar;j++) {
 3297:     for (i=1;i<=npar;i++){ 
 3298:       printf("%.2f ",y[i][j]);
 3299:       fprintf(ficlog,"%.2f ",y[i][j]);
 3300:     }
 3301:     printf("\n");
 3302:     fprintf(ficlog,"\n");
 3303:   }
 3304: #endif
 3305: 
 3306:   free_matrix(a,1,npar,1,npar);
 3307:   free_matrix(y,1,npar,1,npar);
 3308:   free_vector(x,1,npar);
 3309:   free_ivector(indx,1,npar);
 3310:   /* free_matrix(hess,1,npar,1,npar); */
 3311: 
 3312: 
 3313: }
 3314: 
 3315: /*************** hessian matrix ****************/
 3316: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3317: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3318:   int i;
 3319:   int l=1, lmax=20;
 3320:   double k1,k2, res, fx;
 3321:   double p2[MAXPARM+1]; /* identical to x */
 3322:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3323:   int k=0,kmax=10;
 3324:   double l1;
 3325: 
 3326:   fx=func(x);
 3327:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3328:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3329:     l1=pow(10,l);
 3330:     delts=delt;
 3331:     for(k=1 ; k <kmax; k=k+1){
 3332:       delt = delta*(l1*k);
 3333:       p2[theta]=x[theta] +delt;
 3334:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3335:       p2[theta]=x[theta]-delt;
 3336:       k2=func(p2)-fx;
 3337:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3338:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3339:       
 3340: #ifdef DEBUGHESSII
 3341:       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);
 3342:       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);
 3343: #endif
 3344:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3345:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3346: 	k=kmax;
 3347:       }
 3348:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3349: 	k=kmax; l=lmax*10;
 3350:       }
 3351:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3352: 	delts=delt;
 3353:       }
 3354:     } /* End loop k */
 3355:   }
 3356:   delti[theta]=delts;
 3357:   return res; 
 3358:   
 3359: }
 3360: 
 3361: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3362: {
 3363:   int i;
 3364:   int l=1, lmax=20;
 3365:   double k1,k2,k3,k4,res,fx;
 3366:   double p2[MAXPARM+1];
 3367:   int k, kmax=1;
 3368:   double v1, v2, cv12, lc1, lc2;
 3369: 
 3370:   int firstime=0;
 3371:   
 3372:   fx=func(x);
 3373:   for (k=1; k<=kmax; k=k+10) {
 3374:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3375:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3376:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3377:     k1=func(p2)-fx;
 3378:   
 3379:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3380:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3381:     k2=func(p2)-fx;
 3382:   
 3383:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3384:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3385:     k3=func(p2)-fx;
 3386:   
 3387:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3388:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3389:     k4=func(p2)-fx;
 3390:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3391:     if(k1*k2*k3*k4 <0.){
 3392:       firstime=1;
 3393:       kmax=kmax+10;
 3394:     }
 3395:     if(kmax >=10 || firstime ==1){
 3396:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
 3397:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
 3398:       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);
 3399:       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);
 3400:     }
 3401: #ifdef DEBUGHESSIJ
 3402:     v1=hess[thetai][thetai];
 3403:     v2=hess[thetaj][thetaj];
 3404:     cv12=res;
 3405:     /* Computing eigen value of Hessian matrix */
 3406:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3407:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3408:     if ((lc2 <0) || (lc1 <0) ){
 3409:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3410:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3411:       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);
 3412:       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);
 3413:     }
 3414: #endif
 3415:   }
 3416:   return res;
 3417: }
 3418: 
 3419:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3420: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3421: /* { */
 3422: /*   int i; */
 3423: /*   int l=1, lmax=20; */
 3424: /*   double k1,k2,k3,k4,res,fx; */
 3425: /*   double p2[MAXPARM+1]; */
 3426: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3427: /*   int k=0,kmax=10; */
 3428: /*   double l1; */
 3429:   
 3430: /*   fx=func(x); */
 3431: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3432: /*     l1=pow(10,l); */
 3433: /*     delts=delt; */
 3434: /*     for(k=1 ; k <kmax; k=k+1){ */
 3435: /*       delt = delti*(l1*k); */
 3436: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3437: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3438: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3439: /*       k1=func(p2)-fx; */
 3440:       
 3441: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3442: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3443: /*       k2=func(p2)-fx; */
 3444:       
 3445: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3446: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3447: /*       k3=func(p2)-fx; */
 3448:       
 3449: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3450: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3451: /*       k4=func(p2)-fx; */
 3452: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3453: /* #ifdef DEBUGHESSIJ */
 3454: /*       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); */
 3455: /*       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); */
 3456: /* #endif */
 3457: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3458: /* 	k=kmax; */
 3459: /*       } */
 3460: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3461: /* 	k=kmax; l=lmax*10; */
 3462: /*       } */
 3463: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3464: /* 	delts=delt; */
 3465: /*       } */
 3466: /*     } /\* End loop k *\/ */
 3467: /*   } */
 3468: /*   delti[theta]=delts; */
 3469: /*   return res;  */
 3470: /* } */
 3471: 
 3472: 
 3473: /************** Inverse of matrix **************/
 3474: void ludcmp(double **a, int n, int *indx, double *d) 
 3475: { 
 3476:   int i,imax,j,k; 
 3477:   double big,dum,sum,temp; 
 3478:   double *vv; 
 3479:  
 3480:   vv=vector(1,n); 
 3481:   *d=1.0; 
 3482:   for (i=1;i<=n;i++) { 
 3483:     big=0.0; 
 3484:     for (j=1;j<=n;j++) 
 3485:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3486:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3487:     vv[i]=1.0/big; 
 3488:   } 
 3489:   for (j=1;j<=n;j++) { 
 3490:     for (i=1;i<j;i++) { 
 3491:       sum=a[i][j]; 
 3492:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3493:       a[i][j]=sum; 
 3494:     } 
 3495:     big=0.0; 
 3496:     for (i=j;i<=n;i++) { 
 3497:       sum=a[i][j]; 
 3498:       for (k=1;k<j;k++) 
 3499: 	sum -= a[i][k]*a[k][j]; 
 3500:       a[i][j]=sum; 
 3501:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3502: 	big=dum; 
 3503: 	imax=i; 
 3504:       } 
 3505:     } 
 3506:     if (j != imax) { 
 3507:       for (k=1;k<=n;k++) { 
 3508: 	dum=a[imax][k]; 
 3509: 	a[imax][k]=a[j][k]; 
 3510: 	a[j][k]=dum; 
 3511:       } 
 3512:       *d = -(*d); 
 3513:       vv[imax]=vv[j]; 
 3514:     } 
 3515:     indx[j]=imax; 
 3516:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3517:     if (j != n) { 
 3518:       dum=1.0/(a[j][j]); 
 3519:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3520:     } 
 3521:   } 
 3522:   free_vector(vv,1,n);  /* Doesn't work */
 3523: ;
 3524: } 
 3525: 
 3526: void lubksb(double **a, int n, int *indx, double b[]) 
 3527: { 
 3528:   int i,ii=0,ip,j; 
 3529:   double sum; 
 3530:  
 3531:   for (i=1;i<=n;i++) { 
 3532:     ip=indx[i]; 
 3533:     sum=b[ip]; 
 3534:     b[ip]=b[i]; 
 3535:     if (ii) 
 3536:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3537:     else if (sum) ii=i; 
 3538:     b[i]=sum; 
 3539:   } 
 3540:   for (i=n;i>=1;i--) { 
 3541:     sum=b[i]; 
 3542:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3543:     b[i]=sum/a[i][i]; 
 3544:   } 
 3545: } 
 3546: 
 3547: void pstamp(FILE *fichier)
 3548: {
 3549:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3550: }
 3551: 
 3552: /************ Frequencies ********************/
 3553: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 3554: 		  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
 3555: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 3556: {  /* Some frequencies */
 3557:   
 3558:   int i, m, jk, j1, bool, z1,j;
 3559:   int mi; /* Effective wave */
 3560:   int first;
 3561:   double ***freq; /* Frequencies */
 3562:   double *pp, **prop;
 3563:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 3564:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 3565:   double agebegin, ageend;
 3566:     
 3567:   pp=vector(1,nlstate);
 3568:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 3569:   strcpy(fileresp,"P_");
 3570:   strcat(fileresp,fileresu);
 3571:   /*strcat(fileresphtm,fileresu);*/
 3572:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 3573:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 3574:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 3575:     exit(0);
 3576:   }
 3577: 
 3578:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 3579:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 3580:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3581:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3582:     fflush(ficlog);
 3583:     exit(70); 
 3584:   }
 3585:   else{
 3586:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3587: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3588: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3589: 	  fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3590:   }
 3591:     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);
 3592:     
 3593:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 3594:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 3595:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3596:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3597:     fflush(ficlog);
 3598:     exit(70); 
 3599:   }
 3600:   else{
 3601:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3602: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3603: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3604: 	  fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3605:   }
 3606:   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);
 3607: 
 3608:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 3609:   j1=0;
 3610:   
 3611:   j=cptcoveff;
 3612:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3613: 
 3614:   first=1;
 3615: 
 3616:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
 3617:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 3618: 	scanf("%d", i);*/
 3619:       for (i=-5; i<=nlstate+ndeath; i++)  
 3620: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 3621: 	  for(m=iagemin; m <= iagemax+3; m++)
 3622: 	    freq[i][jk][m]=0;
 3623:       
 3624:       for (i=1; i<=nlstate; i++)  
 3625: 	for(m=iagemin; m <= iagemax+3; m++)
 3626: 	  prop[i][m]=0;
 3627:       
 3628:       dateintsum=0;
 3629:       k2cpt=0;
 3630:       for (i=1; i<=imx; i++) { /* For each individual i */
 3631: 	bool=1;
 3632: 	if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3633: 	  for (z1=1; z1<=cptcoveff; z1++)       
 3634:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 3635:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 3636:               bool=0;
 3637:               /* 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", 
 3638:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 3639:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 3640:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 3641:             } 
 3642: 	} /* cptcovn > 0 */
 3643: 
 3644: 	if (bool==1){
 3645: 	  /* for(m=firstpass; m<=lastpass; m++){ */
 3646: 	  for(mi=1; mi<wav[i];mi++){
 3647: 	    m=mw[mi][i];
 3648: 	    /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
 3649: 	       and mw[mi+1][i]. dh depends on stepm. */
 3650: 	    agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 3651: 	    ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
 3652: 	    if(m >=firstpass && m <=lastpass){
 3653: 	      k2=anint[m][i]+(mint[m][i]/12.);
 3654: 	      /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 3655: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 3656: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 3657: 	      if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
 3658: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
 3659: 	      if (m<lastpass) {
 3660: 		/* if(s[m][i]==4 && s[m+1][i]==4) */
 3661: 		/*   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]); */
 3662: 		if(s[m][i]==-1)
 3663: 		  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.));
 3664: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
 3665: 		/* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
 3666: 		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 */
 3667: 	      }
 3668: 	    }  
 3669: 	    if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
 3670: 	      dateintsum=dateintsum+k2;
 3671: 	      k2cpt++;
 3672: 	      /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 3673: 	    }
 3674: 	    /*}*/
 3675: 	  } /* end m */
 3676: 	} /* end bool */
 3677:       } /* end i = 1 to imx */
 3678:        
 3679:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 3680:       pstamp(ficresp);
 3681:       if  (cptcovn>0) {
 3682: 	fprintf(ficresp, "\n#********** Variable "); 
 3683: 	fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 3684: 	fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 3685: 	for (z1=1; z1<=cptcoveff; z1++){
 3686: 	  fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3687: 	  fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3688: 	  fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3689: 	}
 3690: 	  fprintf(ficresp, "**********\n#");
 3691: 	fprintf(ficresphtm, "**********</h3>\n");
 3692: 	fprintf(ficresphtmfr, "**********</h3>\n");
 3693: 	fprintf(ficlog, "\n#********** Variable "); 
 3694: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3695: 	fprintf(ficlog, "**********\n");
 3696:       }
 3697:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 3698:       for(i=1; i<=nlstate;i++) {
 3699: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 3700: 	fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 3701:       }
 3702:       fprintf(ficresp, "\n");
 3703:       fprintf(ficresphtm, "\n");
 3704:       
 3705:       /* Header of frequency table by age */
 3706:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 3707:       fprintf(ficresphtmfr,"<th>Age</th> ");
 3708:       for(jk=-1; jk <=nlstate+ndeath; jk++){
 3709: 	for(m=-1; m <=nlstate+ndeath; m++){
 3710: 	  if(jk!=0 && m!=0)
 3711: 	    fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 3712: 	}
 3713:       }
 3714:       fprintf(ficresphtmfr, "\n");
 3715:       
 3716:       /* For each age */
 3717:       for(i=iagemin; i <= iagemax+3; i++){
 3718: 	fprintf(ficresphtm,"<tr>");
 3719: 	if(i==iagemax+1){
 3720: 	  fprintf(ficlog,"1");
 3721: 	  fprintf(ficresphtmfr,"<tr><th>0</th> ");
 3722: 	}else if(i==iagemax+2){
 3723: 	  fprintf(ficlog,"0");
 3724: 	  fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 3725: 	}else if(i==iagemax+3){
 3726: 	  fprintf(ficlog,"Total");
 3727: 	  fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 3728: 	}else{
 3729: 	  if(first==1){
 3730: 	    first=0;
 3731: 	    printf("See log file for details...\n");
 3732: 	  }
 3733: 	  fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
 3734: 	  fprintf(ficlog,"Age %d", i);
 3735: 	}
 3736: 	for(jk=1; jk <=nlstate ; jk++){
 3737: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 3738: 	    pp[jk] += freq[jk][m][i]; 
 3739: 	}
 3740: 	for(jk=1; jk <=nlstate ; jk++){
 3741: 	  for(m=-1, pos=0; m <=0 ; m++)
 3742: 	    pos += freq[jk][m][i];
 3743: 	  if(pp[jk]>=1.e-10){
 3744: 	    if(first==1){
 3745: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3746: 	    }
 3747: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3748: 	  }else{
 3749: 	    if(first==1)
 3750: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3751: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3752: 	  }
 3753: 	}
 3754: 
 3755: 	for(jk=1; jk <=nlstate ; jk++){
 3756: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 3757: 	    pp[jk] += freq[jk][m][i];
 3758: 	}	
 3759: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 3760: 	  pos += pp[jk];
 3761: 	  posprop += prop[jk][i];
 3762: 	}
 3763: 	for(jk=1; jk <=nlstate ; jk++){
 3764: 	  if(pos>=1.e-5){
 3765: 	    if(first==1)
 3766: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3767: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3768: 	  }else{
 3769: 	    if(first==1)
 3770: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3771: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3772: 	  }
 3773: 	  if( i <= iagemax){
 3774: 	    if(pos>=1.e-5){
 3775: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3776: 	      fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3777: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 3778: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 3779: 	    }
 3780: 	    else{
 3781: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 3782: 	      fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
 3783: 	    }
 3784: 	  }
 3785: 	}
 3786: 	
 3787: 	for(jk=-1; jk <=nlstate+ndeath; jk++){
 3788: 	  for(m=-1; m <=nlstate+ndeath; m++){
 3789: 	    if(freq[jk][m][i] !=0 ) { /* minimizing output */
 3790: 	      if(first==1){
 3791: 		printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 3792: 	      }
 3793: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 3794: 	    }
 3795: 	    if(jk!=0 && m!=0)
 3796: 	      fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
 3797: 	  }
 3798: 	}
 3799: 	fprintf(ficresphtmfr,"</tr>\n ");
 3800: 	if(i <= iagemax){
 3801: 	  fprintf(ficresp,"\n");
 3802: 	  fprintf(ficresphtm,"</tr>\n");
 3803: 	}
 3804: 	if(first==1)
 3805: 	  printf("Others in log...\n");
 3806: 	fprintf(ficlog,"\n");
 3807:       } /* end loop i */
 3808:       fprintf(ficresphtm,"</table>\n");
 3809:       fprintf(ficresphtmfr,"</table>\n");
 3810:       /*}*/
 3811:   } /* end j1 */
 3812:   dateintmean=dateintsum/k2cpt; 
 3813:  
 3814:   fclose(ficresp);
 3815:   fclose(ficresphtm);
 3816:   fclose(ficresphtmfr);
 3817:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 3818:   free_vector(pp,1,nlstate);
 3819:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 3820:   /* End of Freq */
 3821: }
 3822: 
 3823: /************ Prevalence ********************/
 3824: 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)
 3825: {  
 3826:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3827:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3828:      We still use firstpass and lastpass as another selection.
 3829:   */
 3830:  
 3831:   int i, m, jk, j1, bool, z1,j;
 3832:   int mi; /* Effective wave */
 3833:   int iage;
 3834:   double agebegin, ageend;
 3835: 
 3836:   double **prop;
 3837:   double posprop; 
 3838:   double  y2; /* in fractional years */
 3839:   int iagemin, iagemax;
 3840:   int first; /** to stop verbosity which is redirected to log file */
 3841: 
 3842:   iagemin= (int) agemin;
 3843:   iagemax= (int) agemax;
 3844:   /*pp=vector(1,nlstate);*/
 3845:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 3846:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3847:   j1=0;
 3848:   
 3849:   /*j=cptcoveff;*/
 3850:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3851:   
 3852:   first=1;
 3853:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3854:     for (i=1; i<=nlstate; i++)  
 3855:       for(iage=iagemin; iage <= iagemax+3; iage++)
 3856: 	prop[i][iage]=0.0;
 3857:     
 3858:     for (i=1; i<=imx; i++) { /* Each individual */
 3859:       bool=1;
 3860:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3861: 	for (z1=1; z1<=cptcoveff; z1++) 
 3862: 	  if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
 3863: 	    bool=0;
 3864:       } 
 3865:       if (bool==1) { 
 3866: 	/* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 3867: 	for(mi=1; mi<wav[i];mi++){
 3868: 	  m=mw[mi][i];
 3869: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 3870: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 3871: 	  if(m >=firstpass && m <=lastpass){
 3872: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3873: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3874: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3875: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3876: 	      if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
 3877: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 3878: 		/*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]]);*/
 3879: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 3880: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 3881: 	      } /* end valid statuses */ 
 3882: 	    } /* end selection of dates */
 3883: 	  } /* end selection of waves */
 3884: 	} /* end effective waves */
 3885:       } /* end bool */
 3886:     }
 3887:     for(i=iagemin; i <= iagemax+3; i++){  
 3888:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 3889: 	posprop += prop[jk][i]; 
 3890:       } 
 3891:       
 3892:       for(jk=1; jk <=nlstate ; jk++){	    
 3893: 	if( i <=  iagemax){ 
 3894: 	  if(posprop>=1.e-5){ 
 3895: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 3896: 	  } else{
 3897: 	    if(first==1){
 3898: 	      first=0;
 3899: 	      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]);
 3900: 	    }
 3901: 	  }
 3902: 	} 
 3903:       }/* end jk */ 
 3904:     }/* end i */ 
 3905:     /*} *//* end i1 */
 3906:   } /* end j1 */
 3907:   
 3908:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 3909:   /*free_vector(pp,1,nlstate);*/
 3910:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 3911: }  /* End of prevalence */
 3912: 
 3913: /************* Waves Concatenation ***************/
 3914: 
 3915: 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)
 3916: {
 3917:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 3918:      Death is a valid wave (if date is known).
 3919:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 3920:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3921:      and mw[mi+1][i]. dh depends on stepm.
 3922:      */
 3923: 
 3924:   int i, mi, m;
 3925:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 3926:      double sum=0., jmean=0.;*/
 3927:   int first, firstwo, firsthree;
 3928:   int j, k=0,jk, ju, jl;
 3929:   double sum=0.;
 3930:   first=0;
 3931:   firstwo=0;
 3932:   firsthree=0;
 3933:   jmin=100000;
 3934:   jmax=-1;
 3935:   jmean=0.;
 3936:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 3937:     mi=0;
 3938:     m=firstpass;
 3939:     while(s[m][i] <= nlstate){  /* a live state */
 3940:       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 */
 3941: 	mw[++mi][i]=m;
 3942:       }
 3943:       if(m >=lastpass){
 3944: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 3945: 	  if(firsthree == 0){
 3946: 	    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);
 3947: 	    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.\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);
 3948: 	    firsthree=1;
 3949: 	  }else{
 3950: 	    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.\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);
 3951: 	  }
 3952: 	  mw[++mi][i]=m;
 3953: 	}
 3954: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 3955: 	  nbwarn++;
 3956: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 3957: 	    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);
 3958: 	    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);
 3959: 	  }
 3960: 	  break;
 3961: 	}
 3962: 	break;
 3963:       }
 3964:       else
 3965: 	m++;
 3966:     }/* end while */
 3967:     
 3968:     /* After last pass */
 3969:     if (s[m][i] > nlstate){  /* In a death state */
 3970:       mi++;	/* Death is another wave */
 3971:       /* if(mi==0)  never been interviewed correctly before death */
 3972: 	 /* Only death is a correct wave */
 3973:       mw[mi][i]=m;
 3974:     }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 */
 3975:       /* m++; */
 3976:       /* mi++; */
 3977:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 3978:       /* mw[mi][i]=m; */
 3979:       nberr++;
 3980:       if(firstwo==0){
 3981: 	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 );
 3982: 	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.\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 );
 3983: 	firstwo=1;
 3984:       }else if(firstwo==1){
 3985: 	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.\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 );
 3986:       }
 3987:     }
 3988:     wav[i]=mi;
 3989:     if(mi==0){
 3990:       nbwarn++;
 3991:       if(first==0){
 3992: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 3993: 	first=1;
 3994:       }
 3995:       if(first==1){
 3996: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 3997:       }
 3998:     } /* end mi==0 */
 3999:   } /* End individuals */
 4000:   /* wav and mw are no more changed */
 4001: 
 4002:   
 4003:   for(i=1; i<=imx; i++){
 4004:     for(mi=1; mi<wav[i];mi++){
 4005:       if (stepm <=0)
 4006: 	dh[mi][i]=1;
 4007:       else{
 4008: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4009: 	  if (agedc[i] < 2*AGESUP) {
 4010: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4011: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4012: 	    else if(j<0){
 4013: 	      nberr++;
 4014: 	      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]);
 4015: 	      j=1; /* Temporary Dangerous patch */
 4016: 	      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);
 4017: 	      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]);
 4018: 	      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);
 4019: 	    }
 4020: 	    k=k+1;
 4021: 	    if (j >= jmax){
 4022: 	      jmax=j;
 4023: 	      ijmax=i;
 4024: 	    }
 4025: 	    if (j <= jmin){
 4026: 	      jmin=j;
 4027: 	      ijmin=i;
 4028: 	    }
 4029: 	    sum=sum+j;
 4030: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4031: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4032: 	  }
 4033: 	}
 4034: 	else{
 4035: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4036: /* 	  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]); */
 4037: 
 4038: 	  k=k+1;
 4039: 	  if (j >= jmax) {
 4040: 	    jmax=j;
 4041: 	    ijmax=i;
 4042: 	  }
 4043: 	  else if (j <= jmin){
 4044: 	    jmin=j;
 4045: 	    ijmin=i;
 4046: 	  }
 4047: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4048: 	  /*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]);*/
 4049: 	  if(j<0){
 4050: 	    nberr++;
 4051: 	    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]);
 4052: 	    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]);
 4053: 	  }
 4054: 	  sum=sum+j;
 4055: 	}
 4056: 	jk= j/stepm;
 4057: 	jl= j -jk*stepm;
 4058: 	ju= j -(jk+1)*stepm;
 4059: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4060: 	  if(jl==0){
 4061: 	    dh[mi][i]=jk;
 4062: 	    bh[mi][i]=0;
 4063: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4064: 		  * to avoid the price of an extra matrix product in likelihood */
 4065: 	    dh[mi][i]=jk+1;
 4066: 	    bh[mi][i]=ju;
 4067: 	  }
 4068: 	}else{
 4069: 	  if(jl <= -ju){
 4070: 	    dh[mi][i]=jk;
 4071: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4072: 				 * is higher than the multiple of stepm and negative otherwise.
 4073: 				 */
 4074: 	  }
 4075: 	  else{
 4076: 	    dh[mi][i]=jk+1;
 4077: 	    bh[mi][i]=ju;
 4078: 	  }
 4079: 	  if(dh[mi][i]==0){
 4080: 	    dh[mi][i]=1; /* At least one step */
 4081: 	    bh[mi][i]=ju; /* At least one step */
 4082: 	    /*  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);*/
 4083: 	  }
 4084: 	} /* end if mle */
 4085:       }
 4086:     } /* end wave */
 4087:   }
 4088:   jmean=sum/k;
 4089:   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);
 4090:   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);
 4091:  }
 4092: 
 4093: /*********** Tricode ****************************/
 4094: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 4095: {
 4096:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4097:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4098:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4099:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 4100:    * nbcode[Tvar[j]][1]= 
 4101:   */
 4102: 
 4103:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4104:   int modmaxcovj=0; /* Modality max of covariates j */
 4105:   int cptcode=0; /* Modality max of covariates j */
 4106:   int modmincovj=0; /* Modality min of covariates j */
 4107: 
 4108: 
 4109:   cptcoveff=0; 
 4110:  
 4111:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4112: 
 4113:   /* Loop on covariates without age and products */
 4114:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 4115:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 4116:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 4117: 			       modality of this covariate Vj*/ 
 4118:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4119: 				    * If product of Vn*Vm, still boolean *:
 4120: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4121: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4122:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4123: 				      modality of the nth covariate of individual i. */
 4124:       if (ij > modmaxcovj)
 4125:         modmaxcovj=ij; 
 4126:       else if (ij < modmincovj) 
 4127: 	modmincovj=ij; 
 4128:       if ((ij < -1) && (ij > NCOVMAX)){
 4129: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4130: 	exit(1);
 4131:       }else
 4132:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4133:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4134:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4135:       /* getting the maximum value of the modality of the covariate
 4136: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4137: 	 female is 1, then modmaxcovj=1.*/
 4138:     } /* end for loop on individuals i */
 4139:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4140:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4141:     cptcode=modmaxcovj;
 4142:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4143:    /*for (i=0; i<=cptcode; i++) {*/
 4144:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 4145:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4146:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4147:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 4148: 	if( k != -1){
 4149: 	  ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 4150: 			     covariate for which somebody answered excluding 
 4151: 			     undefined. Usually 2: 0 and 1. */
 4152: 	}
 4153: 	ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 4154: 			     covariate for which somebody answered including 
 4155: 			     undefined. Usually 3: -1, 0 and 1. */
 4156:       }
 4157:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 4158: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4159:     } /* Ndum[-1] number of undefined modalities */
 4160: 
 4161:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4162:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 4163:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 4164:        modmincovj=3; modmaxcovj = 7;
 4165:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 4166:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 4167:        defining two dummy variables: variables V1_1 and V1_2.
 4168:        nbcode[Tvar[j]][ij]=k;
 4169:        nbcode[Tvar[j]][1]=0;
 4170:        nbcode[Tvar[j]][2]=1;
 4171:        nbcode[Tvar[j]][3]=2;
 4172:        To be continued (not working yet).
 4173:     */
 4174:     ij=0; /* ij is similar to i but can jump over null modalities */
 4175:     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*/
 4176:     	if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4177: 	  break;
 4178: 	}
 4179: 	ij++;
 4180: 	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.*/
 4181: 	cptcode = ij; /* New max modality for covar j */
 4182:     } /* end of loop on modality i=-1 to 1 or more */
 4183:       
 4184:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4185:     /* 	/\*recode from 0 *\/ */
 4186:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4187:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4188:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4189:     /* 	} */
 4190:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4191:     /* 	if (ij > ncodemax[j]) { */
 4192:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4193:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4194:     /* 	  break; */
 4195:     /* 	} */
 4196:     /*   }  /\* end of loop on modality k *\/ */
 4197:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4198:   
 4199:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4200:   
 4201:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4202:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4203:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 4204:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 4205:  } 
 4206: 
 4207:  ij=0;
 4208:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4209:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4210:    if((Ndum[i]!=0) && (i<=ncovcol)){
 4211:      ij++;
 4212:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4213:      Tvaraff[ij]=i; /*For printing (unclear) */
 4214:    }else{
 4215:        /* Tvaraff[ij]=0; */
 4216:    }
 4217:  }
 4218:  /* ij--; */
 4219:  cptcoveff=ij; /*Number of total covariates*/
 4220: 
 4221: }
 4222: 
 4223: 
 4224: /*********** Health Expectancies ****************/
 4225: 
 4226: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 4227: 
 4228: {
 4229:   /* Health expectancies, no variances */
 4230:   int i, j, nhstepm, hstepm, h, nstepm;
 4231:   int nhstepma, nstepma; /* Decreasing with age */
 4232:   double age, agelim, hf;
 4233:   double ***p3mat;
 4234:   double eip;
 4235: 
 4236:   pstamp(ficreseij);
 4237:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4238:   fprintf(ficreseij,"# Age");
 4239:   for(i=1; i<=nlstate;i++){
 4240:     for(j=1; j<=nlstate;j++){
 4241:       fprintf(ficreseij," e%1d%1d ",i,j);
 4242:     }
 4243:     fprintf(ficreseij," e%1d. ",i);
 4244:   }
 4245:   fprintf(ficreseij,"\n");
 4246: 
 4247:   
 4248:   if(estepm < stepm){
 4249:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4250:   }
 4251:   else  hstepm=estepm;   
 4252:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4253:    * This is mainly to measure the difference between two models: for example
 4254:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4255:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4256:    * progression in between and thus overestimating or underestimating according
 4257:    * to the curvature of the survival function. If, for the same date, we 
 4258:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4259:    * to compare the new estimate of Life expectancy with the same linear 
 4260:    * hypothesis. A more precise result, taking into account a more precise
 4261:    * curvature will be obtained if estepm is as small as stepm. */
 4262: 
 4263:   /* For example we decided to compute the life expectancy with the smallest unit */
 4264:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4265:      nhstepm is the number of hstepm from age to agelim 
 4266:      nstepm is the number of stepm from age to agelin. 
 4267:      Look at hpijx to understand the reason of that which relies in memory size
 4268:      and note for a fixed period like estepm months */
 4269:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4270:      survival function given by stepm (the optimization length). Unfortunately it
 4271:      means that if the survival funtion is printed only each two years of age and if
 4272:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4273:      results. So we changed our mind and took the option of the best precision.
 4274:   */
 4275:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4276: 
 4277:   agelim=AGESUP;
 4278:   /* If stepm=6 months */
 4279:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 4280:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 4281:     
 4282: /* nhstepm age range expressed in number of stepm */
 4283:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4284:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4285:   /* if (stepm >= YEARM) hstepm=1;*/
 4286:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4287:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4288: 
 4289:   for (age=bage; age<=fage; age ++){ 
 4290:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4291:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4292:     /* if (stepm >= YEARM) hstepm=1;*/
 4293:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4294: 
 4295:     /* If stepm=6 months */
 4296:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4297:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4298:     
 4299:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4300:     
 4301:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4302:     
 4303:     printf("%d|",(int)age);fflush(stdout);
 4304:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4305:     
 4306:     /* Computing expectancies */
 4307:     for(i=1; i<=nlstate;i++)
 4308:       for(j=1; j<=nlstate;j++)
 4309: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4310: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 4311: 	  
 4312: 	  /* 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]);*/
 4313: 
 4314: 	}
 4315: 
 4316:     fprintf(ficreseij,"%3.0f",age );
 4317:     for(i=1; i<=nlstate;i++){
 4318:       eip=0;
 4319:       for(j=1; j<=nlstate;j++){
 4320: 	eip +=eij[i][j][(int)age];
 4321: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 4322:       }
 4323:       fprintf(ficreseij,"%9.4f", eip );
 4324:     }
 4325:     fprintf(ficreseij,"\n");
 4326:     
 4327:   }
 4328:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4329:   printf("\n");
 4330:   fprintf(ficlog,"\n");
 4331:   
 4332: }
 4333: 
 4334: 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[] )
 4335: 
 4336: {
 4337:   /* Covariances of health expectancies eij and of total life expectancies according
 4338:    to initial status i, ei. .
 4339:   */
 4340:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 4341:   int nhstepma, nstepma; /* Decreasing with age */
 4342:   double age, agelim, hf;
 4343:   double ***p3matp, ***p3matm, ***varhe;
 4344:   double **dnewm,**doldm;
 4345:   double *xp, *xm;
 4346:   double **gp, **gm;
 4347:   double ***gradg, ***trgradg;
 4348:   int theta;
 4349: 
 4350:   double eip, vip;
 4351: 
 4352:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 4353:   xp=vector(1,npar);
 4354:   xm=vector(1,npar);
 4355:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 4356:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 4357:   
 4358:   pstamp(ficresstdeij);
 4359:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 4360:   fprintf(ficresstdeij,"# Age");
 4361:   for(i=1; i<=nlstate;i++){
 4362:     for(j=1; j<=nlstate;j++)
 4363:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 4364:     fprintf(ficresstdeij," e%1d. ",i);
 4365:   }
 4366:   fprintf(ficresstdeij,"\n");
 4367: 
 4368:   pstamp(ficrescveij);
 4369:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 4370:   fprintf(ficrescveij,"# Age");
 4371:   for(i=1; i<=nlstate;i++)
 4372:     for(j=1; j<=nlstate;j++){
 4373:       cptj= (j-1)*nlstate+i;
 4374:       for(i2=1; i2<=nlstate;i2++)
 4375: 	for(j2=1; j2<=nlstate;j2++){
 4376: 	  cptj2= (j2-1)*nlstate+i2;
 4377: 	  if(cptj2 <= cptj)
 4378: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 4379: 	}
 4380:     }
 4381:   fprintf(ficrescveij,"\n");
 4382:   
 4383:   if(estepm < stepm){
 4384:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4385:   }
 4386:   else  hstepm=estepm;   
 4387:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4388:    * This is mainly to measure the difference between two models: for example
 4389:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4390:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4391:    * progression in between and thus overestimating or underestimating according
 4392:    * to the curvature of the survival function. If, for the same date, we 
 4393:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4394:    * to compare the new estimate of Life expectancy with the same linear 
 4395:    * hypothesis. A more precise result, taking into account a more precise
 4396:    * curvature will be obtained if estepm is as small as stepm. */
 4397: 
 4398:   /* For example we decided to compute the life expectancy with the smallest unit */
 4399:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4400:      nhstepm is the number of hstepm from age to agelim 
 4401:      nstepm is the number of stepm from age to agelin. 
 4402:      Look at hpijx to understand the reason of that which relies in memory size
 4403:      and note for a fixed period like estepm months */
 4404:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4405:      survival function given by stepm (the optimization length). Unfortunately it
 4406:      means that if the survival funtion is printed only each two years of age and if
 4407:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4408:      results. So we changed our mind and took the option of the best precision.
 4409:   */
 4410:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4411: 
 4412:   /* If stepm=6 months */
 4413:   /* nhstepm age range expressed in number of stepm */
 4414:   agelim=AGESUP;
 4415:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 4416:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4417:   /* if (stepm >= YEARM) hstepm=1;*/
 4418:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4419:   
 4420:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4421:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4422:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 4423:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 4424:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 4425:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 4426: 
 4427:   for (age=bage; age<=fage; age ++){ 
 4428:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4429:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4430:     /* if (stepm >= YEARM) hstepm=1;*/
 4431:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4432: 
 4433:     /* If stepm=6 months */
 4434:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4435:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4436:     
 4437:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4438: 
 4439:     /* Computing  Variances of health expectancies */
 4440:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 4441:        decrease memory allocation */
 4442:     for(theta=1; theta <=npar; theta++){
 4443:       for(i=1; i<=npar; i++){ 
 4444: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4445: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 4446:       }
 4447:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 4448:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 4449:   
 4450:       for(j=1; j<= nlstate; j++){
 4451: 	for(i=1; i<=nlstate; i++){
 4452: 	  for(h=0; h<=nhstepm-1; h++){
 4453: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 4454: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 4455: 	  }
 4456: 	}
 4457:       }
 4458:      
 4459:       for(ij=1; ij<= nlstate*nlstate; ij++)
 4460: 	for(h=0; h<=nhstepm-1; h++){
 4461: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 4462: 	}
 4463:     }/* End theta */
 4464:     
 4465:     
 4466:     for(h=0; h<=nhstepm-1; h++)
 4467:       for(j=1; j<=nlstate*nlstate;j++)
 4468: 	for(theta=1; theta <=npar; theta++)
 4469: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 4470:     
 4471: 
 4472:      for(ij=1;ij<=nlstate*nlstate;ij++)
 4473:       for(ji=1;ji<=nlstate*nlstate;ji++)
 4474: 	varhe[ij][ji][(int)age] =0.;
 4475: 
 4476:      printf("%d|",(int)age);fflush(stdout);
 4477:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4478:      for(h=0;h<=nhstepm-1;h++){
 4479:       for(k=0;k<=nhstepm-1;k++){
 4480: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 4481: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 4482: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 4483: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 4484: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 4485:       }
 4486:     }
 4487: 
 4488:     /* Computing expectancies */
 4489:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4490:     for(i=1; i<=nlstate;i++)
 4491:       for(j=1; j<=nlstate;j++)
 4492: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4493: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 4494: 	  
 4495: 	  /* 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]);*/
 4496: 
 4497: 	}
 4498: 
 4499:     fprintf(ficresstdeij,"%3.0f",age );
 4500:     for(i=1; i<=nlstate;i++){
 4501:       eip=0.;
 4502:       vip=0.;
 4503:       for(j=1; j<=nlstate;j++){
 4504: 	eip += eij[i][j][(int)age];
 4505: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 4506: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 4507: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 4508:       }
 4509:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 4510:     }
 4511:     fprintf(ficresstdeij,"\n");
 4512: 
 4513:     fprintf(ficrescveij,"%3.0f",age );
 4514:     for(i=1; i<=nlstate;i++)
 4515:       for(j=1; j<=nlstate;j++){
 4516: 	cptj= (j-1)*nlstate+i;
 4517: 	for(i2=1; i2<=nlstate;i2++)
 4518: 	  for(j2=1; j2<=nlstate;j2++){
 4519: 	    cptj2= (j2-1)*nlstate+i2;
 4520: 	    if(cptj2 <= cptj)
 4521: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 4522: 	  }
 4523:       }
 4524:     fprintf(ficrescveij,"\n");
 4525:    
 4526:   }
 4527:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 4528:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 4529:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 4530:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 4531:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4532:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4533:   printf("\n");
 4534:   fprintf(ficlog,"\n");
 4535: 
 4536:   free_vector(xm,1,npar);
 4537:   free_vector(xp,1,npar);
 4538:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 4539:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 4540:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 4541: }
 4542: 
 4543: /************ Variance ******************/
 4544:  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[])
 4545: {
 4546:   /* Variance of health expectancies */
 4547:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 4548:   /* double **newm;*/
 4549:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 4550:   
 4551:   int movingaverage();
 4552:   double **dnewm,**doldm;
 4553:   double **dnewmp,**doldmp;
 4554:   int i, j, nhstepm, hstepm, h, nstepm ;
 4555:   int k;
 4556:   double *xp;
 4557:   double **gp, **gm;  /* for var eij */
 4558:   double ***gradg, ***trgradg; /*for var eij */
 4559:   double **gradgp, **trgradgp; /* for var p point j */
 4560:   double *gpp, *gmp; /* for var p point j */
 4561:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 4562:   double ***p3mat;
 4563:   double age,agelim, hf;
 4564:   double ***mobaverage;
 4565:   int theta;
 4566:   char digit[4];
 4567:   char digitp[25];
 4568: 
 4569:   char fileresprobmorprev[FILENAMELENGTH];
 4570: 
 4571:   if(popbased==1){
 4572:     if(mobilav!=0)
 4573:       strcpy(digitp,"-POPULBASED-MOBILAV_");
 4574:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 4575:   }
 4576:   else 
 4577:     strcpy(digitp,"-STABLBASED_");
 4578: 
 4579:   if (mobilav!=0) {
 4580:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4581:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 4582:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4583:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4584:     }
 4585:   }
 4586: 
 4587:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
 4588:   sprintf(digit,"%-d",ij);
 4589:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 4590:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 4591:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 4592:   strcat(fileresprobmorprev,fileresu);
 4593:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 4594:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 4595:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 4596:   }
 4597:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4598:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4599:   pstamp(ficresprobmorprev);
 4600:   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);
 4601:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 4602:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4603:     fprintf(ficresprobmorprev," p.%-d SE",j);
 4604:     for(i=1; i<=nlstate;i++)
 4605:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 4606:   }  
 4607:   fprintf(ficresprobmorprev,"\n");
 4608:   
 4609:   fprintf(ficgp,"\n# Routine varevsij");
 4610:   fprintf(ficgp,"\nunset title \n");
 4611: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 4612:   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");
 4613:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 4614: /*   } */
 4615:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4616:   pstamp(ficresvij);
 4617:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 4618:   if(popbased==1)
 4619:     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);
 4620:   else
 4621:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 4622:   fprintf(ficresvij,"# Age");
 4623:   for(i=1; i<=nlstate;i++)
 4624:     for(j=1; j<=nlstate;j++)
 4625:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 4626:   fprintf(ficresvij,"\n");
 4627: 
 4628:   xp=vector(1,npar);
 4629:   dnewm=matrix(1,nlstate,1,npar);
 4630:   doldm=matrix(1,nlstate,1,nlstate);
 4631:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 4632:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4633: 
 4634:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 4635:   gpp=vector(nlstate+1,nlstate+ndeath);
 4636:   gmp=vector(nlstate+1,nlstate+ndeath);
 4637:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4638:   
 4639:   if(estepm < stepm){
 4640:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4641:   }
 4642:   else  hstepm=estepm;   
 4643:   /* For example we decided to compute the life expectancy with the smallest unit */
 4644:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4645:      nhstepm is the number of hstepm from age to agelim 
 4646:      nstepm is the number of stepm from age to agelim. 
 4647:      Look at function hpijx to understand why because of memory size limitations, 
 4648:      we decided (b) to get a life expectancy respecting the most precise curvature of the
 4649:      survival function given by stepm (the optimization length). Unfortunately it
 4650:      means that if the survival funtion is printed every two years of age and if
 4651:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4652:      results. So we changed our mind and took the option of the best precision.
 4653:   */
 4654:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4655:   agelim = AGESUP;
 4656:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4657:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4658:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4659:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4660:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 4661:     gp=matrix(0,nhstepm,1,nlstate);
 4662:     gm=matrix(0,nhstepm,1,nlstate);
 4663: 
 4664: 
 4665:     for(theta=1; theta <=npar; theta++){
 4666:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 4667: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4668:       }
 4669: 
 4670:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4671: 
 4672:       if (popbased==1) {
 4673: 	if(mobilav ==0){
 4674: 	  for(i=1; i<=nlstate;i++)
 4675: 	    prlim[i][i]=probs[(int)age][i][ij];
 4676: 	}else{ /* mobilav */ 
 4677: 	  for(i=1; i<=nlstate;i++)
 4678: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 4679: 	}
 4680:       }
 4681:   
 4682:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 4683:       for(j=1; j<= nlstate; j++){
 4684: 	for(h=0; h<=nhstepm; h++){
 4685: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 4686: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 4687: 	}
 4688:       }
 4689:       /* Next for computing probability of death (h=1 means
 4690:          computed over hstepm matrices product = hstepm*stepm months) 
 4691:          as a weighted average of prlim.
 4692:       */
 4693:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4694: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 4695: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 4696:       }    
 4697:       /* end probability of death */
 4698: 
 4699:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 4700: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4701: 
 4702:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 4703:  
 4704:       if (popbased==1) {
 4705: 	if(mobilav ==0){
 4706: 	  for(i=1; i<=nlstate;i++)
 4707: 	    prlim[i][i]=probs[(int)age][i][ij];
 4708: 	}else{ /* mobilav */ 
 4709: 	  for(i=1; i<=nlstate;i++)
 4710: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 4711: 	}
 4712:       }
 4713: 
 4714:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 4715: 
 4716:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 4717: 	for(h=0; h<=nhstepm; h++){
 4718: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 4719: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 4720: 	}
 4721:       }
 4722:       /* This for computing probability of death (h=1 means
 4723:          computed over hstepm matrices product = hstepm*stepm months) 
 4724:          as a weighted average of prlim.
 4725:       */
 4726:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4727: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 4728:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 4729:       }    
 4730:       /* end probability of death */
 4731: 
 4732:       for(j=1; j<= nlstate; j++) /* vareij */
 4733: 	for(h=0; h<=nhstepm; h++){
 4734: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 4735: 	}
 4736: 
 4737:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 4738: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 4739:       }
 4740: 
 4741:     } /* End theta */
 4742: 
 4743:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 4744: 
 4745:     for(h=0; h<=nhstepm; h++) /* veij */
 4746:       for(j=1; j<=nlstate;j++)
 4747: 	for(theta=1; theta <=npar; theta++)
 4748: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 4749: 
 4750:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 4751:       for(theta=1; theta <=npar; theta++)
 4752: 	trgradgp[j][theta]=gradgp[theta][j];
 4753:   
 4754: 
 4755:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4756:     for(i=1;i<=nlstate;i++)
 4757:       for(j=1;j<=nlstate;j++)
 4758: 	vareij[i][j][(int)age] =0.;
 4759: 
 4760:     for(h=0;h<=nhstepm;h++){
 4761:       for(k=0;k<=nhstepm;k++){
 4762: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 4763: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 4764: 	for(i=1;i<=nlstate;i++)
 4765: 	  for(j=1;j<=nlstate;j++)
 4766: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 4767:       }
 4768:     }
 4769:   
 4770:     /* pptj */
 4771:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 4772:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 4773:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 4774:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 4775: 	varppt[j][i]=doldmp[j][i];
 4776:     /* end ppptj */
 4777:     /*  x centered again */
 4778: 
 4779:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 4780:  
 4781:     if (popbased==1) {
 4782:       if(mobilav ==0){
 4783: 	for(i=1; i<=nlstate;i++)
 4784: 	  prlim[i][i]=probs[(int)age][i][ij];
 4785:       }else{ /* mobilav */ 
 4786: 	for(i=1; i<=nlstate;i++)
 4787: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 4788:       }
 4789:     }
 4790:              
 4791:     /* This for computing probability of death (h=1 means
 4792:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 4793:        as a weighted average of prlim.
 4794:     */
 4795:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 4796:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4797:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 4798: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 4799:     }    
 4800:     /* end probability of death */
 4801: 
 4802:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 4803:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4804:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 4805:       for(i=1; i<=nlstate;i++){
 4806: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 4807:       }
 4808:     } 
 4809:     fprintf(ficresprobmorprev,"\n");
 4810: 
 4811:     fprintf(ficresvij,"%.0f ",age );
 4812:     for(i=1; i<=nlstate;i++)
 4813:       for(j=1; j<=nlstate;j++){
 4814: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 4815:       }
 4816:     fprintf(ficresvij,"\n");
 4817:     free_matrix(gp,0,nhstepm,1,nlstate);
 4818:     free_matrix(gm,0,nhstepm,1,nlstate);
 4819:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 4820:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 4821:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4822:   } /* End age */
 4823:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 4824:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 4825:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 4826:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4827:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 4828:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 4829:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 4830:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 4831:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4832: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 4833: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4834: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4835:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 4836:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 4837:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 4838:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 4839:   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);
 4840:   /*  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);
 4841: */
 4842: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 4843:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4844: 
 4845:   free_vector(xp,1,npar);
 4846:   free_matrix(doldm,1,nlstate,1,nlstate);
 4847:   free_matrix(dnewm,1,nlstate,1,npar);
 4848:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4849:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 4850:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4851:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4852:   fclose(ficresprobmorprev);
 4853:   fflush(ficgp);
 4854:   fflush(fichtm); 
 4855: }  /* end varevsij */
 4856: 
 4857: /************ Variance of prevlim ******************/
 4858:  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[])
 4859: {
 4860:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 4861:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 4862: 
 4863:   double **dnewm,**doldm;
 4864:   int i, j, nhstepm, hstepm;
 4865:   double *xp;
 4866:   double *gp, *gm;
 4867:   double **gradg, **trgradg;
 4868:   double **mgm, **mgp;
 4869:   double age,agelim;
 4870:   int theta;
 4871:   
 4872:   pstamp(ficresvpl);
 4873:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 4874:   fprintf(ficresvpl,"# Age");
 4875:   for(i=1; i<=nlstate;i++)
 4876:       fprintf(ficresvpl," %1d-%1d",i,i);
 4877:   fprintf(ficresvpl,"\n");
 4878: 
 4879:   xp=vector(1,npar);
 4880:   dnewm=matrix(1,nlstate,1,npar);
 4881:   doldm=matrix(1,nlstate,1,nlstate);
 4882:   
 4883:   hstepm=1*YEARM; /* Every year of age */
 4884:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 4885:   agelim = AGESUP;
 4886:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4887:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4888:     if (stepm >= YEARM) hstepm=1;
 4889:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4890:     gradg=matrix(1,npar,1,nlstate);
 4891:     mgp=matrix(1,npar,1,nlstate);
 4892:     mgm=matrix(1,npar,1,nlstate);
 4893:     gp=vector(1,nlstate);
 4894:     gm=vector(1,nlstate);
 4895: 
 4896:     for(theta=1; theta <=npar; theta++){
 4897:       for(i=1; i<=npar; i++){ /* Computes gradient */
 4898: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4899:       }
 4900:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 4901: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4902:       else
 4903: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4904:       for(i=1;i<=nlstate;i++){
 4905: 	gp[i] = prlim[i][i];
 4906: 	mgp[theta][i] = prlim[i][i];
 4907:       }
 4908:       for(i=1; i<=npar; i++) /* Computes gradient */
 4909: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4910:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 4911: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4912:       else
 4913: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4914:       for(i=1;i<=nlstate;i++){
 4915: 	gm[i] = prlim[i][i];
 4916: 	mgm[theta][i] = prlim[i][i];
 4917:       }
 4918:       for(i=1;i<=nlstate;i++)
 4919: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 4920:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 4921:     } /* End theta */
 4922: 
 4923:     trgradg =matrix(1,nlstate,1,npar);
 4924: 
 4925:     for(j=1; j<=nlstate;j++)
 4926:       for(theta=1; theta <=npar; theta++)
 4927: 	trgradg[j][theta]=gradg[theta][j];
 4928:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 4929:     /*   printf("\nmgm mgp %d ",(int)age); */
 4930:     /*   for(j=1; j<=nlstate;j++){ */
 4931:     /* 	printf(" %d ",j); */
 4932:     /* 	for(theta=1; theta <=npar; theta++) */
 4933:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 4934:     /* 	printf("\n "); */
 4935:     /*   } */
 4936:     /* } */
 4937:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 4938:     /*   printf("\n gradg %d ",(int)age); */
 4939:     /*   for(j=1; j<=nlstate;j++){ */
 4940:     /* 	printf("%d ",j); */
 4941:     /* 	for(theta=1; theta <=npar; theta++) */
 4942:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 4943:     /* 	printf("\n "); */
 4944:     /*   } */
 4945:     /* } */
 4946: 
 4947:     for(i=1;i<=nlstate;i++)
 4948:       varpl[i][(int)age] =0.;
 4949:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 4950:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4951:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4952:     }else{
 4953:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4954:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4955:     }
 4956:     for(i=1;i<=nlstate;i++)
 4957:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 4958: 
 4959:     fprintf(ficresvpl,"%.0f ",age );
 4960:     for(i=1; i<=nlstate;i++)
 4961:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 4962:     fprintf(ficresvpl,"\n");
 4963:     free_vector(gp,1,nlstate);
 4964:     free_vector(gm,1,nlstate);
 4965:     free_matrix(mgm,1,npar,1,nlstate);
 4966:     free_matrix(mgp,1,npar,1,nlstate);
 4967:     free_matrix(gradg,1,npar,1,nlstate);
 4968:     free_matrix(trgradg,1,nlstate,1,npar);
 4969:   } /* End age */
 4970: 
 4971:   free_vector(xp,1,npar);
 4972:   free_matrix(doldm,1,nlstate,1,npar);
 4973:   free_matrix(dnewm,1,nlstate,1,nlstate);
 4974: 
 4975: }
 4976: 
 4977: /************ Variance of one-step probabilities  ******************/
 4978: 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[])
 4979: {
 4980:   int i, j=0,  k1, l1, tj;
 4981:   int k2, l2, j1,  z1;
 4982:   int k=0, l;
 4983:   int first=1, first1, first2;
 4984:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 4985:   double **dnewm,**doldm;
 4986:   double *xp;
 4987:   double *gp, *gm;
 4988:   double **gradg, **trgradg;
 4989:   double **mu;
 4990:   double age, cov[NCOVMAX+1];
 4991:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 4992:   int theta;
 4993:   char fileresprob[FILENAMELENGTH];
 4994:   char fileresprobcov[FILENAMELENGTH];
 4995:   char fileresprobcor[FILENAMELENGTH];
 4996:   double ***varpij;
 4997: 
 4998:   strcpy(fileresprob,"PROB_"); 
 4999:   strcat(fileresprob,fileres);
 5000:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5001:     printf("Problem with resultfile: %s\n", fileresprob);
 5002:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5003:   }
 5004:   strcpy(fileresprobcov,"PROBCOV_"); 
 5005:   strcat(fileresprobcov,fileresu);
 5006:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5007:     printf("Problem with resultfile: %s\n", fileresprobcov);
 5008:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5009:   }
 5010:   strcpy(fileresprobcor,"PROBCOR_"); 
 5011:   strcat(fileresprobcor,fileresu);
 5012:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5013:     printf("Problem with resultfile: %s\n", fileresprobcor);
 5014:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5015:   }
 5016:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5017:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5018:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5019:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5020:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5021:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5022:   pstamp(ficresprob);
 5023:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5024:   fprintf(ficresprob,"# Age");
 5025:   pstamp(ficresprobcov);
 5026:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5027:   fprintf(ficresprobcov,"# Age");
 5028:   pstamp(ficresprobcor);
 5029:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5030:   fprintf(ficresprobcor,"# Age");
 5031: 
 5032: 
 5033:   for(i=1; i<=nlstate;i++)
 5034:     for(j=1; j<=(nlstate+ndeath);j++){
 5035:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5036:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5037:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5038:     }  
 5039:  /* fprintf(ficresprob,"\n");
 5040:   fprintf(ficresprobcov,"\n");
 5041:   fprintf(ficresprobcor,"\n");
 5042:  */
 5043:   xp=vector(1,npar);
 5044:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5045:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5046:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5047:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5048:   first=1;
 5049:   fprintf(ficgp,"\n# Routine varprob");
 5050:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5051:   fprintf(fichtm,"\n");
 5052: 
 5053:   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);
 5054:   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);
 5055:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5056: and drawn. It helps understanding how is the covariance between two incidences.\
 5057:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5058:   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. \
 5059: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5060: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5061: standard deviations wide on each axis. <br>\
 5062:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5063:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5064: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5065: 
 5066:   cov[1]=1;
 5067:   /* tj=cptcoveff; */
 5068:   tj = (int) pow(2,cptcoveff);
 5069:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5070:   j1=0;
 5071:   for(j1=1; j1<=tj;j1++){
 5072:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 5073:     /*j1++;*/
 5074:       if  (cptcovn>0) {
 5075: 	fprintf(ficresprob, "\n#********** Variable "); 
 5076: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5077: 	fprintf(ficresprob, "**********\n#\n");
 5078: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 5079: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5080: 	fprintf(ficresprobcov, "**********\n#\n");
 5081: 	
 5082: 	fprintf(ficgp, "\n#********** Variable "); 
 5083: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5084: 	fprintf(ficgp, "**********\n#\n");
 5085: 	
 5086: 	
 5087: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5088: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5089: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5090: 	
 5091: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 5092: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5093: 	fprintf(ficresprobcor, "**********\n#");    
 5094:       }
 5095:       
 5096:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5097:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5098:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 5099:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 5100:       for (age=bage; age<=fage; age ++){ 
 5101: 	cov[2]=age;
 5102: 	if(nagesqr==1)
 5103: 	  cov[3]= age*age;
 5104: 	for (k=1; k<=cptcovn;k++) {
 5105: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5106: 	  /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5107: 							 * 1  1 1 1 1
 5108: 							 * 2  2 1 1 1
 5109: 							 * 3  1 2 1 1
 5110: 							 */
 5111: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5112: 	}
 5113: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5114: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5115: 	for (k=1; k<=cptcovprod;k++)
 5116: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5117: 	
 5118:     
 5119: 	for(theta=1; theta <=npar; theta++){
 5120: 	  for(i=1; i<=npar; i++)
 5121: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5122: 	  
 5123: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5124: 	  
 5125: 	  k=0;
 5126: 	  for(i=1; i<= (nlstate); i++){
 5127: 	    for(j=1; j<=(nlstate+ndeath);j++){
 5128: 	      k=k+1;
 5129: 	      gp[k]=pmmij[i][j];
 5130: 	    }
 5131: 	  }
 5132: 	  
 5133: 	  for(i=1; i<=npar; i++)
 5134: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5135:     
 5136: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5137: 	  k=0;
 5138: 	  for(i=1; i<=(nlstate); i++){
 5139: 	    for(j=1; j<=(nlstate+ndeath);j++){
 5140: 	      k=k+1;
 5141: 	      gm[k]=pmmij[i][j];
 5142: 	    }
 5143: 	  }
 5144:      
 5145: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5146: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5147: 	}
 5148: 
 5149: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5150: 	  for(theta=1; theta <=npar; theta++)
 5151: 	    trgradg[j][theta]=gradg[theta][j];
 5152: 	
 5153: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5154: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5155: 
 5156: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 5157: 	
 5158: 	k=0;
 5159: 	for(i=1; i<=(nlstate); i++){
 5160: 	  for(j=1; j<=(nlstate+ndeath);j++){
 5161: 	    k=k+1;
 5162: 	    mu[k][(int) age]=pmmij[i][j];
 5163: 	  }
 5164: 	}
 5165:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5166: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5167: 	    varpij[i][j][(int)age] = doldm[i][j];
 5168: 
 5169: 	/*printf("\n%d ",(int)age);
 5170: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5171: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5172: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5173: 	  }*/
 5174: 
 5175: 	fprintf(ficresprob,"\n%d ",(int)age);
 5176: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 5177: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 5178: 
 5179: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5180: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5181: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5182: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5183: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5184: 	}
 5185: 	i=0;
 5186: 	for (k=1; k<=(nlstate);k++){
 5187:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 5188:  	    i++;
 5189: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5190: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5191: 	    for (j=1; j<=i;j++){
 5192: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5193: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5194: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5195: 	    }
 5196: 	  }
 5197: 	}/* end of loop for state */
 5198:       } /* end of loop for age */
 5199:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5200:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5201:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5202:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5203:       
 5204:       /* Confidence intervalle of pij  */
 5205:       /*
 5206: 	fprintf(ficgp,"\nunset parametric;unset label");
 5207: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5208: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5209: 	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);
 5210: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5211: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5212: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5213:       */
 5214: 
 5215:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5216:       first1=1;first2=2;
 5217:       for (k2=1; k2<=(nlstate);k2++){
 5218: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5219: 	  if(l2==k2) continue;
 5220: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 5221: 	  for (k1=1; k1<=(nlstate);k1++){
 5222: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5223: 	      if(l1==k1) continue;
 5224: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 5225: 	      if(i<=j) continue;
 5226: 	      for (age=bage; age<=fage; age ++){ 
 5227: 		if ((int)age %5==0){
 5228: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5229: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5230: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5231: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 5232: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 5233: 		  c12=cv12/sqrt(v1*v2);
 5234: 		  /* Computing eigen value of matrix of covariance */
 5235: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5236: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5237: 		  if ((lc2 <0) || (lc1 <0) ){
 5238: 		    if(first2==1){
 5239: 		      first1=0;
 5240: 		    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);
 5241: 		    }
 5242: 		    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);
 5243: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5244: 		    /* lc2=fabs(lc2); */
 5245: 		  }
 5246: 
 5247: 		  /* Eigen vectors */
 5248: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5249: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 5250: 		  v21=(lc1-v1)/cv12*v11;
 5251: 		  v12=-v21;
 5252: 		  v22=v11;
 5253: 		  tnalp=v21/v11;
 5254: 		  if(first1==1){
 5255: 		    first1=0;
 5256: 		    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);
 5257: 		  }
 5258: 		  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);
 5259: 		  /*printf(fignu*/
 5260: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 5261: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 5262: 		  if(first==1){
 5263: 		    first=0;
 5264:  		    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 5265:  		    fprintf(ficgp,"\nset parametric;unset label");
 5266: 		    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);
 5267: 		    fprintf(ficgp,"\nset ter svg size 640, 480");
 5268: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 5269:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
 5270: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 5271: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
 5272: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5273: 		    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5274: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 5275: 		    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5276: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5277: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5278: 		    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",\
 5279: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 5280: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5281: 		  }else{
 5282: 		    first=0;
 5283: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 5284: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5285: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5286: 		    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",\
 5287: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 5288: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5289: 		  }/* if first */
 5290: 		} /* age mod 5 */
 5291: 	      } /* end loop age */
 5292: 	      fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5293: 	      first=1;
 5294: 	    } /*l12 */
 5295: 	  } /* k12 */
 5296: 	} /*l1 */
 5297:       }/* k1 */
 5298:       /* } */ /* loop covariates */
 5299:   }
 5300:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 5301:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 5302:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5303:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 5304:   free_vector(xp,1,npar);
 5305:   fclose(ficresprob);
 5306:   fclose(ficresprobcov);
 5307:   fclose(ficresprobcor);
 5308:   fflush(ficgp);
 5309:   fflush(fichtmcov);
 5310: }
 5311: 
 5312: 
 5313: /******************* Printing html file ***********/
 5314: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 5315: 		  int lastpass, int stepm, int weightopt, char model[],\
 5316: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 5317: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 5318: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 5319: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 5320:   int jj1, k1, i1, cpt;
 5321: 
 5322:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 5323:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 5324: </ul>");
 5325:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 5326:    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",
 5327: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 5328:    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) ",
 5329: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 5330:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 5331:    fprintf(fichtm,"\
 5332:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5333: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 5334:    fprintf(fichtm,"\
 5335:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5336: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 5337:    fprintf(fichtm,"\
 5338:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5339: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 5340:    fprintf(fichtm,"\
 5341:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5342: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 5343:    fprintf(fichtm,"\
 5344:  - (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): \
 5345:    <a href=\"%s\">%s</a> <br>\n",
 5346: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 5347:    if(prevfcast==1){
 5348:      fprintf(fichtm,"\
 5349:  - Prevalence projections by age and states:				\
 5350:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 5351:    }
 5352: 
 5353: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 5354: 
 5355:  m=pow(2,cptcoveff);
 5356:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5357: 
 5358:  jj1=0;
 5359:  for(k1=1; k1<=m;k1++){
 5360:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5361:      jj1++;
 5362:      if (cptcovn > 0) {
 5363:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5364:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 5365: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5366: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 5367:        }
 5368:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5369:      }
 5370:      /* aij, bij */
 5371:      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> \
 5372: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 5373:      /* Pij */
 5374:      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> \
 5375: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 5376:      /* Quasi-incidences */
 5377:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 5378:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
 5379:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 5380: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 5381: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 5382:      /* Survival functions (period) in state j */
 5383:      for(cpt=1; cpt<=nlstate;cpt++){
 5384:        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> \
 5385: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 5386:      }
 5387:      /* State specific survival functions (period) */
 5388:      for(cpt=1; cpt<=nlstate;cpt++){
 5389:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 5390:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
 5391:  <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);
 5392:      }
 5393:      /* Period (stable) prevalence in each health state */
 5394:      for(cpt=1; cpt<=nlstate;cpt++){
 5395:        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> \
 5396: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 5397:      }
 5398:     if(backcast==1){
 5399:      /* Period (stable) back prevalence in each health state */
 5400:      for(cpt=1; cpt<=nlstate;cpt++){
 5401:        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> \
 5402: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 5403:      }
 5404:     }
 5405:     if(prevfcast==1){
 5406:       /* Projection of prevalence up to period (stable) prevalence in each health state */
 5407:       for(cpt=1; cpt<=nlstate;cpt++){
 5408: 	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> \
 5409: <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);
 5410:       }
 5411:     }
 5412: 
 5413:      for(cpt=1; cpt<=nlstate;cpt++) {
 5414:        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> \
 5415: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 5416:      }
 5417:    /* } /\* end i1 *\/ */
 5418:  }/* End k1 */
 5419:  fprintf(fichtm,"</ul>");
 5420: 
 5421:  fprintf(fichtm,"\
 5422: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 5423:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 5424:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 5425: But because parameters are usually highly correlated (a higher incidence of disability \
 5426: and a higher incidence of recovery can give very close observed transition) it might \
 5427: be very useful to look not only at linear confidence intervals estimated from the \
 5428: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 5429: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 5430: covariance matrix of the one-step probabilities. \
 5431: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 5432: 
 5433:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5434: 	 subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 5435:  fprintf(fichtm,"\
 5436:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5437: 	 subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 5438: 
 5439:  fprintf(fichtm,"\
 5440:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5441: 	 subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 5442:  fprintf(fichtm,"\
 5443:  - 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): \
 5444:    <a href=\"%s\">%s</a> <br>\n</li>",
 5445: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 5446:  fprintf(fichtm,"\
 5447:  - (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): \
 5448:    <a href=\"%s\">%s</a> <br>\n</li>",
 5449: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 5450:  fprintf(fichtm,"\
 5451:  - 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",
 5452: 	 estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 5453:  fprintf(fichtm,"\
 5454:  - 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",
 5455: 	 estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 5456:  fprintf(fichtm,"\
 5457:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 5458: 	 subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 5459: 
 5460: /*  if(popforecast==1) fprintf(fichtm,"\n */
 5461: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 5462: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 5463: /* 	<br>",fileres,fileres,fileres,fileres); */
 5464: /*  else  */
 5465: /*    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); */
 5466:  fflush(fichtm);
 5467:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 5468: 
 5469:  m=pow(2,cptcoveff);
 5470:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5471: 
 5472:  jj1=0;
 5473:  for(k1=1; k1<=m;k1++){
 5474:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5475:      jj1++;
 5476:      if (cptcovn > 0) {
 5477:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5478:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 5479: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5480:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5481:      }
 5482:      for(cpt=1; cpt<=nlstate;cpt++) {
 5483:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 5484: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
 5485: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 5486:      }
 5487:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 5488: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 5489: true period expectancies (those weighted with period prevalences are also\
 5490:  drawn in addition to the population based expectancies computed using\
 5491:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
 5492: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 5493:    /* } /\* end i1 *\/ */
 5494:  }/* End k1 */
 5495:  fprintf(fichtm,"</ul>");
 5496:  fflush(fichtm);
 5497: }
 5498: 
 5499: /******************* Gnuplot file **************/
 5500:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
 5501: 
 5502:   char dirfileres[132],optfileres[132];
 5503:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 5504:   int lv=0, vlv=0, kl=0;
 5505:   int ng=0;
 5506:   int vpopbased;
 5507: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 5508: /*     printf("Problem with file %s",optionfilegnuplot); */
 5509: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 5510: /*   } */
 5511: 
 5512:   /*#ifdef windows */
 5513:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5514:     /*#endif */
 5515:   m=pow(2,cptcoveff);
 5516: 
 5517:   /* Contribution to likelihood */
 5518:   /* Plot the probability implied in the likelihood */
 5519:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 5520:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 5521:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 5522:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 5523: /* nice for mle=4 plot by number of matrix products.
 5524:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 5525: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 5526:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 5527:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 5528:     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));
 5529:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 5530:     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));
 5531:     for (i=1; i<= nlstate ; i ++) {
 5532:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 5533:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 5534:       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);
 5535:       for (j=2; j<= nlstate+ndeath ; j ++) {
 5536: 	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);
 5537:       }
 5538:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 5539:     }
 5540:     /* 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 */		 
 5541:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 5542:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 5543:     fprintf(ficgp,"\nset out;unset log\n");
 5544:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 5545: 
 5546:   strcpy(dirfileres,optionfilefiname);
 5547:   strcpy(optfileres,"vpl");
 5548:  /* 1eme*/
 5549:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 5550:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
 5551:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 5552:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 5553:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5554: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5555: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5556: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5557: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5558: 	vlv= nbcode[Tvaraff[lv]][lv];
 5559: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5560:       }
 5561:       fprintf(ficgp,"\n#\n");
 5562: 
 5563:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 5564:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 5565:      fprintf(ficgp,"set xlabel \"Age\" \n\
 5566: set ylabel \"Probability\" \n\
 5567: set ter svg size 640, 480\n\
 5568: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5569: 
 5570:      for (i=1; i<= nlstate ; i ++) {
 5571:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5572:        else        fprintf(ficgp," %%*lf (%%*lf)");
 5573:      }
 5574:      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);
 5575:      for (i=1; i<= nlstate ; i ++) {
 5576:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5577:        else fprintf(ficgp," %%*lf (%%*lf)");
 5578:      } 
 5579:      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); 
 5580:      for (i=1; i<= nlstate ; i ++) {
 5581:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5582:        else fprintf(ficgp," %%*lf (%%*lf)");
 5583:      }  
 5584:      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));
 5585:      fprintf(ficgp,"\nset out \n");
 5586:     } /* k1 */
 5587:   } /* cpt */
 5588:   /*2 eme*/
 5589:   for (k1=1; k1<= m ; k1 ++) { 
 5590:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 5591:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5592: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5593: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5594: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5595: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5596: 	vlv= nbcode[Tvaraff[lv]][lv];
 5597: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5598:       }
 5599:       fprintf(ficgp,"\n#\n");
 5600: 
 5601:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 5602:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 5603:       if(vpopbased==0)
 5604: 	fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 5605:       else
 5606: 	fprintf(ficgp,"\nreplot ");
 5607:       for (i=1; i<= nlstate+1 ; i ++) {
 5608: 	k=2*i;
 5609: 	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);
 5610: 	for (j=1; j<= nlstate+1 ; j ++) {
 5611: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5612: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5613: 	}   
 5614: 	if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 5615: 	else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 5616: 	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);
 5617: 	for (j=1; j<= nlstate+1 ; j ++) {
 5618: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5619: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5620: 	}   
 5621: 	fprintf(ficgp,"\" t\"\" w l lt 0,");
 5622: 	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);
 5623: 	for (j=1; j<= nlstate+1 ; j ++) {
 5624: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5625: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5626: 	}   
 5627: 	if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 5628: 	else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 5629:       } /* state */
 5630:     } /* vpopbased */
 5631:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 5632:   } /* k1 */
 5633: 
 5634: 
 5635:   /*3eme*/
 5636:   for (k1=1; k1<= m ; k1 ++) { 
 5637:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 5638:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 5639:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5640: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5641: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5642: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5643: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5644: 	vlv= nbcode[Tvaraff[lv]][lv];
 5645: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5646:       }
 5647:       fprintf(ficgp,"\n#\n");
 5648: 
 5649:       /*       k=2+nlstate*(2*cpt-2); */
 5650:       k=2+(nlstate+1)*(cpt-1);
 5651:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 5652:       fprintf(ficgp,"set ter svg size 640, 480\n\
 5653: 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);
 5654:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5655: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5656: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5657: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5658: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5659: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5660: 	
 5661:       */
 5662:       for (i=1; i< nlstate ; i ++) {
 5663: 	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);
 5664: 	/*	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);*/
 5665: 	
 5666:       } 
 5667:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 5668:     }
 5669:   }
 5670:   
 5671:   /* Survival functions (period) from state i in state j by initial state i */
 5672:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 5673:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5674:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 5675:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5676: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5677: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5678: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5679: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5680: 	vlv= nbcode[Tvaraff[lv]][lv];
 5681: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5682:       }
 5683:       fprintf(ficgp,"\n#\n");
 5684: 
 5685:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 5686:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5687: set ter svg size 640, 480\n\
 5688: unset log y\n\
 5689: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5690:       k=3;
 5691:       for (i=1; i<= nlstate ; i ++){
 5692: 	if(i==1){
 5693: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5694: 	}else{
 5695: 	  fprintf(ficgp,", '' ");
 5696: 	}
 5697: 	l=(nlstate+ndeath)*(i-1)+1;
 5698: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5699: 	for (j=2; j<= nlstate+ndeath ; j ++)
 5700: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5701: 	fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 5702:       } /* nlstate */
 5703:       fprintf(ficgp,"\nset out\n");
 5704:     } /* end cpt state*/ 
 5705:   } /* end covariate */  
 5706: 
 5707:   /* Survival functions (period) from state i in state j by final state j */
 5708:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 5709:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 5710:       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);
 5711:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5712: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5713: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5714: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5715: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5716: 	vlv= nbcode[Tvaraff[lv]][lv];
 5717: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5718:       }
 5719:       fprintf(ficgp,"\n#\n");
 5720: 
 5721:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 5722:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5723: set ter svg size 640, 480\n\
 5724: unset log y\n\
 5725: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5726:       k=3;
 5727:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5728: 	if(j==1)
 5729: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5730: 	else
 5731: 	  fprintf(ficgp,", '' ");
 5732: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5733: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 5734: 	/* for (i=2; i<= nlstate+ndeath ; i ++) */
 5735: 	/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 5736: 	fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 5737:       } /* nlstate */
 5738:       fprintf(ficgp,", '' ");
 5739:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 5740:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5741: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5742: 	if(j < nlstate)
 5743: 	  fprintf(ficgp,"$%d +",k+l);
 5744: 	else
 5745: 	  fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 5746:       }
 5747:       fprintf(ficgp,"\nset out\n");
 5748:     } /* end cpt state*/ 
 5749:   } /* end covariate */  
 5750: 
 5751:   /* CV preval stable (period) for each covariate */
 5752:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5753:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5754:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 5755:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5756: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5757: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5758: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5759: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5760: 	vlv= nbcode[Tvaraff[lv]][lv];
 5761: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5762:       }
 5763:       fprintf(ficgp,"\n#\n");
 5764: 
 5765:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 5766:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 5767: set ter svg size 640, 480\n\
 5768: unset log y\n\
 5769: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5770:       k=3; /* Offset */
 5771:       for (i=1; i<= nlstate ; i ++){
 5772: 	if(i==1)
 5773: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5774: 	else
 5775: 	  fprintf(ficgp,", '' ");
 5776: 	l=(nlstate+ndeath)*(i-1)+1;
 5777: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5778: 	for (j=2; j<= nlstate ; j ++)
 5779: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5780: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 5781:       } /* nlstate */
 5782:       fprintf(ficgp,"\nset out\n");
 5783:     } /* end cpt state*/ 
 5784:   } /* end covariate */  
 5785: 
 5786:     /* CV back preval stable (period) for each covariate */
 5787:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5788:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5789:       fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 5790:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5791: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5792: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5793: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5794: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5795: 	vlv= nbcode[Tvaraff[lv]][lv];
 5796: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5797:       }
 5798:       fprintf(ficgp,"\n#\n");
 5799: 
 5800:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 5801:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 5802: set ter svg size 640, 480\n\
 5803: unset log y\n\
 5804: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5805:       k=3; /* Offset */
 5806:       for (i=1; i<= nlstate ; i ++){
 5807: 	if(i==1)
 5808: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 5809: 	else
 5810: 	  fprintf(ficgp,", '' ");
 5811: 	l=(nlstate+ndeath)*(i-1)+1;
 5812: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /* a vérifier */
 5813: 	for (j=2; j<= nlstate ; j ++)
 5814: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5815: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 5816:       } /* nlstate */
 5817:       fprintf(ficgp,"\nset out\n");
 5818:     } /* end cpt state*/ 
 5819:   } /* end covariate */  
 5820: 
 5821:   if(prevfcast==1){
 5822:   /* Projection from cross-sectional to stable (period) for each covariate */
 5823: 
 5824:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5825:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5826: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 5827: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 5828: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5829: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5830: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5831: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5832: 	  vlv= nbcode[Tvaraff[lv]][lv];
 5833: 	  fprintf(ficgp," V%d=%d ",k,vlv);
 5834: 	}
 5835: 	fprintf(ficgp,"\n#\n");
 5836: 	
 5837: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 5838: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 5839: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 5840: set ter svg size 640, 480\n\
 5841: unset log y\n\
 5842: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5843: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 5844: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5845: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5846: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5847: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5848: 	  if(i==1){
 5849: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 5850: 	  }else{
 5851: 	    fprintf(ficgp,",\\\n '' ");
 5852: 	  }
 5853: 	  if(cptcoveff ==0){ /* No covariate */
 5854: 	    fprintf(ficgp," u 2:("); /* Age is in 2 */
 5855: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 5856: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 5857: 	    if(i==nlstate+1)
 5858: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
 5859: 			2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
 5860: 	    else
 5861: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
 5862: 		      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 5863: 	  }else{
 5864: 	    fprintf(ficgp,"u 6:(("); /* Age is in 6 */
 5865: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5866: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5867: 	    kl=0;
 5868: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
 5869: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5870: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5871: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5872: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5873: 	      vlv= nbcode[Tvaraff[lv]][lv];
 5874: 	      kl++;
 5875: 	      /* 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 *\/ */
 5876: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 5877: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 5878: 	      /* ''  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*/
 5879: 	      if(k==cptcoveff)
 5880: 		if(i==nlstate+1)
 5881: 		  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
 5882: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
 5883: 		else
 5884: 		  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], \
 5885: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 5886: 	      else{
 5887: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
 5888: 		kl++;
 5889: 	      }
 5890: 	    } /* end covariate */
 5891: 	  } /* end if covariate */
 5892: 	} /* nlstate */
 5893: 	fprintf(ficgp,"\nset out\n");
 5894:       } /* end cpt state*/
 5895:     } /* end covariate */
 5896:   } /* End if prevfcast */
 5897: 
 5898: 
 5899:   /* proba elementaires */
 5900:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 5901:   for(i=1,jk=1; i <=nlstate; i++){
 5902:     fprintf(ficgp,"# initial state %d\n",i);
 5903:     for(k=1; k <=(nlstate+ndeath); k++){
 5904:       if (k != i) {
 5905: 	fprintf(ficgp,"#   current state %d\n",k);
 5906: 	for(j=1; j <=ncovmodel; j++){
 5907: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 5908: 	  jk++; 
 5909: 	}
 5910: 	fprintf(ficgp,"\n");
 5911:       }
 5912:     }
 5913:    }
 5914:   fprintf(ficgp,"##############\n#\n");
 5915: 
 5916:   /*goto avoid;*/
 5917:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 5918:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 5919:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 5920:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 5921:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 5922:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5923:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 5924:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5925:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 5926:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 5927:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5928:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 5929:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 5930:   fprintf(ficgp,"#\n");
 5931:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 5932:      fprintf(ficgp,"# ng=%d\n",ng);
 5933:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 5934:      for(jk=1; jk <=m; jk++) {
 5935:        fprintf(ficgp,"#    jk=%d\n",jk);
 5936:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 5937:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
 5938:        if (ng==1){
 5939: 	 fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 5940: 	 fprintf(ficgp,"\nunset log y");
 5941:        }else if (ng==2){
 5942: 	 fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 5943: 	 fprintf(ficgp,"\nset log y");
 5944:        }else if (ng==3){
 5945: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 5946: 	 fprintf(ficgp,"\nset log y");
 5947:        }else
 5948: 	 fprintf(ficgp,"\nunset title ");
 5949:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 5950:        i=1;
 5951:        for(k2=1; k2<=nlstate; k2++) {
 5952: 	 k3=i;
 5953: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 5954: 	   if (k != k2){
 5955: 	     switch( ng) {
 5956: 	     case 1:
 5957: 	       if(nagesqr==0)
 5958: 		 fprintf(ficgp," p%d+p%d*x",i,i+1);
 5959: 	       else /* nagesqr =1 */
 5960: 		 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 5961: 	       break;
 5962: 	     case 2: /* ng=2 */
 5963: 	       if(nagesqr==0)
 5964: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 5965: 	       else /* nagesqr =1 */
 5966: 		   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 5967: 	       break;
 5968: 	     case 3:
 5969: 	       if(nagesqr==0)
 5970: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 5971: 	       else /* nagesqr =1 */
 5972: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 5973: 	       break;
 5974: 	     }
 5975: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 5976: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 5977: 	       /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 5978: 	       if(ij <=cptcovage) { /* Bug valgrind */
 5979: 		 if((j-2)==Tage[ij]) { /* Bug valgrind */
 5980: 		   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5981: 		   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 5982: 		   ij++;
 5983: 		 }
 5984: 	       }
 5985: 	       else
 5986: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5987: 	     }
 5988: 	   }else{
 5989: 	     i=i-ncovmodel;
 5990: 	     if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 5991: 	       fprintf(ficgp," (1.");
 5992: 	   }
 5993: 	   
 5994: 	   if(ng != 1){
 5995: 	     fprintf(ficgp,")/(1");
 5996: 	     
 5997: 	     for(k1=1; k1 <=nlstate; k1++){ 
 5998: 	       if(nagesqr==0)
 5999: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6000: 	       else /* nagesqr =1 */
 6001: 		 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);
 6002: 	       
 6003: 	       ij=1;
 6004: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 6005: 		 if(ij <=cptcovage) { /* Bug valgrind */
 6006: 		   if((j-2)==Tage[ij]) { /* Bug valgrind */
 6007: 		     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6008: 		     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6009: 		     ij++;
 6010: 		   }
 6011: 		 }
 6012: 		 else
 6013: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6014: 	       }
 6015: 	       fprintf(ficgp,")");
 6016: 	     }
 6017: 	     fprintf(ficgp,")");
 6018: 	     if(ng ==2)
 6019: 	       fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6020: 	     else /* ng= 3 */
 6021: 	       fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6022: 	   }else{ /* end ng <> 1 */
 6023: 	     if( k !=k2) /* logit p11 is hard to draw */
 6024: 	       fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6025: 	   }
 6026: 	   if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6027: 	     fprintf(ficgp,",");
 6028: 	   if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6029: 	     fprintf(ficgp,",");
 6030: 	   i=i+ncovmodel;
 6031: 	 } /* end k */
 6032:        } /* end k2 */
 6033:        fprintf(ficgp,"\n set out\n");
 6034:      } /* end jk */
 6035:    } /* end ng */
 6036:  /* avoid: */
 6037:    fflush(ficgp); 
 6038: }  /* end gnuplot */
 6039: 
 6040: 
 6041: /*************** Moving average **************/
 6042: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 6043: 
 6044:   int i, cpt, cptcod;
 6045:   int modcovmax =1;
 6046:   int mobilavrange, mob;
 6047:   double age;
 6048: 
 6049:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 6050: 			   a covariate has 2 modalities */
 6051:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 6052: 
 6053:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 6054:     if(mobilav==1) mobilavrange=5; /* default */
 6055:     else mobilavrange=mobilav;
 6056:     for (age=bage; age<=fage; age++)
 6057:       for (i=1; i<=nlstate;i++)
 6058: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 6059: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 6060:     /* We keep the original values on the extreme ages bage, fage and for 
 6061:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 6062:        we use a 5 terms etc. until the borders are no more concerned. 
 6063:     */ 
 6064:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 6065:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 6066: 	for (i=1; i<=nlstate;i++){
 6067: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 6068: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 6069: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 6070: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 6071: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 6072: 	      }
 6073: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 6074: 	  }
 6075: 	}
 6076:       }/* end age */
 6077:     }/* end mob */
 6078:   }else return -1;
 6079:   return 0;
 6080: }/* End movingaverage */
 6081: 
 6082: 
 6083: /************** Forecasting ******************/
 6084: 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){
 6085:   /* proj1, year, month, day of starting projection 
 6086:      agemin, agemax range of age
 6087:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6088:      anproj2 year of en of projection (same day and month as proj1).
 6089:   */
 6090:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6091:   double agec; /* generic age */
 6092:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6093:   double *popeffectif,*popcount;
 6094:   double ***p3mat;
 6095:   double ***mobaverage;
 6096:   char fileresf[FILENAMELENGTH];
 6097: 
 6098:   agelim=AGESUP;
 6099:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6100:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6101:      We still use firstpass and lastpass as another selection.
 6102:   */
 6103:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6104:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6105:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6106:  
 6107:   strcpy(fileresf,"F_"); 
 6108:   strcat(fileresf,fileresu);
 6109:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 6110:     printf("Problem with forecast resultfile: %s\n", fileresf);
 6111:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 6112:   }
 6113:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6114:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6115: 
 6116:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6117: 
 6118:   if (mobilav!=0) {
 6119:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6120:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 6121:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6122:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6123:     }
 6124:   }
 6125: 
 6126:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6127:   if (stepm<=12) stepsize=1;
 6128:   if(estepm < stepm){
 6129:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6130:   }
 6131:   else  hstepm=estepm;   
 6132: 
 6133:   hstepm=hstepm/stepm; 
 6134:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6135:                                fractional in yp1 */
 6136:   anprojmean=yp;
 6137:   yp2=modf((yp1*12),&yp);
 6138:   mprojmean=yp;
 6139:   yp1=modf((yp2*30.5),&yp);
 6140:   jprojmean=yp;
 6141:   if(jprojmean==0) jprojmean=1;
 6142:   if(mprojmean==0) jprojmean=1;
 6143: 
 6144:   i1=cptcoveff;
 6145:   if (cptcovn < 1){i1=1;}
 6146:   
 6147:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6148:   
 6149:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 6150: 
 6151: /* 	      if (h==(int)(YEARM*yearp)){ */
 6152:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 6153:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6154:       k=k+1;
 6155:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6156:       for(j=1;j<=cptcoveff;j++) {
 6157: 	fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6158:       }
 6159:       fprintf(ficresf," yearproj age");
 6160:       for(j=1; j<=nlstate+ndeath;j++){ 
 6161: 	for(i=1; i<=nlstate;i++) 	      
 6162:           fprintf(ficresf," p%d%d",i,j);
 6163: 	fprintf(ficresf," p.%d",j);
 6164:       }
 6165:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 6166: 	fprintf(ficresf,"\n");
 6167: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 6168:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6169: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6170: 	  nhstepm = nhstepm/hstepm; 
 6171: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6172: 	  oldm=oldms;savm=savms;
 6173: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
 6174: 	
 6175: 	  for (h=0; h<=nhstepm; h++){
 6176: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 6177:               fprintf(ficresf,"\n");
 6178:               for(j=1;j<=cptcoveff;j++) 
 6179:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6180: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 6181: 	    } 
 6182: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6183: 	      ppij=0.;
 6184: 	      for(i=1; i<=nlstate;i++) {
 6185: 		if (mobilav==1) 
 6186: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 6187: 		else {
 6188: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 6189: 		}
 6190: 		if (h*hstepm/YEARM*stepm== yearp) {
 6191: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 6192: 		}
 6193: 	      } /* end i */
 6194: 	      if (h*hstepm/YEARM*stepm==yearp) {
 6195: 		fprintf(ficresf," %.3f", ppij);
 6196: 	      }
 6197: 	    }/* end j */
 6198: 	  } /* end h */
 6199: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6200: 	} /* end agec */
 6201:       } /* end yearp */
 6202:     } /* end cptcod */
 6203:   } /* end  cptcov */
 6204:        
 6205:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6206: 
 6207:   fclose(ficresf);
 6208:   printf("End of Computing forecasting \n");
 6209:   fprintf(ficlog,"End of Computing forecasting\n");
 6210: 
 6211: }
 6212: 
 6213: /************** Back Forecasting ******************/
 6214: 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){
 6215:   /* back1, year, month, day of starting backection 
 6216:      agemin, agemax range of age
 6217:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6218:      anback2 year of en of backection (same day and month as back1).
 6219:   */
 6220:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6221:   double agec; /* generic age */
 6222:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6223:   double *popeffectif,*popcount;
 6224:   double ***p3mat;
 6225:   double ***mobaverage;
 6226:   char fileresfb[FILENAMELENGTH];
 6227: 
 6228:   agelim=AGESUP;
 6229:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6230:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6231:      We still use firstpass and lastpass as another selection.
 6232:   */
 6233:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6234:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6235:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6236:  
 6237:   strcpy(fileresfb,"FB_"); 
 6238:   strcat(fileresfb,fileresu);
 6239:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
 6240:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
 6241:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
 6242:   }
 6243:   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb);
 6244:   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb);
 6245: 
 6246:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6247: 
 6248:   if (mobilav!=0) {
 6249:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6250:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 6251:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6252:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6253:     }
 6254:   }
 6255: 
 6256:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6257:   if (stepm<=12) stepsize=1;
 6258:   if(estepm < stepm){
 6259:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6260:   }
 6261:   else  hstepm=estepm;   
 6262: 
 6263:   hstepm=hstepm/stepm; 
 6264:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6265:                                fractional in yp1 */
 6266:   anprojmean=yp;
 6267:   yp2=modf((yp1*12),&yp);
 6268:   mprojmean=yp;
 6269:   yp1=modf((yp2*30.5),&yp);
 6270:   jprojmean=yp;
 6271:   if(jprojmean==0) jprojmean=1;
 6272:   if(mprojmean==0) jprojmean=1;
 6273: 
 6274:   i1=cptcoveff;
 6275:   if (cptcovn < 1){i1=1;}
 6276:   
 6277:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6278:   
 6279:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
 6280: 
 6281: /* 	      if (h==(int)(YEARM*yearp)){ */
 6282:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 6283:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6284:       k=k+1;
 6285:       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6286:       for(j=1;j<=cptcoveff;j++) {
 6287: 	fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6288:       }
 6289:       fprintf(ficresfb," yearbproj age");
 6290:       for(j=1; j<=nlstate+ndeath;j++){ 
 6291: 	for(i=1; i<=nlstate;i++) 	      
 6292:           fprintf(ficresfb," p%d%d",i,j);
 6293: 	fprintf(ficresfb," p.%d",j);
 6294:       }
 6295:       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) { 
 6296:      /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
 6297: 	fprintf(ficresfb,"\n");
 6298: 	fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);   
 6299:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6300: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6301: 	  nhstepm = nhstepm/hstepm; 
 6302: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6303: 	  oldm=oldms;savm=savms;
 6304: 	  hbxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6305: 	
 6306: 	  for (h=0; h<=nhstepm; h++){
 6307: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 6308:               fprintf(ficresfb,"\n");
 6309:               for(j=1;j<=cptcoveff;j++) 
 6310:                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6311: 	      fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm);
 6312: 	    } 
 6313: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6314: 	      ppij=0.;
 6315: 	      for(i=1; i<=nlstate;i++) {
 6316: 		if (mobilav==1) 
 6317: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 6318: 		else {
 6319: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 6320: 		}
 6321: 		if (h*hstepm/YEARM*stepm== yearp) {
 6322: 		  fprintf(ficresfb," %.3f", p3mat[i][j][h]);
 6323: 		}
 6324: 	      } /* end i */
 6325: 	      if (h*hstepm/YEARM*stepm==yearp) {
 6326: 		fprintf(ficresfb," %.3f", ppij);
 6327: 	      }
 6328: 	    }/* end j */
 6329: 	  } /* end h */
 6330: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6331: 	} /* end agec */
 6332:       } /* end yearp */
 6333:     } /* end cptcod */
 6334:   } /* end  cptcov */
 6335:        
 6336:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6337: 
 6338:   fclose(ficresfb);
 6339:   printf("End of Computing Back forecasting \n");
 6340:   fprintf(ficlog,"End of Computing Back forecasting\n");
 6341: 
 6342: }
 6343: 
 6344: /************** Forecasting *****not tested NB*************/
 6345: 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){
 6346:   
 6347:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 6348:   int *popage;
 6349:   double calagedatem, agelim, kk1, kk2;
 6350:   double *popeffectif,*popcount;
 6351:   double ***p3mat,***tabpop,***tabpopprev;
 6352:   double ***mobaverage;
 6353:   char filerespop[FILENAMELENGTH];
 6354: 
 6355:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6356:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6357:   agelim=AGESUP;
 6358:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 6359:   
 6360:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6361:   
 6362:   
 6363:   strcpy(filerespop,"POP_"); 
 6364:   strcat(filerespop,fileresu);
 6365:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 6366:     printf("Problem with forecast resultfile: %s\n", filerespop);
 6367:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 6368:   }
 6369:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 6370:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 6371: 
 6372:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6373: 
 6374:   if (mobilav!=0) {
 6375:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6376:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 6377:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6378:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6379:     }
 6380:   }
 6381: 
 6382:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6383:   if (stepm<=12) stepsize=1;
 6384:   
 6385:   agelim=AGESUP;
 6386:   
 6387:   hstepm=1;
 6388:   hstepm=hstepm/stepm; 
 6389:   
 6390:   if (popforecast==1) {
 6391:     if((ficpop=fopen(popfile,"r"))==NULL) {
 6392:       printf("Problem with population file : %s\n",popfile);exit(0);
 6393:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 6394:     } 
 6395:     popage=ivector(0,AGESUP);
 6396:     popeffectif=vector(0,AGESUP);
 6397:     popcount=vector(0,AGESUP);
 6398:     
 6399:     i=1;   
 6400:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 6401:    
 6402:     imx=i;
 6403:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 6404:   }
 6405: 
 6406:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 6407:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6408:       k=k+1;
 6409:       fprintf(ficrespop,"\n#******");
 6410:       for(j=1;j<=cptcoveff;j++) {
 6411: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6412:       }
 6413:       fprintf(ficrespop,"******\n");
 6414:       fprintf(ficrespop,"# Age");
 6415:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 6416:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 6417:       
 6418:       for (cpt=0; cpt<=0;cpt++) { 
 6419: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6420: 	
 6421:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6422: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6423: 	  nhstepm = nhstepm/hstepm; 
 6424: 	  
 6425: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6426: 	  oldm=oldms;savm=savms;
 6427: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6428: 	
 6429: 	  for (h=0; h<=nhstepm; h++){
 6430: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6431: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6432: 	    } 
 6433: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6434: 	      kk1=0.;kk2=0;
 6435: 	      for(i=1; i<=nlstate;i++) {	      
 6436: 		if (mobilav==1) 
 6437: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 6438: 		else {
 6439: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 6440: 		}
 6441: 	      }
 6442: 	      if (h==(int)(calagedatem+12*cpt)){
 6443: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 6444: 		  /*fprintf(ficrespop," %.3f", kk1);
 6445: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 6446: 	      }
 6447: 	    }
 6448: 	    for(i=1; i<=nlstate;i++){
 6449: 	      kk1=0.;
 6450: 		for(j=1; j<=nlstate;j++){
 6451: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 6452: 		}
 6453: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 6454: 	    }
 6455: 
 6456: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 6457: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 6458: 	  }
 6459: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6460: 	}
 6461:       }
 6462:  
 6463:   /******/
 6464: 
 6465:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 6466: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6467: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6468: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6469: 	  nhstepm = nhstepm/hstepm; 
 6470: 	  
 6471: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6472: 	  oldm=oldms;savm=savms;
 6473: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6474: 	  for (h=0; h<=nhstepm; h++){
 6475: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6476: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6477: 	    } 
 6478: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6479: 	      kk1=0.;kk2=0;
 6480: 	      for(i=1; i<=nlstate;i++) {	      
 6481: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 6482: 	      }
 6483: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 6484: 	    }
 6485: 	  }
 6486: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6487: 	}
 6488:       }
 6489:    } 
 6490:   }
 6491:  
 6492:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6493: 
 6494:   if (popforecast==1) {
 6495:     free_ivector(popage,0,AGESUP);
 6496:     free_vector(popeffectif,0,AGESUP);
 6497:     free_vector(popcount,0,AGESUP);
 6498:   }
 6499:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6500:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6501:   fclose(ficrespop);
 6502: } /* End of popforecast */
 6503: 
 6504: int fileappend(FILE *fichier, char *optionfich)
 6505: {
 6506:   if((fichier=fopen(optionfich,"a"))==NULL) {
 6507:     printf("Problem with file: %s\n", optionfich);
 6508:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 6509:     return (0);
 6510:   }
 6511:   fflush(fichier);
 6512:   return (1);
 6513: }
 6514: 
 6515: 
 6516: /**************** function prwizard **********************/
 6517: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 6518: {
 6519: 
 6520:   /* Wizard to print covariance matrix template */
 6521: 
 6522:   char ca[32], cb[32];
 6523:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 6524:   int numlinepar;
 6525: 
 6526:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6527:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6528:   for(i=1; i <=nlstate; i++){
 6529:     jj=0;
 6530:     for(j=1; j <=nlstate+ndeath; j++){
 6531:       if(j==i) continue;
 6532:       jj++;
 6533:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 6534:       printf("%1d%1d",i,j);
 6535:       fprintf(ficparo,"%1d%1d",i,j);
 6536:       for(k=1; k<=ncovmodel;k++){
 6537: 	/* 	  printf(" %lf",param[i][j][k]); */
 6538: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 6539: 	printf(" 0.");
 6540: 	fprintf(ficparo," 0.");
 6541:       }
 6542:       printf("\n");
 6543:       fprintf(ficparo,"\n");
 6544:     }
 6545:   }
 6546:   printf("# Scales (for hessian or gradient estimation)\n");
 6547:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 6548:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 6549:   for(i=1; i <=nlstate; i++){
 6550:     jj=0;
 6551:     for(j=1; j <=nlstate+ndeath; j++){
 6552:       if(j==i) continue;
 6553:       jj++;
 6554:       fprintf(ficparo,"%1d%1d",i,j);
 6555:       printf("%1d%1d",i,j);
 6556:       fflush(stdout);
 6557:       for(k=1; k<=ncovmodel;k++){
 6558: 	/* 	printf(" %le",delti3[i][j][k]); */
 6559: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 6560: 	printf(" 0.");
 6561: 	fprintf(ficparo," 0.");
 6562:       }
 6563:       numlinepar++;
 6564:       printf("\n");
 6565:       fprintf(ficparo,"\n");
 6566:     }
 6567:   }
 6568:   printf("# Covariance matrix\n");
 6569: /* # 121 Var(a12)\n\ */
 6570: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6571: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6572: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6573: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6574: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6575: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6576: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6577:   fflush(stdout);
 6578:   fprintf(ficparo,"# Covariance matrix\n");
 6579:   /* # 121 Var(a12)\n\ */
 6580:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6581:   /* #   ...\n\ */
 6582:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 6583:   
 6584:   for(itimes=1;itimes<=2;itimes++){
 6585:     jj=0;
 6586:     for(i=1; i <=nlstate; i++){
 6587:       for(j=1; j <=nlstate+ndeath; j++){
 6588: 	if(j==i) continue;
 6589: 	for(k=1; k<=ncovmodel;k++){
 6590: 	  jj++;
 6591: 	  ca[0]= k+'a'-1;ca[1]='\0';
 6592: 	  if(itimes==1){
 6593: 	    printf("#%1d%1d%d",i,j,k);
 6594: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 6595: 	  }else{
 6596: 	    printf("%1d%1d%d",i,j,k);
 6597: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 6598: 	    /* 	printf(" %.5le",matcov[i][j]); */
 6599: 	  }
 6600: 	  ll=0;
 6601: 	  for(li=1;li <=nlstate; li++){
 6602: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 6603: 	      if(lj==li) continue;
 6604: 	      for(lk=1;lk<=ncovmodel;lk++){
 6605: 		ll++;
 6606: 		if(ll<=jj){
 6607: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 6608: 		  if(ll<jj){
 6609: 		    if(itimes==1){
 6610: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6611: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6612: 		    }else{
 6613: 		      printf(" 0.");
 6614: 		      fprintf(ficparo," 0.");
 6615: 		    }
 6616: 		  }else{
 6617: 		    if(itimes==1){
 6618: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 6619: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 6620: 		    }else{
 6621: 		      printf(" 0.");
 6622: 		      fprintf(ficparo," 0.");
 6623: 		    }
 6624: 		  }
 6625: 		}
 6626: 	      } /* end lk */
 6627: 	    } /* end lj */
 6628: 	  } /* end li */
 6629: 	  printf("\n");
 6630: 	  fprintf(ficparo,"\n");
 6631: 	  numlinepar++;
 6632: 	} /* end k*/
 6633:       } /*end j */
 6634:     } /* end i */
 6635:   } /* end itimes */
 6636: 
 6637: } /* end of prwizard */
 6638: /******************* Gompertz Likelihood ******************************/
 6639: double gompertz(double x[])
 6640: { 
 6641:   double A,B,L=0.0,sump=0.,num=0.;
 6642:   int i,n=0; /* n is the size of the sample */
 6643: 
 6644:   for (i=0;i<=imx-1 ; i++) {
 6645:     sump=sump+weight[i];
 6646:     /*    sump=sump+1;*/
 6647:     num=num+1;
 6648:   }
 6649:  
 6650:  
 6651:   /* for (i=0; i<=imx; i++) 
 6652:      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]);*/
 6653: 
 6654:   for (i=1;i<=imx ; i++)
 6655:     {
 6656:       if (cens[i] == 1 && wav[i]>1)
 6657: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 6658:       
 6659:       if (cens[i] == 0 && wav[i]>1)
 6660: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 6661: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 6662:       
 6663:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 6664:       if (wav[i] > 1 ) { /* ??? */
 6665: 	L=L+A*weight[i];
 6666: 	/* 	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]);*/
 6667:       }
 6668:     }
 6669: 
 6670:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 6671:  
 6672:   return -2*L*num/sump;
 6673: }
 6674: 
 6675: #ifdef GSL
 6676: /******************* Gompertz_f Likelihood ******************************/
 6677: double gompertz_f(const gsl_vector *v, void *params)
 6678: { 
 6679:   double A,B,LL=0.0,sump=0.,num=0.;
 6680:   double *x= (double *) v->data;
 6681:   int i,n=0; /* n is the size of the sample */
 6682: 
 6683:   for (i=0;i<=imx-1 ; i++) {
 6684:     sump=sump+weight[i];
 6685:     /*    sump=sump+1;*/
 6686:     num=num+1;
 6687:   }
 6688:  
 6689:  
 6690:   /* for (i=0; i<=imx; i++) 
 6691:      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]);*/
 6692:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 6693:   for (i=1;i<=imx ; i++)
 6694:     {
 6695:       if (cens[i] == 1 && wav[i]>1)
 6696: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 6697:       
 6698:       if (cens[i] == 0 && wav[i]>1)
 6699: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 6700: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 6701:       
 6702:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 6703:       if (wav[i] > 1 ) { /* ??? */
 6704: 	LL=LL+A*weight[i];
 6705: 	/* 	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]);*/
 6706:       }
 6707:     }
 6708: 
 6709:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 6710:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 6711:  
 6712:   return -2*LL*num/sump;
 6713: }
 6714: #endif
 6715: 
 6716: /******************* Printing html file ***********/
 6717: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 6718: 		  int lastpass, int stepm, int weightopt, char model[],\
 6719: 		  int imx,  double p[],double **matcov,double agemortsup){
 6720:   int i,k;
 6721: 
 6722:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 6723:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 6724:   for (i=1;i<=2;i++) 
 6725:     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]));
 6726:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 6727:   fprintf(fichtm,"</ul>");
 6728: 
 6729: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 6730: 
 6731:  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>");
 6732: 
 6733:  for (k=agegomp;k<(agemortsup-2);k++) 
 6734:    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]);
 6735: 
 6736:  
 6737:   fflush(fichtm);
 6738: }
 6739: 
 6740: /******************* Gnuplot file **************/
 6741: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 6742: 
 6743:   char dirfileres[132],optfileres[132];
 6744: 
 6745:   int ng;
 6746: 
 6747: 
 6748:   /*#ifdef windows */
 6749:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6750:     /*#endif */
 6751: 
 6752: 
 6753:   strcpy(dirfileres,optionfilefiname);
 6754:   strcpy(optfileres,"vpl");
 6755:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 6756:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 6757:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 6758:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 6759:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 6760: 
 6761: } 
 6762: 
 6763: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 6764: {
 6765: 
 6766:   /*-------- data file ----------*/
 6767:   FILE *fic;
 6768:   char dummy[]="                         ";
 6769:   int i=0, j=0, n=0;
 6770:   int linei, month, year,iout;
 6771:   char line[MAXLINE], linetmp[MAXLINE];
 6772:   char stra[MAXLINE], strb[MAXLINE];
 6773:   char *stratrunc;
 6774:   int lstra;
 6775: 
 6776: 
 6777:   if((fic=fopen(datafile,"r"))==NULL)    {
 6778:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
 6779:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
 6780:   }
 6781: 
 6782:   i=1;
 6783:   linei=0;
 6784:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 6785:     linei=linei+1;
 6786:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 6787:       if(line[j] == '\t')
 6788: 	line[j] = ' ';
 6789:     }
 6790:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 6791:       ;
 6792:     };
 6793:     line[j+1]=0;  /* Trims blanks at end of line */
 6794:     if(line[0]=='#'){
 6795:       fprintf(ficlog,"Comment line\n%s\n",line);
 6796:       printf("Comment line\n%s\n",line);
 6797:       continue;
 6798:     }
 6799:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 6800:     strcpy(line, linetmp);
 6801:   
 6802: 
 6803:     for (j=maxwav;j>=1;j--){
 6804:       cutv(stra, strb, line, ' '); 
 6805:       if(strb[0]=='.') { /* Missing status */
 6806: 	lval=-1;
 6807:       }else{
 6808: 	errno=0;
 6809: 	lval=strtol(strb,&endptr,10); 
 6810:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 6811: 	if( strb[0]=='\0' || (*endptr != '\0')){
 6812: 	  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);
 6813: 	  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);
 6814: 	  return 1;
 6815: 	}
 6816:       }
 6817:       s[j][i]=lval;
 6818:       
 6819:       strcpy(line,stra);
 6820:       cutv(stra, strb,line,' ');
 6821:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6822:       }
 6823:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 6824: 	month=99;
 6825: 	year=9999;
 6826:       }else{
 6827: 	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);
 6828: 	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);
 6829: 	return 1;
 6830:       }
 6831:       anint[j][i]= (double) year; 
 6832:       mint[j][i]= (double)month; 
 6833:       strcpy(line,stra);
 6834:     } /* ENd Waves */
 6835:     
 6836:     cutv(stra, strb,line,' '); 
 6837:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6838:     }
 6839:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 6840:       month=99;
 6841:       year=9999;
 6842:     }else{
 6843:       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);
 6844: 	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);
 6845: 	return 1;
 6846:     }
 6847:     andc[i]=(double) year; 
 6848:     moisdc[i]=(double) month; 
 6849:     strcpy(line,stra);
 6850:     
 6851:     cutv(stra, strb,line,' '); 
 6852:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6853:     }
 6854:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 6855:       month=99;
 6856:       year=9999;
 6857:     }else{
 6858:       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);
 6859:       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);
 6860: 	return 1;
 6861:     }
 6862:     if (year==9999) {
 6863:       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);
 6864:       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);
 6865: 	return 1;
 6866: 
 6867:     }
 6868:     annais[i]=(double)(year);
 6869:     moisnais[i]=(double)(month); 
 6870:     strcpy(line,stra);
 6871:     
 6872:     cutv(stra, strb,line,' '); 
 6873:     errno=0;
 6874:     dval=strtod(strb,&endptr); 
 6875:     if( strb[0]=='\0' || (*endptr != '\0')){
 6876:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 6877:       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);
 6878:       fflush(ficlog);
 6879:       return 1;
 6880:     }
 6881:     weight[i]=dval; 
 6882:     strcpy(line,stra);
 6883:     
 6884:     for (j=ncovcol;j>=1;j--){
 6885:       cutv(stra, strb,line,' '); 
 6886:       if(strb[0]=='.') { /* Missing status */
 6887: 	lval=-1;
 6888:       }else{
 6889: 	errno=0;
 6890: 	lval=strtol(strb,&endptr,10); 
 6891: 	if( strb[0]=='\0' || (*endptr != '\0')){
 6892: 	  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);
 6893: 	  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);
 6894: 	  return 1;
 6895: 	}
 6896:       }
 6897:       if(lval <-1 || lval >1){
 6898: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 6899:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 6900:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 6901:  For example, for multinomial values like 1, 2 and 3,\n \
 6902:  build V1=0 V2=0 for the reference value (1),\n \
 6903:         V1=1 V2=0 for (2) \n \
 6904:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 6905:  output of IMaCh is often meaningless.\n \
 6906:  Exiting.\n",lval,linei, i,line,j);
 6907: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 6908:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 6909:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 6910:  For example, for multinomial values like 1, 2 and 3,\n \
 6911:  build V1=0 V2=0 for the reference value (1),\n \
 6912:         V1=1 V2=0 for (2) \n \
 6913:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 6914:  output of IMaCh is often meaningless.\n \
 6915:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 6916: 	return 1;
 6917:       }
 6918:       covar[j][i]=(double)(lval);
 6919:       strcpy(line,stra);
 6920:     }  
 6921:     lstra=strlen(stra);
 6922:      
 6923:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 6924:       stratrunc = &(stra[lstra-9]);
 6925:       num[i]=atol(stratrunc);
 6926:     }
 6927:     else
 6928:       num[i]=atol(stra);
 6929:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 6930:       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;}*/
 6931:     
 6932:     i=i+1;
 6933:   } /* End loop reading  data */
 6934: 
 6935:   *imax=i-1; /* Number of individuals */
 6936:   fclose(fic);
 6937:  
 6938:   return (0);
 6939:   /* endread: */
 6940:     printf("Exiting readdata: ");
 6941:     fclose(fic);
 6942:     return (1);
 6943: 
 6944: 
 6945: 
 6946: }
 6947: void removespace(char *str) {
 6948:   char *p1 = str, *p2 = str;
 6949:   do
 6950:     while (*p2 == ' ')
 6951:       p2++;
 6952:   while (*p1++ == *p2++);
 6953: }
 6954: 
 6955: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 6956:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 6957:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 6958:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 6959:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 6960:    * - cptcovage number of covariates with age*products =2
 6961:    * - cptcovs number of simple covariates
 6962:    * - 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
 6963:    *     which is a new column after the 9 (ncovcol) variables. 
 6964:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 6965:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 6966:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 6967:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 6968:  */
 6969: {
 6970:   int i, j, k, ks;
 6971:   int  j1, k1, k2;
 6972:   char modelsav[80];
 6973:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 6974:   char *strpt;
 6975: 
 6976:   /*removespace(model);*/
 6977:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 6978:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 6979:     if (strstr(model,"AGE") !=0){
 6980:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 6981:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 6982:       return 1;
 6983:     }
 6984:     if (strstr(model,"v") !=0){
 6985:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 6986:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 6987:       return 1;
 6988:     }
 6989:     strcpy(modelsav,model); 
 6990:     if ((strpt=strstr(model,"age*age")) !=0){
 6991:       printf(" strpt=%s, model=%s\n",strpt, model);
 6992:       if(strpt != model){
 6993:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 6994:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 6995:  corresponding column of parameters.\n",model);
 6996:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 6997:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 6998:  corresponding column of parameters.\n",model); fflush(ficlog);
 6999:       return 1;
 7000:     }
 7001: 
 7002:       nagesqr=1;
 7003:       if (strstr(model,"+age*age") !=0)
 7004: 	substrchaine(modelsav, model, "+age*age");
 7005:       else if (strstr(model,"age*age+") !=0)
 7006: 	substrchaine(modelsav, model, "age*age+");
 7007:       else 
 7008: 	substrchaine(modelsav, model, "age*age");
 7009:     }else
 7010:       nagesqr=0;
 7011:     if (strlen(modelsav) >1){
 7012:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 7013:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 7014:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 7015:       cptcovt= j+1; /* Number of total covariates in the model, not including
 7016: 		   * cst, age and age*age 
 7017: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 7018:                   /* including age products which are counted in cptcovage.
 7019: 		  * but the covariates which are products must be treated 
 7020: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 7021:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 7022:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 7023: 
 7024:     
 7025:       /*   Design
 7026:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 7027:        *  <          ncovcol=8                >
 7028:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 7029:        *   k=  1    2      3       4     5       6      7        8
 7030:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 7031:        *  covar[k,i], value of kth covariate if not including age for individual i:
 7032:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 7033:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 7034:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 7035:        *  Tage[++cptcovage]=k
 7036:        *       if products, new covar are created after ncovcol with k1
 7037:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 7038:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 7039:        *  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
 7040:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 7041:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 7042:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 7043:        *  <          ncovcol=8                >
 7044:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 7045:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 7046:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 7047:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7048:        * p Tprod[1]@2={                         6, 5}
 7049:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 7050:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 7051:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 7052:        *How to reorganize?
 7053:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 7054:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7055:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 7056:        * Struct []
 7057:        */
 7058: 
 7059:       /* This loop fills the array Tvar from the string 'model'.*/
 7060:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 7061:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 7062:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 7063:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 7064:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 7065:       /* 	k=1 Tvar[1]=2 (from V2) */
 7066:       /* 	k=5 Tvar[5] */
 7067:       /* for (k=1; k<=cptcovn;k++) { */
 7068:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 7069:       /* 	} */
 7070:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 7071:       /*
 7072:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 7073:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 7074:         Tvar[k]=0;
 7075:       cptcovage=0;
 7076:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 7077: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 7078: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 7079: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 7080: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 7081: 	/*scanf("%d",i);*/
 7082: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 7083: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 7084: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 7085: 	    /* covar is not filled and then is empty */
 7086: 	    cptcovprod--;
 7087: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 7088: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 7089: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 7090: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 7091: 	    /*printf("stre=%s ", stre);*/
 7092: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 7093: 	    cptcovprod--;
 7094: 	    cutl(stre,strb,strc,'V');
 7095: 	    Tvar[k]=atoi(stre);
 7096: 	    cptcovage++;
 7097: 	    Tage[cptcovage]=k;
 7098: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 7099: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 7100: 	    cptcovn++;
 7101: 	    cptcovprodnoage++;k1++;
 7102: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 7103: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 7104: 				   because this model-covariate is a construction we invent a new column
 7105: 				   ncovcol + k1
 7106: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 7107: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 7108: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 7109: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 7110: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 7111: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 7112: 	    k2=k2+2;
 7113: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 7114: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 7115: 	    for (i=1; i<=lastobs;i++){
 7116: 	      /* Computes the new covariate which is a product of
 7117: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 7118: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 7119: 	    }
 7120: 	  } /* End age is not in the model */
 7121: 	} /* End if model includes a product */
 7122: 	else { /* no more sum */
 7123: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 7124: 	  /*  scanf("%d",i);*/
 7125: 	  cutl(strd,strc,strb,'V');
 7126: 	  ks++; /**< Number of simple covariates */
 7127: 	  cptcovn++;
 7128: 	  Tvar[k]=atoi(strd);
 7129: 	}
 7130: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 7131: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 7132: 	  scanf("%d",i);*/
 7133:       } /* end of loop + on total covariates */
 7134:     } /* end if strlen(modelsave == 0) age*age might exist */
 7135:   } /* end if strlen(model == 0) */
 7136:   
 7137:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 7138:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 7139: 
 7140:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 7141:   printf("cptcovprod=%d ", cptcovprod);
 7142:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 7143: 
 7144:   scanf("%d ",i);*/
 7145: 
 7146: 
 7147:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 7148:   /*endread:*/
 7149:     printf("Exiting decodemodel: ");
 7150:     return (1);
 7151: }
 7152: 
 7153: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 7154: {
 7155:   int i, m;
 7156: 
 7157:   for (i=1; i<=imx; i++) {
 7158:     for(m=2; (m<= maxwav); m++) {
 7159:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 7160: 	anint[m][i]=9999;
 7161: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 7162: 	  s[m][i]=-1;
 7163:       }
 7164:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 7165: 	*nberr = *nberr + 1;
 7166: 	printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 7167: 	fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 7168: 	s[m][i]=-1;
 7169:       }
 7170:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 7171: 	(*nberr)++;
 7172: 	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]); 
 7173: 	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]); 
 7174: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 7175:       }
 7176:     }
 7177:   }
 7178: 
 7179:   for (i=1; i<=imx; i++)  {
 7180:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 7181:     for(m=firstpass; (m<= lastpass); m++){
 7182:       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 */
 7183: 	if (s[m][i] >= nlstate+1) {
 7184: 	  if(agedc[i]>0){
 7185: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 7186: 	      agev[m][i]=agedc[i];
 7187: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 7188: 	    }else {
 7189: 	      if ((int)andc[i]!=9999){
 7190: 		nbwarn++;
 7191: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 7192: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 7193: 		agev[m][i]=-1;
 7194: 	      }
 7195: 	    }
 7196: 	  } /* agedc > 0 */
 7197: 	} /* end if */
 7198: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 7199: 				 years but with the precision of a month */
 7200: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 7201: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 7202: 	    agev[m][i]=1;
 7203: 	  else if(agev[m][i] < *agemin){ 
 7204: 	    *agemin=agev[m][i];
 7205: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 7206: 	  }
 7207: 	  else if(agev[m][i] >*agemax){
 7208: 	    *agemax=agev[m][i];
 7209: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 7210: 	  }
 7211: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 7212: 	  /*	 agev[m][i] = age[i]+2*m;*/
 7213: 	} /* en if 9*/
 7214: 	else { /* =9 */
 7215: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 7216: 	  agev[m][i]=1;
 7217: 	  s[m][i]=-1;
 7218: 	}
 7219:       }
 7220:       else if(s[m][i]==0) /*= 0 Unknown */
 7221: 	agev[m][i]=1;
 7222:       else{
 7223: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7224: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7225: 	agev[m][i]=0;
 7226:       }
 7227:     } /* End for lastpass */
 7228:   }
 7229:     
 7230:   for (i=1; i<=imx; i++)  {
 7231:     for(m=firstpass; (m<=lastpass); m++){
 7232:       if (s[m][i] > (nlstate+ndeath)) {
 7233: 	(*nberr)++;
 7234: 	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);	
 7235: 	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);	
 7236: 	return 1;
 7237:       }
 7238:     }
 7239:   }
 7240: 
 7241:   /*for (i=1; i<=imx; i++){
 7242:   for (m=firstpass; (m<lastpass); m++){
 7243:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 7244: }
 7245: 
 7246: }*/
 7247: 
 7248: 
 7249:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 7250:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 7251: 
 7252:   return (0);
 7253:  /* endread:*/
 7254:     printf("Exiting calandcheckages: ");
 7255:     return (1);
 7256: }
 7257: 
 7258: #if defined(_MSC_VER)
 7259: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7260: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7261: //#include "stdafx.h"
 7262: //#include <stdio.h>
 7263: //#include <tchar.h>
 7264: //#include <windows.h>
 7265: //#include <iostream>
 7266: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 7267: 
 7268: LPFN_ISWOW64PROCESS fnIsWow64Process;
 7269: 
 7270: BOOL IsWow64()
 7271: {
 7272: 	BOOL bIsWow64 = FALSE;
 7273: 
 7274: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 7275: 	//  (HANDLE, PBOOL);
 7276: 
 7277: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 7278: 
 7279: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 7280: 	const char funcName[] = "IsWow64Process";
 7281: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 7282: 		GetProcAddress(module, funcName);
 7283: 
 7284: 	if (NULL != fnIsWow64Process)
 7285: 	{
 7286: 		if (!fnIsWow64Process(GetCurrentProcess(),
 7287: 			&bIsWow64))
 7288: 			//throw std::exception("Unknown error");
 7289: 			printf("Unknown error\n");
 7290: 	}
 7291: 	return bIsWow64 != FALSE;
 7292: }
 7293: #endif
 7294: 
 7295: void syscompilerinfo(int logged)
 7296:  {
 7297:    /* #include "syscompilerinfo.h"*/
 7298:    /* command line Intel compiler 32bit windows, XP compatible:*/
 7299:    /* /GS /W3 /Gy
 7300:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 7301:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 7302:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 7303:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 7304:    */ 
 7305:    /* 64 bits */
 7306:    /*
 7307:      /GS /W3 /Gy
 7308:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 7309:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 7310:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 7311:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 7312:    /* Optimization are useless and O3 is slower than O2 */
 7313:    /*
 7314:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 7315:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 7316:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 7317:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 7318:    */
 7319:    /* Link is */ /* /OUT:"visual studio
 7320:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 7321:       /PDB:"visual studio
 7322:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 7323:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 7324:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 7325:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 7326:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 7327:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 7328:       uiAccess='false'"
 7329:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 7330:       /NOLOGO /TLBID:1
 7331:    */
 7332: #if defined __INTEL_COMPILER
 7333: #if defined(__GNUC__)
 7334: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 7335: #endif
 7336: #elif defined(__GNUC__) 
 7337: #ifndef  __APPLE__
 7338: #include <gnu/libc-version.h>  /* Only on gnu */
 7339: #endif
 7340:    struct utsname sysInfo;
 7341:    int cross = CROSS;
 7342:    if (cross){
 7343: 	   printf("Cross-");
 7344: 	   if(logged) fprintf(ficlog, "Cross-");
 7345:    }
 7346: #endif
 7347: 
 7348: #include <stdint.h>
 7349: 
 7350:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 7351: #if defined(__clang__)
 7352:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 7353: #endif
 7354: #if defined(__ICC) || defined(__INTEL_COMPILER)
 7355:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 7356: #endif
 7357: #if defined(__GNUC__) || defined(__GNUG__)
 7358:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 7359: #endif
 7360: #if defined(__HP_cc) || defined(__HP_aCC)
 7361:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 7362: #endif
 7363: #if defined(__IBMC__) || defined(__IBMCPP__)
 7364:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 7365: #endif
 7366: #if defined(_MSC_VER)
 7367:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 7368: #endif
 7369: #if defined(__PGI)
 7370:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 7371: #endif
 7372: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 7373:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 7374: #endif
 7375:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 7376:    
 7377: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 7378: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 7379:     // Windows (x64 and x86)
 7380:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 7381: #elif __unix__ // all unices, not all compilers
 7382:     // Unix
 7383:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 7384: #elif __linux__
 7385:     // linux
 7386:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 7387: #elif __APPLE__
 7388:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 7389:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 7390: #endif
 7391: 
 7392: /*  __MINGW32__	  */
 7393: /*  __CYGWIN__	 */
 7394: /* __MINGW64__  */
 7395: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 7396: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 7397: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 7398: /* _WIN64  // Defined for applications for Win64. */
 7399: /* _M_X64 // Defined for compilations that target x64 processors. */
 7400: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 7401: 
 7402: #if UINTPTR_MAX == 0xffffffff
 7403:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 7404: #elif UINTPTR_MAX == 0xffffffffffffffff
 7405:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 7406: #else
 7407:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 7408: #endif
 7409: 
 7410: #if defined(__GNUC__)
 7411: # if defined(__GNUC_PATCHLEVEL__)
 7412: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7413:                             + __GNUC_MINOR__ * 100 \
 7414:                             + __GNUC_PATCHLEVEL__)
 7415: # else
 7416: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7417:                             + __GNUC_MINOR__ * 100)
 7418: # endif
 7419:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 7420:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 7421: 
 7422:    if (uname(&sysInfo) != -1) {
 7423:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7424: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7425:    }
 7426:    else
 7427:       perror("uname() error");
 7428:    //#ifndef __INTEL_COMPILER 
 7429: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 7430:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 7431:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 7432: #endif
 7433: #endif
 7434: 
 7435:    //   void main()
 7436:    //   {
 7437: #if defined(_MSC_VER)
 7438:    if (IsWow64()){
 7439: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7440: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7441:    }
 7442:    else{
 7443: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7444: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7445:    }
 7446:    //	   printf("\nPress Enter to continue...");
 7447:    //	   getchar();
 7448:    //   }
 7449: 
 7450: #endif
 7451:    
 7452: 
 7453:  }
 7454: 
 7455:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 7456:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7457:   int i, j, k, i1 ;
 7458:   /* double ftolpl = 1.e-10; */
 7459:   double age, agebase, agelim;
 7460:   double tot;
 7461: 
 7462:   strcpy(filerespl,"PL_");
 7463:   strcat(filerespl,fileresu);
 7464:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 7465:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7466:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7467:   }
 7468:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7469:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7470:   pstamp(ficrespl);
 7471:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7472:   fprintf(ficrespl,"#Age ");
 7473:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 7474:   fprintf(ficrespl,"\n");
 7475:   
 7476:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7477: 
 7478:     agebase=ageminpar;
 7479:     agelim=agemaxpar;
 7480: 
 7481:     i1=pow(2,cptcoveff);
 7482:     if (cptcovn < 1){i1=1;}
 7483: 
 7484:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7485:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7486:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7487: 	k=k+1;
 7488: 	/* to clean */
 7489: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7490: 	fprintf(ficrespl,"#******");
 7491: 	printf("#******");
 7492: 	fprintf(ficlog,"#******");
 7493: 	for(j=1;j<=cptcoveff;j++) {
 7494: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7495: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7496: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7497: 	}
 7498: 	fprintf(ficrespl,"******\n");
 7499: 	printf("******\n");
 7500: 	fprintf(ficlog,"******\n");
 7501: 
 7502: 	fprintf(ficrespl,"#Age ");
 7503: 	for(j=1;j<=cptcoveff;j++) {
 7504: 	  fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7505: 	}
 7506: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 7507: 	fprintf(ficrespl,"Total Years_to_converge\n");
 7508: 	
 7509: 	for (age=agebase; age<=agelim; age++){
 7510: 	/* for (age=agebase; age<=agebase; age++){ */
 7511: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 7512: 	  fprintf(ficrespl,"%.0f ",age );
 7513: 	  for(j=1;j<=cptcoveff;j++)
 7514: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7515: 	  tot=0.;
 7516: 	  for(i=1; i<=nlstate;i++){
 7517: 	    tot +=  prlim[i][i];
 7518: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 7519: 	  }
 7520: 	  fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 7521: 	} /* Age */
 7522: 	/* was end of cptcod */
 7523:     } /* cptcov */
 7524: 	return 0;
 7525: }
 7526: 
 7527:  int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 7528:   /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 7529:   int i, j, k, i1 ;
 7530:   /* double ftolpl = 1.e-10; */
 7531:   double age, agebase, agelim;
 7532:   double tot;
 7533: 
 7534:   strcpy(fileresplb,"PLB_");
 7535:   strcat(fileresplb,fileresu);
 7536:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 7537:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7538:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7539:   }
 7540:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7541:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7542:   pstamp(ficresplb);
 7543:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7544:   fprintf(ficresplb,"#Age ");
 7545:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 7546:   fprintf(ficresplb,"\n");
 7547:   
 7548:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7549: 
 7550:     agebase=ageminpar;
 7551:     agelim=agemaxpar;
 7552: 
 7553:     i1=pow(2,cptcoveff);
 7554:     if (cptcovn < 1){i1=1;}
 7555: 
 7556:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7557:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7558:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7559: 	k=k+1;
 7560: 	/* to clean */
 7561: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7562: 	fprintf(ficresplb,"#******");
 7563: 	printf("#******");
 7564: 	fprintf(ficlog,"#******");
 7565: 	for(j=1;j<=cptcoveff;j++) {
 7566: 	  fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7567: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7568: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7569: 	}
 7570: 	fprintf(ficresplb,"******\n");
 7571: 	printf("******\n");
 7572: 	fprintf(ficlog,"******\n");
 7573: 
 7574: 	fprintf(ficresplb,"#Age ");
 7575: 	for(j=1;j<=cptcoveff;j++) {
 7576: 	  fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7577: 	}
 7578: 	for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 7579: 	fprintf(ficresplb,"Total Years_to_converge\n");
 7580: 	
 7581: 	for (age=agebase; age<=agelim; age++){
 7582: 	/* for (age=agebase; age<=agebase; age++){ */
 7583: 	  bprevalim(bprlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 7584: 	  fprintf(ficresplb,"%.0f ",age );
 7585: 	  for(j=1;j<=cptcoveff;j++)
 7586: 	    fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7587: 	  tot=0.;
 7588: 	  for(i=1; i<=nlstate;i++){
 7589: 	    tot +=  bprlim[i][i];
 7590: 	    fprintf(ficresplb," %.5f", bprlim[i][i]);
 7591: 	  }
 7592: 	  fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 7593: 	} /* Age */
 7594: 	/* was end of cptcod */
 7595:     } /* cptcov */
 7596: 	return 0;
 7597: }
 7598: 
 7599: int hPijx(double *p, int bage, int fage){
 7600:     /*------------- h Pij x at various ages ------------*/
 7601: 
 7602:   int stepsize;
 7603:   int agelim;
 7604:   int hstepm;
 7605:   int nhstepm;
 7606:   int h, i, i1, j, k;
 7607: 
 7608:   double agedeb;
 7609:   double ***p3mat;
 7610: 
 7611:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 7612:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 7613:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 7614:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 7615:     }
 7616:     printf("Computing pij: result on file '%s' \n", filerespij);
 7617:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 7618:   
 7619:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 7620:     /*if (stepm<=24) stepsize=2;*/
 7621: 
 7622:     agelim=AGESUP;
 7623:     hstepm=stepsize*YEARM; /* Every year of age */
 7624:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 7625: 
 7626:     /* hstepm=1;   aff par mois*/
 7627:     pstamp(ficrespij);
 7628:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 7629:     i1= pow(2,cptcoveff);
 7630:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7631:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 7632:    /*  	k=k+1;  */
 7633:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7634:       fprintf(ficrespij,"\n#****** ");
 7635:       for(j=1;j<=cptcoveff;j++) 
 7636: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7637:       fprintf(ficrespij,"******\n");
 7638:       
 7639:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 7640: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7641: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7642: 	
 7643: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 7644: 	
 7645: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7646: 	oldm=oldms;savm=savms;
 7647: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 7648: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 7649: 	for(i=1; i<=nlstate;i++)
 7650: 	  for(j=1; j<=nlstate+ndeath;j++)
 7651: 	    fprintf(ficrespij," %1d-%1d",i,j);
 7652: 	fprintf(ficrespij,"\n");
 7653: 	for (h=0; h<=nhstepm; h++){
 7654: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 7655: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 7656: 	  for(i=1; i<=nlstate;i++)
 7657: 	    for(j=1; j<=nlstate+ndeath;j++)
 7658: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 7659: 	  fprintf(ficrespij,"\n");
 7660: 	}
 7661: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7662: 	fprintf(ficrespij,"\n");
 7663:       }
 7664:       /*}*/
 7665:     }
 7666: 	return 0;
 7667: }
 7668: 
 7669:  int hBijx(double *p, int bage, int fage){
 7670:     /*------------- h Bij x at various ages ------------*/
 7671: 
 7672:   int stepsize;
 7673:   int agelim;
 7674:   int hstepm;
 7675:   int nhstepm;
 7676:   int h, i, i1, j, k;
 7677: 
 7678:   double agedeb;
 7679:   double ***p3mat;
 7680: 
 7681:     strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 7682:     if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 7683:       printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 7684:       fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 7685:     }
 7686:     printf("Computing pij back: result on file '%s' \n", filerespijb);
 7687:     fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 7688:   
 7689:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 7690:     /*if (stepm<=24) stepsize=2;*/
 7691: 
 7692:     agelim=AGESUP;
 7693:     hstepm=stepsize*YEARM; /* Every year of age */
 7694:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 7695: 
 7696:     /* hstepm=1;   aff par mois*/
 7697:     pstamp(ficrespijb);
 7698:     fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 7699:     i1= pow(2,cptcoveff);
 7700:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7701:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 7702:    /*  	k=k+1;  */
 7703:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7704:       fprintf(ficrespijb,"\n#****** ");
 7705:       for(j=1;j<=cptcoveff;j++) 
 7706: 	fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7707:       fprintf(ficrespijb,"******\n");
 7708:       
 7709:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 7710:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months */
 7711: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7712: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7713: 	
 7714: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 7715: 	
 7716: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7717: 	oldm=oldms;savm=savms;
 7718: 	hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 7719: 	fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 7720: 	for(i=1; i<=nlstate;i++)
 7721: 	  for(j=1; j<=nlstate+ndeath;j++)
 7722: 	    fprintf(ficrespijb," %1d-%1d",i,j);
 7723: 	fprintf(ficrespijb,"\n");
 7724: 	for (h=0; h<=nhstepm; h++){
 7725: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 7726: 	  fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 7727: 	  /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 7728: 	  for(i=1; i<=nlstate;i++)
 7729: 	    for(j=1; j<=nlstate+ndeath;j++)
 7730: 	      fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 7731: 	  fprintf(ficrespijb,"\n");
 7732: 	}
 7733: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7734: 	fprintf(ficrespijb,"\n");
 7735:       }
 7736:       /*}*/
 7737:     }
 7738: 	return 0;
 7739: }
 7740: 
 7741: 
 7742: /***********************************************/
 7743: /**************** Main Program *****************/
 7744: /***********************************************/
 7745: 
 7746: int main(int argc, char *argv[])
 7747: {
 7748: #ifdef GSL
 7749:   const gsl_multimin_fminimizer_type *T;
 7750:   size_t iteri = 0, it;
 7751:   int rval = GSL_CONTINUE;
 7752:   int status = GSL_SUCCESS;
 7753:   double ssval;
 7754: #endif
 7755:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 7756:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 7757:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 7758:   int jj, ll, li, lj, lk;
 7759:   int numlinepar=0; /* Current linenumber of parameter file */
 7760:   int num_filled;
 7761:   int itimes;
 7762:   int NDIM=2;
 7763:   int vpopbased=0;
 7764: 
 7765:   char ca[32], cb[32];
 7766:   /*  FILE *fichtm; *//* Html File */
 7767:   /* FILE *ficgp;*/ /*Gnuplot File */
 7768:   struct stat info;
 7769:   double agedeb=0.;
 7770: 
 7771:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 7772: 
 7773:   double fret;
 7774:   double dum=0.; /* Dummy variable */
 7775:   double ***p3mat;
 7776:   double ***mobaverage;
 7777: 
 7778:   char line[MAXLINE];
 7779:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 7780: 
 7781:   char model[MAXLINE], modeltemp[MAXLINE];
 7782:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 7783:   char *tok, *val; /* pathtot */
 7784:   int firstobs=1, lastobs=10;
 7785:   int c,  h , cpt, c2;
 7786:   int jl=0;
 7787:   int i1, j1, jk, stepsize=0;
 7788:   int count=0;
 7789: 
 7790:   int *tab; 
 7791:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 7792:   int backcast=0;
 7793:   int mobilav=0,popforecast=0;
 7794:   int hstepm=0, nhstepm=0;
 7795:   int agemortsup;
 7796:   float  sumlpop=0.;
 7797:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 7798:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 7799: 
 7800:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 7801:   double ftolpl=FTOL;
 7802:   double **prlim;
 7803:   double **bprlim;
 7804:   double ***param; /* Matrix of parameters */
 7805:   double  *p;
 7806:   double **matcov; /* Matrix of covariance */
 7807:   double **hess; /* Hessian matrix */
 7808:   double ***delti3; /* Scale */
 7809:   double *delti; /* Scale */
 7810:   double ***eij, ***vareij;
 7811:   double **varpl; /* Variances of prevalence limits by age */
 7812:   double *epj, vepp;
 7813: 
 7814:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 7815:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 7816: 
 7817:   double **ximort;
 7818:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 7819:   int *dcwave;
 7820: 
 7821:   char z[1]="c";
 7822: 
 7823:   /*char  *strt;*/
 7824:   char strtend[80];
 7825: 
 7826: 
 7827: /*   setlocale (LC_ALL, ""); */
 7828: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 7829: /*   textdomain (PACKAGE); */
 7830: /*   setlocale (LC_CTYPE, ""); */
 7831: /*   setlocale (LC_MESSAGES, ""); */
 7832: 
 7833:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 7834:   rstart_time = time(NULL);  
 7835:   /*  (void) gettimeofday(&start_time,&tzp);*/
 7836:   start_time = *localtime(&rstart_time);
 7837:   curr_time=start_time;
 7838:   /*tml = *localtime(&start_time.tm_sec);*/
 7839:   /* strcpy(strstart,asctime(&tml)); */
 7840:   strcpy(strstart,asctime(&start_time));
 7841: 
 7842: /*  printf("Localtime (at start)=%s",strstart); */
 7843: /*  tp.tm_sec = tp.tm_sec +86400; */
 7844: /*  tm = *localtime(&start_time.tm_sec); */
 7845: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 7846: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 7847: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 7848: /*   tp.tm_sec = mktime(&tmg); */
 7849: /*   strt=asctime(&tmg); */
 7850: /*   printf("Time(after) =%s",strstart);  */
 7851: /*  (void) time (&time_value);
 7852: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 7853: *  tm = *localtime(&time_value);
 7854: *  strstart=asctime(&tm);
 7855: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 7856: */
 7857: 
 7858:   nberr=0; /* Number of errors and warnings */
 7859:   nbwarn=0;
 7860: #ifdef WIN32
 7861:   _getcwd(pathcd, size);
 7862: #else
 7863:   getcwd(pathcd, size);
 7864: #endif
 7865:   syscompilerinfo(0);
 7866:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 7867:   if(argc <=1){
 7868:     printf("\nEnter the parameter file name: ");
 7869:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 7870:       printf("ERROR Empty parameter file name\n");
 7871:       goto end;
 7872:     }
 7873:     i=strlen(pathr);
 7874:     if(pathr[i-1]=='\n')
 7875:       pathr[i-1]='\0';
 7876:     i=strlen(pathr);
 7877:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 7878:       pathr[i-1]='\0';
 7879:     }
 7880:     i=strlen(pathr);
 7881:     if( i==0 ){
 7882:       printf("ERROR Empty parameter file name\n");
 7883:       goto end;
 7884:     }
 7885:     for (tok = pathr; tok != NULL; ){
 7886:       printf("Pathr |%s|\n",pathr);
 7887:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 7888:       printf("val= |%s| pathr=%s\n",val,pathr);
 7889:       strcpy (pathtot, val);
 7890:       if(pathr[0] == '\0') break; /* Dirty */
 7891:     }
 7892:   }
 7893:   else{
 7894:     strcpy(pathtot,argv[1]);
 7895:   }
 7896:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 7897:   /*cygwin_split_path(pathtot,path,optionfile);
 7898:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 7899:   /* cutv(path,optionfile,pathtot,'\\');*/
 7900: 
 7901:   /* Split argv[0], imach program to get pathimach */
 7902:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 7903:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 7904:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 7905:  /*   strcpy(pathimach,argv[0]); */
 7906:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 7907:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 7908:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 7909: #ifdef WIN32
 7910:   _chdir(path); /* Can be a relative path */
 7911:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 7912: #else
 7913:   chdir(path); /* Can be a relative path */
 7914:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 7915: #endif
 7916:   printf("Current directory %s!\n",pathcd);
 7917:   strcpy(command,"mkdir ");
 7918:   strcat(command,optionfilefiname);
 7919:   if((outcmd=system(command)) != 0){
 7920:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 7921:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 7922:     /* fclose(ficlog); */
 7923: /*     exit(1); */
 7924:   }
 7925: /*   if((imk=mkdir(optionfilefiname))<0){ */
 7926: /*     perror("mkdir"); */
 7927: /*   } */
 7928: 
 7929:   /*-------- arguments in the command line --------*/
 7930: 
 7931:   /* Main Log file */
 7932:   strcat(filelog, optionfilefiname);
 7933:   strcat(filelog,".log");    /* */
 7934:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 7935:     printf("Problem with logfile %s\n",filelog);
 7936:     goto end;
 7937:   }
 7938:   fprintf(ficlog,"Log filename:%s\n",filelog);
 7939:   fprintf(ficlog,"Version %s %s",version,fullversion);
 7940:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 7941:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 7942:  path=%s \n\
 7943:  optionfile=%s\n\
 7944:  optionfilext=%s\n\
 7945:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 7946: 
 7947:   syscompilerinfo(1);
 7948: 
 7949:   printf("Local time (at start):%s",strstart);
 7950:   fprintf(ficlog,"Local time (at start): %s",strstart);
 7951:   fflush(ficlog);
 7952: /*   (void) gettimeofday(&curr_time,&tzp); */
 7953: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 7954: 
 7955:   /* */
 7956:   strcpy(fileres,"r");
 7957:   strcat(fileres, optionfilefiname);
 7958:   strcat(fileresu, optionfilefiname); /* Without r in front */
 7959:   strcat(fileres,".txt");    /* Other files have txt extension */
 7960:   strcat(fileresu,".txt");    /* Other files have txt extension */
 7961: 
 7962:   /* Main ---------arguments file --------*/
 7963: 
 7964:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 7965:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 7966:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 7967:     fflush(ficlog);
 7968:     /* goto end; */
 7969:     exit(70); 
 7970:   }
 7971: 
 7972: 
 7973: 
 7974:   strcpy(filereso,"o");
 7975:   strcat(filereso,fileresu);
 7976:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 7977:     printf("Problem with Output resultfile: %s\n", filereso);
 7978:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 7979:     fflush(ficlog);
 7980:     goto end;
 7981:   }
 7982: 
 7983:   /* Reads comments: lines beginning with '#' */
 7984:   numlinepar=0;
 7985: 
 7986:     /* First parameter line */
 7987:   while(fgets(line, MAXLINE, ficpar)) {
 7988:     /* If line starts with a # it is a comment */
 7989:     if (line[0] == '#') {
 7990:       numlinepar++;
 7991:       fputs(line,stdout);
 7992:       fputs(line,ficparo);
 7993:       fputs(line,ficlog);
 7994:       continue;
 7995:     }else
 7996:       break;
 7997:   }
 7998:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 7999: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 8000:     if (num_filled != 5) {
 8001:       printf("Should be 5 parameters\n");
 8002:     }
 8003:     numlinepar++;
 8004:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 8005:   }
 8006:   /* Second parameter line */
 8007:   while(fgets(line, MAXLINE, ficpar)) {
 8008:     /* If line starts with a # it is a comment */
 8009:     if (line[0] == '#') {
 8010:       numlinepar++;
 8011:       fputs(line,stdout);
 8012:       fputs(line,ficparo);
 8013:       fputs(line,ficlog);
 8014:       continue;
 8015:     }else
 8016:       break;
 8017:   }
 8018:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
 8019: 			&ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 8020:     if (num_filled != 8) {
 8021:       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");
 8022:       printf("but line=%s\n",line);
 8023:     }
 8024:     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);
 8025:   }
 8026:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 8027:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 8028:   /* Third parameter line */
 8029:   while(fgets(line, MAXLINE, ficpar)) {
 8030:     /* If line starts with a # it is a comment */
 8031:     if (line[0] == '#') {
 8032:       numlinepar++;
 8033:       fputs(line,stdout);
 8034:       fputs(line,ficparo);
 8035:       fputs(line,ficlog);
 8036:       continue;
 8037:     }else
 8038:       break;
 8039:   }
 8040:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 8041:     if (num_filled == 0)
 8042:             model[0]='\0';
 8043:     else if (num_filled != 1){
 8044:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8045:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8046:       model[0]='\0';
 8047:       goto end;
 8048:     }
 8049:     else{
 8050:       if (model[0]=='+'){
 8051: 	for(i=1; i<=strlen(model);i++)
 8052: 	  modeltemp[i-1]=model[i];
 8053: 	strcpy(model,modeltemp); 
 8054:       }
 8055:     }
 8056:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 8057:     printf("model=1+age+%s\n",model);fflush(stdout);
 8058:   }
 8059:   /* 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); */
 8060:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 8061:   /* 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); */
 8062:   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);
 8063:   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);
 8064:   fflush(ficlog);
 8065:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 8066:   if(model[0]=='#'){
 8067:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 8068:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 8069:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 8070:     if(mle != -1){
 8071:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 8072:       exit(1);
 8073:     }
 8074:   }
 8075:   while((c=getc(ficpar))=='#' && c!= EOF){
 8076:     ungetc(c,ficpar);
 8077:     fgets(line, MAXLINE, ficpar);
 8078:     numlinepar++;
 8079:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 8080:       z[0]=line[1];
 8081:     }
 8082:     /* printf("****line [1] = %c \n",line[1]); */
 8083:     fputs(line, stdout);
 8084:     //puts(line);
 8085:     fputs(line,ficparo);
 8086:     fputs(line,ficlog);
 8087:   }
 8088:   ungetc(c,ficpar);
 8089: 
 8090:    
 8091:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 8092:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 8093:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 8094:      v1+v2*age+v2*v3 makes cptcovn = 3
 8095:   */
 8096:   if (strlen(model)>1) 
 8097:     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*/
 8098:   else
 8099:     ncovmodel=2; /* Constant and age */
 8100:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 8101:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 8102:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 8103:     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);
 8104:     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);
 8105:     fflush(stdout);
 8106:     fclose (ficlog);
 8107:     goto end;
 8108:   }
 8109:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8110:   delti=delti3[1][1];
 8111:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 8112:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 8113:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8114:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8115:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8116:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 8117:     fclose (ficparo);
 8118:     fclose (ficlog);
 8119:     goto end;
 8120:     exit(0);
 8121:   }
 8122:   else if(mle==-3) { /* Main Wizard */
 8123:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8124:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8125:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8126:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8127:     matcov=matrix(1,npar,1,npar);
 8128:     hess=matrix(1,npar,1,npar);
 8129:   }
 8130:   else{
 8131:     /* Read guessed parameters */
 8132:     /* Reads comments: lines beginning with '#' */
 8133:     while((c=getc(ficpar))=='#' && c!= EOF){
 8134:       ungetc(c,ficpar);
 8135:       fgets(line, MAXLINE, ficpar);
 8136:       numlinepar++;
 8137:       fputs(line,stdout);
 8138:       fputs(line,ficparo);
 8139:       fputs(line,ficlog);
 8140:     }
 8141:     ungetc(c,ficpar);
 8142:     
 8143:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8144:     for(i=1; i <=nlstate; i++){
 8145:       j=0;
 8146:       for(jj=1; jj <=nlstate+ndeath; jj++){
 8147: 	if(jj==i) continue;
 8148: 	j++;
 8149: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 8150: 	if ((i1 != i) || (j1 != jj)){
 8151: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 8152: It might be a problem of design; if ncovcol and the model are correct\n \
 8153: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 8154: 	  exit(1);
 8155: 	}
 8156: 	fprintf(ficparo,"%1d%1d",i1,j1);
 8157: 	if(mle==1)
 8158: 	  printf("%1d%1d",i,jj);
 8159: 	fprintf(ficlog,"%1d%1d",i,jj);
 8160: 	for(k=1; k<=ncovmodel;k++){
 8161: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 8162: 	  if(mle==1){
 8163: 	    printf(" %lf",param[i][j][k]);
 8164: 	    fprintf(ficlog," %lf",param[i][j][k]);
 8165: 	  }
 8166: 	  else
 8167: 	    fprintf(ficlog," %lf",param[i][j][k]);
 8168: 	  fprintf(ficparo," %lf",param[i][j][k]);
 8169: 	}
 8170: 	fscanf(ficpar,"\n");
 8171: 	numlinepar++;
 8172: 	if(mle==1)
 8173: 	  printf("\n");
 8174: 	fprintf(ficlog,"\n");
 8175: 	fprintf(ficparo,"\n");
 8176:       }
 8177:     }  
 8178:     fflush(ficlog);
 8179: 
 8180:     /* Reads scales values */
 8181:     p=param[1][1];
 8182:     
 8183:     /* Reads comments: lines beginning with '#' */
 8184:     while((c=getc(ficpar))=='#' && c!= EOF){
 8185:       ungetc(c,ficpar);
 8186:       fgets(line, MAXLINE, ficpar);
 8187:       numlinepar++;
 8188:       fputs(line,stdout);
 8189:       fputs(line,ficparo);
 8190:       fputs(line,ficlog);
 8191:     }
 8192:     ungetc(c,ficpar);
 8193: 
 8194:     for(i=1; i <=nlstate; i++){
 8195:       for(j=1; j <=nlstate+ndeath-1; j++){
 8196: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 8197: 	if ( (i1-i) * (j1-j) != 0){
 8198: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 8199: 	  exit(1);
 8200: 	}
 8201: 	printf("%1d%1d",i,j);
 8202: 	fprintf(ficparo,"%1d%1d",i1,j1);
 8203: 	fprintf(ficlog,"%1d%1d",i1,j1);
 8204: 	for(k=1; k<=ncovmodel;k++){
 8205: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 8206: 	  printf(" %le",delti3[i][j][k]);
 8207: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 8208: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 8209: 	}
 8210: 	fscanf(ficpar,"\n");
 8211: 	numlinepar++;
 8212: 	printf("\n");
 8213: 	fprintf(ficparo,"\n");
 8214: 	fprintf(ficlog,"\n");
 8215:       }
 8216:     }
 8217:     fflush(ficlog);
 8218: 
 8219:     /* Reads covariance matrix */
 8220:     delti=delti3[1][1];
 8221: 
 8222: 
 8223:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 8224:   
 8225:     /* Reads comments: lines beginning with '#' */
 8226:     while((c=getc(ficpar))=='#' && c!= EOF){
 8227:       ungetc(c,ficpar);
 8228:       fgets(line, MAXLINE, ficpar);
 8229:       numlinepar++;
 8230:       fputs(line,stdout);
 8231:       fputs(line,ficparo);
 8232:       fputs(line,ficlog);
 8233:     }
 8234:     ungetc(c,ficpar);
 8235:   
 8236:     matcov=matrix(1,npar,1,npar);
 8237:     hess=matrix(1,npar,1,npar);
 8238:     for(i=1; i <=npar; i++)
 8239:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 8240:       
 8241:     /* Scans npar lines */
 8242:     for(i=1; i <=npar; i++){
 8243:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
 8244:       if(count != 3){
 8245: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8246: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8247: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8248: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8249: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8250: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8251: 	exit(1);
 8252:       }else
 8253:       if(mle==1)
 8254: 	printf("%1d%1d%1d",i1,j1,jk);
 8255:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
 8256:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
 8257:       for(j=1; j <=i; j++){
 8258: 	fscanf(ficpar," %le",&matcov[i][j]);
 8259: 	if(mle==1){
 8260: 	  printf(" %.5le",matcov[i][j]);
 8261: 	}
 8262: 	fprintf(ficlog," %.5le",matcov[i][j]);
 8263: 	fprintf(ficparo," %.5le",matcov[i][j]);
 8264:       }
 8265:       fscanf(ficpar,"\n");
 8266:       numlinepar++;
 8267:       if(mle==1)
 8268: 	printf("\n");
 8269:       fprintf(ficlog,"\n");
 8270:       fprintf(ficparo,"\n");
 8271:     }
 8272:     /* End of read covariance matrix npar lines */
 8273:     for(i=1; i <=npar; i++)
 8274:       for(j=i+1;j<=npar;j++)
 8275: 	matcov[i][j]=matcov[j][i];
 8276:     
 8277:     if(mle==1)
 8278:       printf("\n");
 8279:     fprintf(ficlog,"\n");
 8280:     
 8281:     fflush(ficlog);
 8282:     
 8283:     /*-------- Rewriting parameter file ----------*/
 8284:     strcpy(rfileres,"r");    /* "Rparameterfile */
 8285:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 8286:     strcat(rfileres,".");    /* */
 8287:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 8288:     if((ficres =fopen(rfileres,"w"))==NULL) {
 8289:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 8290:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 8291:     }
 8292:     fprintf(ficres,"#%s\n",version);
 8293:   }    /* End of mle != -3 */
 8294: 
 8295:   /*  Main data
 8296:    */
 8297:   n= lastobs;
 8298:   num=lvector(1,n);
 8299:   moisnais=vector(1,n);
 8300:   annais=vector(1,n);
 8301:   moisdc=vector(1,n);
 8302:   andc=vector(1,n);
 8303:   agedc=vector(1,n);
 8304:   cod=ivector(1,n);
 8305:   weight=vector(1,n);
 8306:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 8307:   mint=matrix(1,maxwav,1,n);
 8308:   anint=matrix(1,maxwav,1,n);
 8309:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 8310:   tab=ivector(1,NCOVMAX);
 8311:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8312:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8313: 
 8314:   /* Reads data from file datafile */
 8315:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 8316:     goto end;
 8317: 
 8318:   /* Calculation of the number of parameters from char model */
 8319:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 8320: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 8321: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 8322: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 8323: 	k=1 Tvar[1]=2 (from V2)
 8324:     */
 8325:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 8326:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 8327:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 8328:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 8329:   */
 8330:   /* For model-covariate k tells which data-covariate to use but
 8331:     because this model-covariate is a construction we invent a new column
 8332:     ncovcol + k1
 8333:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 8334:     Tvar[3=V1*V4]=4+1 etc */
 8335:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 8336:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 8337:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 8338:   */
 8339:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 8340:   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
 8341: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 8342: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 8343:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 8344: 			 4 covariates (3 plus signs)
 8345: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 8346: 		      */  
 8347: 
 8348: /* Main decodemodel */
 8349: 
 8350: 
 8351:   if(decodemodel(model, lastobs) == 1)
 8352:     goto end;
 8353: 
 8354:   if((double)(lastobs-imx)/(double)imx > 1.10){
 8355:     nbwarn++;
 8356:     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); 
 8357:     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); 
 8358:   }
 8359:     /*  if(mle==1){*/
 8360:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 8361:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 8362:   }
 8363: 
 8364:     /*-calculation of age at interview from date of interview and age at death -*/
 8365:   agev=matrix(1,maxwav,1,imx);
 8366: 
 8367:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 8368:     goto end;
 8369: 
 8370: 
 8371:   agegomp=(int)agemin;
 8372:   free_vector(moisnais,1,n);
 8373:   free_vector(annais,1,n);
 8374:   /* free_matrix(mint,1,maxwav,1,n);
 8375:      free_matrix(anint,1,maxwav,1,n);*/
 8376:   /* free_vector(moisdc,1,n); */
 8377:   /* free_vector(andc,1,n); */
 8378:   /* */
 8379:   
 8380:   wav=ivector(1,imx);
 8381:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8382:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8383:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
 8384:   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.*/
 8385:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
 8386:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
 8387:    
 8388:   /* Concatenates waves */
 8389:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 8390:      Death is a valid wave (if date is known).
 8391:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
 8392:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 8393:      and mw[mi+1][i]. dh depends on stepm.
 8394:   */
 8395: 
 8396:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 8397:   /* */
 8398:  
 8399:   free_vector(moisdc,1,n);
 8400:   free_vector(andc,1,n);
 8401: 
 8402:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 8403: 
 8404:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 8405:   ncodemax[1]=1;
 8406:   Ndum =ivector(-1,NCOVMAX);  
 8407:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 8408:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 8409:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 8410:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 8411:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 8412: 
 8413:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 8414:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 8415:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 8416:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 8417:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 8418:    * (currently 0 or 1) in the data.
 8419:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 8420:    * corresponding modality (h,j).
 8421:    */
 8422: 
 8423:   h=0;
 8424: 
 8425: 
 8426:   /*if (cptcovn > 0) */
 8427:       
 8428:  
 8429:   m=pow(2,cptcoveff);
 8430:  
 8431: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 8432: 	   * For k=4 covariates, h goes from 1 to m=2**k
 8433: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 8434:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8435: 	   *     h\k   1     2     3     4
 8436: 	   *______________________________  
 8437: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 8438: 	   *     2     2     1     1     1
 8439: 	   *     3 i=2 1     2     1     1
 8440: 	   *     4     2     2     1     1
 8441: 	   *     5 i=3 1 i=2 1     2     1
 8442: 	   *     6     2     1     2     1
 8443: 	   *     7 i=4 1     2     2     1
 8444: 	   *     8     2     2     2     1
 8445: 	   *     9 i=5 1 i=3 1 i=2 1     2
 8446: 	   *    10     2     1     1     2
 8447: 	   *    11 i=6 1     2     1     2
 8448: 	   *    12     2     2     1     2
 8449: 	   *    13 i=7 1 i=4 1     2     2    
 8450: 	   *    14     2     1     2     2
 8451: 	   *    15 i=8 1     2     2     2
 8452: 	   *    16     2     2     2     2
 8453: 	   */
 8454:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 8455:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 8456:      * and the value of each covariate?
 8457:      * V1=1, V2=1, V3=2, V4=1 ?
 8458:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 8459:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 8460:      * In order to get the real value in the data, we use nbcode
 8461:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 8462:      * We are keeping this crazy system in order to be able (in the future?) 
 8463:      * to have more than 2 values (0 or 1) for a covariate.
 8464:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8465:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 8466:      *              bbbbbbbb
 8467:      *              76543210     
 8468:      *   h-1        00000101 (6-1=5)
 8469:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
 8470:      *           &
 8471:      *     1        00000001 (1)
 8472:      *              00000001        = 1 & ((h-1) >> (k-1))
 8473:      *          +1= 00000010 =2 
 8474:      *
 8475:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 8476:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 8477:      *    >>k'            11
 8478:      *          &   00000001
 8479:      *            = 00000001
 8480:      *      +1    = 00000010=2    =  codtabm(14,3)   
 8481:      * Reverse h=6 and m=16?
 8482:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 8483:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 8484:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 8485:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 8486:      * V3=decodtabm(14,3,2**4)=2
 8487:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 8488:      *(h-1) >> (j-1)    0011 =13 >> 2
 8489:      *          &1 000000001
 8490:      *           = 000000001
 8491:      *         +1= 000000010 =2
 8492:      *                  2211
 8493:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 8494:      *                  V3=2
 8495:      */
 8496: 
 8497:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
 8498:   /*   /\* printf("h=%2d ", h); *\/ */
 8499:   /*    /\* for(k=1; k <=10; k++){ *\/ */
 8500:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
 8501:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
 8502:   /*    /\* } *\/ */
 8503:   /*    /\* printf("\n"); *\/ */
 8504:   /* } */
 8505:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
 8506:   /*   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 *\/  */
 8507:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
 8508:   /* 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
 8509:   /* 	  h++; */
 8510:   /* 	  if (h>m)  */
 8511:   /* 	    h=1; */
 8512:   /* 	  codtab[h][k]=j; */
 8513:   /* 	  /\* codtab[12][3]=1; *\/ */
 8514:   /* 	  /\*codtab[h][Tvar[k]]=j;*\/ */
 8515:   /* 	  /\* 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]]); *\/ */
 8516:   /* 	}  */
 8517:   /*     } */
 8518:   /*   } */
 8519:   /* }  */
 8520:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 8521:      codtab[1][2]=1;codtab[2][2]=2; */
 8522:   /* for(i=1; i <=m ;i++){  */
 8523:   /*    for(k=1; k <=cptcovn; k++){ */
 8524:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
 8525:   /*    } */
 8526:   /*    printf("\n"); */
 8527:   /* } */
 8528:   /*   scanf("%d",i);*/
 8529: 
 8530:  free_ivector(Ndum,-1,NCOVMAX);
 8531: 
 8532: 
 8533:     
 8534:   /* Initialisation of ----------- gnuplot -------------*/
 8535:   strcpy(optionfilegnuplot,optionfilefiname);
 8536:   if(mle==-3)
 8537:     strcat(optionfilegnuplot,"-MORT_");
 8538:   strcat(optionfilegnuplot,".gp");
 8539: 
 8540:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 8541:     printf("Problem with file %s",optionfilegnuplot);
 8542:   }
 8543:   else{
 8544:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 8545:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 8546:     //fprintf(ficgp,"set missing 'NaNq'\n");
 8547:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 8548:   }
 8549:   /*  fclose(ficgp);*/
 8550: 
 8551: 
 8552:   /* Initialisation of --------- index.htm --------*/
 8553: 
 8554:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 8555:   if(mle==-3)
 8556:     strcat(optionfilehtm,"-MORT_");
 8557:   strcat(optionfilehtm,".htm");
 8558:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 8559:     printf("Problem with %s \n",optionfilehtm);
 8560:     exit(0);
 8561:   }
 8562: 
 8563:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 8564:   strcat(optionfilehtmcov,"-cov.htm");
 8565:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 8566:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 8567:   }
 8568:   else{
 8569:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 8570: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8571: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 8572: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 8573:   }
 8574: 
 8575:   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>  \
 8576: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8577: <font size=\"2\">IMaCh-%s <br> %s</font> \
 8578: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8579: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 8580: \n\
 8581: <hr  size=\"2\" color=\"#EC5E5E\">\
 8582:  <ul><li><h4>Parameter files</h4>\n\
 8583:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 8584:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 8585:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 8586:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 8587:  - Date and time at start: %s</ul>\n",\
 8588: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 8589: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 8590: 	  fileres,fileres,\
 8591: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 8592:   fflush(fichtm);
 8593: 
 8594:   strcpy(pathr,path);
 8595:   strcat(pathr,optionfilefiname);
 8596: #ifdef WIN32
 8597:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 8598: #else
 8599:   chdir(optionfilefiname); /* Move to directory named optionfile */
 8600: #endif
 8601: 	  
 8602:   
 8603:   /* Calculates basic frequencies. Computes observed prevalence at single age
 8604:      and prints on file fileres'p'. */
 8605:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
 8606: 	      firstpass, lastpass,  stepm,  weightopt, model);
 8607: 
 8608:   fprintf(fichtm,"\n");
 8609:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 8610: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 8611: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 8612: 	  imx,agemin,agemax,jmin,jmax,jmean);
 8613:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8614:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8615:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8616:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 8617:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 8618:     
 8619:    
 8620:   /* For Powell, parameters are in a vector p[] starting at p[1]
 8621:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 8622:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 8623: 
 8624:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 8625:   /* For mortality only */
 8626:   if (mle==-3){
 8627:     ximort=matrix(1,NDIM,1,NDIM); 
 8628:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 8629:     cens=ivector(1,n);
 8630:     ageexmed=vector(1,n);
 8631:     agecens=vector(1,n);
 8632:     dcwave=ivector(1,n);
 8633:  
 8634:     for (i=1; i<=imx; i++){
 8635:       dcwave[i]=-1;
 8636:       for (m=firstpass; m<=lastpass; m++)
 8637: 	if (s[m][i]>nlstate) {
 8638: 	  dcwave[i]=m;
 8639: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 8640: 	  break;
 8641: 	}
 8642:     }
 8643: 
 8644:     for (i=1; i<=imx; i++) {
 8645:       if (wav[i]>0){
 8646: 	ageexmed[i]=agev[mw[1][i]][i];
 8647: 	j=wav[i];
 8648: 	agecens[i]=1.; 
 8649: 
 8650: 	if (ageexmed[i]> 1 && wav[i] > 0){
 8651: 	  agecens[i]=agev[mw[j][i]][i];
 8652: 	  cens[i]= 1;
 8653: 	}else if (ageexmed[i]< 1) 
 8654: 	  cens[i]= -1;
 8655: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 8656: 	  cens[i]=0 ;
 8657:       }
 8658:       else cens[i]=-1;
 8659:     }
 8660:     
 8661:     for (i=1;i<=NDIM;i++) {
 8662:       for (j=1;j<=NDIM;j++)
 8663: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 8664:     }
 8665:     
 8666:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 8667:     /*printf("%lf %lf", p[1], p[2]);*/
 8668:     
 8669:     
 8670: #ifdef GSL
 8671:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 8672: #else
 8673:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 8674: #endif
 8675:     strcpy(filerespow,"POW-MORT_"); 
 8676:     strcat(filerespow,fileresu);
 8677:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 8678:       printf("Problem with resultfile: %s\n", filerespow);
 8679:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 8680:     }
 8681: #ifdef GSL
 8682:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 8683: #else
 8684:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 8685: #endif
 8686:     /*  for (i=1;i<=nlstate;i++)
 8687: 	for(j=1;j<=nlstate+ndeath;j++)
 8688: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 8689:     */
 8690:     fprintf(ficrespow,"\n");
 8691: #ifdef GSL
 8692:     /* gsl starts here */ 
 8693:     T = gsl_multimin_fminimizer_nmsimplex;
 8694:     gsl_multimin_fminimizer *sfm = NULL;
 8695:     gsl_vector *ss, *x;
 8696:     gsl_multimin_function minex_func;
 8697: 
 8698:     /* Initial vertex size vector */
 8699:     ss = gsl_vector_alloc (NDIM);
 8700:     
 8701:     if (ss == NULL){
 8702:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 8703:     }
 8704:     /* Set all step sizes to 1 */
 8705:     gsl_vector_set_all (ss, 0.001);
 8706: 
 8707:     /* Starting point */
 8708:     
 8709:     x = gsl_vector_alloc (NDIM);
 8710:     
 8711:     if (x == NULL){
 8712:       gsl_vector_free(ss);
 8713:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 8714:     }
 8715:   
 8716:     /* Initialize method and iterate */
 8717:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 8718:     /*     gsl_vector_set(x, 0, 0.0268); */
 8719:     /*     gsl_vector_set(x, 1, 0.083); */
 8720:     gsl_vector_set(x, 0, p[1]);
 8721:     gsl_vector_set(x, 1, p[2]);
 8722: 
 8723:     minex_func.f = &gompertz_f;
 8724:     minex_func.n = NDIM;
 8725:     minex_func.params = (void *)&p; /* ??? */
 8726:     
 8727:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 8728:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 8729:     
 8730:     printf("Iterations beginning .....\n\n");
 8731:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 8732: 
 8733:     iteri=0;
 8734:     while (rval == GSL_CONTINUE){
 8735:       iteri++;
 8736:       status = gsl_multimin_fminimizer_iterate(sfm);
 8737:       
 8738:       if (status) printf("error: %s\n", gsl_strerror (status));
 8739:       fflush(0);
 8740:       
 8741:       if (status) 
 8742:         break;
 8743:       
 8744:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 8745:       ssval = gsl_multimin_fminimizer_size (sfm);
 8746:       
 8747:       if (rval == GSL_SUCCESS)
 8748:         printf ("converged to a local maximum at\n");
 8749:       
 8750:       printf("%5d ", iteri);
 8751:       for (it = 0; it < NDIM; it++){
 8752: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 8753:       }
 8754:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 8755:     }
 8756:     
 8757:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 8758:     
 8759:     gsl_vector_free(x); /* initial values */
 8760:     gsl_vector_free(ss); /* inital step size */
 8761:     for (it=0; it<NDIM; it++){
 8762:       p[it+1]=gsl_vector_get(sfm->x,it);
 8763:       fprintf(ficrespow," %.12lf", p[it]);
 8764:     }
 8765:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 8766: #endif
 8767: #ifdef POWELL
 8768:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 8769: #endif  
 8770:     fclose(ficrespow);
 8771:     
 8772:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
 8773: 
 8774:     for(i=1; i <=NDIM; i++)
 8775:       for(j=i+1;j<=NDIM;j++)
 8776: 	matcov[i][j]=matcov[j][i];
 8777:     
 8778:     printf("\nCovariance matrix\n ");
 8779:     fprintf(ficlog,"\nCovariance matrix\n ");
 8780:     for(i=1; i <=NDIM; i++) {
 8781:       for(j=1;j<=NDIM;j++){ 
 8782: 	printf("%f ",matcov[i][j]);
 8783: 	fprintf(ficlog,"%f ",matcov[i][j]);
 8784:       }
 8785:       printf("\n ");  fprintf(ficlog,"\n ");
 8786:     }
 8787:     
 8788:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 8789:     for (i=1;i<=NDIM;i++) {
 8790:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 8791:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 8792:     }
 8793:     lsurv=vector(1,AGESUP);
 8794:     lpop=vector(1,AGESUP);
 8795:     tpop=vector(1,AGESUP);
 8796:     lsurv[agegomp]=100000;
 8797:     
 8798:     for (k=agegomp;k<=AGESUP;k++) {
 8799:       agemortsup=k;
 8800:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 8801:     }
 8802:     
 8803:     for (k=agegomp;k<agemortsup;k++)
 8804:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 8805:     
 8806:     for (k=agegomp;k<agemortsup;k++){
 8807:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 8808:       sumlpop=sumlpop+lpop[k];
 8809:     }
 8810:     
 8811:     tpop[agegomp]=sumlpop;
 8812:     for (k=agegomp;k<(agemortsup-3);k++){
 8813:       /*  tpop[k+1]=2;*/
 8814:       tpop[k+1]=tpop[k]-lpop[k];
 8815:     }
 8816:     
 8817:     
 8818:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 8819:     for (k=agegomp;k<(agemortsup-2);k++) 
 8820:       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]);
 8821:     
 8822:     
 8823:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 8824:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
 8825:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 8826: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 8827: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 8828:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 8829: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 8830: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 8831:     }else
 8832:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 8833:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
 8834: 		     stepm, weightopt,\
 8835: 		     model,imx,p,matcov,agemortsup);
 8836:     
 8837:     free_vector(lsurv,1,AGESUP);
 8838:     free_vector(lpop,1,AGESUP);
 8839:     free_vector(tpop,1,AGESUP);
 8840: #ifdef GSL
 8841:     free_ivector(cens,1,n);
 8842:     free_vector(agecens,1,n);
 8843:     free_ivector(dcwave,1,n);
 8844:     free_matrix(ximort,1,NDIM,1,NDIM);
 8845: #endif
 8846:   } /* Endof if mle==-3 mortality only */
 8847:   /* Standard  */
 8848:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
 8849:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 8850:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 8851:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 8852:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 8853:     for (k=1; k<=npar;k++)
 8854:       printf(" %d %8.5f",k,p[k]);
 8855:     printf("\n");
 8856:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
 8857:       /* mlikeli uses func not funcone */
 8858:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 8859:     }
 8860:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
 8861:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 8862:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 8863:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 8864:     }
 8865:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
 8866:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 8867:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 8868:     for (k=1; k<=npar;k++)
 8869:       printf(" %d %8.5f",k,p[k]);
 8870:     printf("\n");
 8871:     
 8872:     /*--------- results files --------------*/
 8873:     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);
 8874:     
 8875:     
 8876:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8877:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8878:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8879:     for(i=1,jk=1; i <=nlstate; i++){
 8880:       for(k=1; k <=(nlstate+ndeath); k++){
 8881: 	if (k != i) {
 8882: 	  printf("%d%d ",i,k);
 8883: 	  fprintf(ficlog,"%d%d ",i,k);
 8884: 	  fprintf(ficres,"%1d%1d ",i,k);
 8885: 	  for(j=1; j <=ncovmodel; j++){
 8886: 	    printf("%12.7f ",p[jk]);
 8887: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 8888: 	    fprintf(ficres,"%12.7f ",p[jk]);
 8889: 	    jk++; 
 8890: 	  }
 8891: 	  printf("\n");
 8892: 	  fprintf(ficlog,"\n");
 8893: 	  fprintf(ficres,"\n");
 8894: 	}
 8895:       }
 8896:     }
 8897:     if(mle != 0){
 8898:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
 8899:       ftolhess=ftol; /* Usually correct */
 8900:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
 8901:       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");
 8902:       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");
 8903:       for(i=1,jk=1; i <=nlstate; i++){
 8904: 	for(k=1; k <=(nlstate+ndeath); k++){
 8905: 	  if (k != i) {
 8906: 	    printf("%d%d ",i,k);
 8907: 	    fprintf(ficlog,"%d%d ",i,k);
 8908: 	    for(j=1; j <=ncovmodel; j++){
 8909: 	      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]));
 8910: 	      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]));
 8911: 	      jk++; 
 8912: 	    }
 8913: 	    printf("\n");
 8914: 	    fprintf(ficlog,"\n");
 8915: 	  }
 8916: 	}
 8917:       }
 8918:     } /* end of hesscov and Wald tests */
 8919: 
 8920:     /*  */
 8921:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 8922:     printf("# Scales (for hessian or gradient estimation)\n");
 8923:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 8924:     for(i=1,jk=1; i <=nlstate; i++){
 8925:       for(j=1; j <=nlstate+ndeath; j++){
 8926: 	if (j!=i) {
 8927: 	  fprintf(ficres,"%1d%1d",i,j);
 8928: 	  printf("%1d%1d",i,j);
 8929: 	  fprintf(ficlog,"%1d%1d",i,j);
 8930: 	  for(k=1; k<=ncovmodel;k++){
 8931: 	    printf(" %.5e",delti[jk]);
 8932: 	    fprintf(ficlog," %.5e",delti[jk]);
 8933: 	    fprintf(ficres," %.5e",delti[jk]);
 8934: 	    jk++;
 8935: 	  }
 8936: 	  printf("\n");
 8937: 	  fprintf(ficlog,"\n");
 8938: 	  fprintf(ficres,"\n");
 8939: 	}
 8940:       }
 8941:     }
 8942:     
 8943:     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");
 8944:     if(mle >= 1) /* To big for the screen */
 8945:       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");
 8946:     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");
 8947:     /* # 121 Var(a12)\n\ */
 8948:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 8949:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 8950:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 8951:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 8952:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 8953:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 8954:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 8955:     
 8956:     
 8957:     /* Just to have a covariance matrix which will be more understandable
 8958:        even is we still don't want to manage dictionary of variables
 8959:     */
 8960:     for(itimes=1;itimes<=2;itimes++){
 8961:       jj=0;
 8962:       for(i=1; i <=nlstate; i++){
 8963: 	for(j=1; j <=nlstate+ndeath; j++){
 8964: 	  if(j==i) continue;
 8965: 	  for(k=1; k<=ncovmodel;k++){
 8966: 	    jj++;
 8967: 	    ca[0]= k+'a'-1;ca[1]='\0';
 8968: 	    if(itimes==1){
 8969: 	      if(mle>=1)
 8970: 		printf("#%1d%1d%d",i,j,k);
 8971: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 8972: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 8973: 	    }else{
 8974: 	      if(mle>=1)
 8975: 		printf("%1d%1d%d",i,j,k);
 8976: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 8977: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 8978: 	    }
 8979: 	    ll=0;
 8980: 	    for(li=1;li <=nlstate; li++){
 8981: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 8982: 		if(lj==li) continue;
 8983: 		for(lk=1;lk<=ncovmodel;lk++){
 8984: 		  ll++;
 8985: 		  if(ll<=jj){
 8986: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 8987: 		    if(ll<jj){
 8988: 		      if(itimes==1){
 8989: 			if(mle>=1)
 8990: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8991: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8992: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8993: 		      }else{
 8994: 			if(mle>=1)
 8995: 			  printf(" %.5e",matcov[jj][ll]); 
 8996: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 8997: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 8998: 		      }
 8999: 		    }else{
 9000: 		      if(itimes==1){
 9001: 			if(mle>=1)
 9002: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 9003: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 9004: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 9005: 		      }else{
 9006: 			if(mle>=1)
 9007: 			  printf(" %.7e",matcov[jj][ll]); 
 9008: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
 9009: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
 9010: 		      }
 9011: 		    }
 9012: 		  }
 9013: 		} /* end lk */
 9014: 	      } /* end lj */
 9015: 	    } /* end li */
 9016: 	    if(mle>=1)
 9017: 	      printf("\n");
 9018: 	    fprintf(ficlog,"\n");
 9019: 	    fprintf(ficres,"\n");
 9020: 	    numlinepar++;
 9021: 	  } /* end k*/
 9022: 	} /*end j */
 9023:       } /* end i */
 9024:     } /* end itimes */
 9025:     
 9026:     fflush(ficlog);
 9027:     fflush(ficres);
 9028:       while(fgets(line, MAXLINE, ficpar)) {
 9029:     /* If line starts with a # it is a comment */
 9030:     if (line[0] == '#') {
 9031:       numlinepar++;
 9032:       fputs(line,stdout);
 9033:       fputs(line,ficparo);
 9034:       fputs(line,ficlog);
 9035:       continue;
 9036:     }else
 9037:       break;
 9038:   }
 9039: 
 9040:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
 9041:     /*   ungetc(c,ficpar); */
 9042:     /*   fgets(line, MAXLINE, ficpar); */
 9043:     /*   fputs(line,stdout); */
 9044:     /*   fputs(line,ficparo); */
 9045:     /* } */
 9046:     /* ungetc(c,ficpar); */
 9047:     
 9048:     estepm=0;
 9049:     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){
 9050: 
 9051:     if (num_filled != 6) {
 9052:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
 9053:       printf("but line=%s\n",line);
 9054:       goto end;
 9055:     }
 9056:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
 9057:   }
 9058:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9059:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9060: 
 9061:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
 9062:     if (estepm==0 || estepm < stepm) estepm=stepm;
 9063:     if (fage <= 2) {
 9064:       bage = ageminpar;
 9065:       fage = agemaxpar;
 9066:     }
 9067:     
 9068:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 9069:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9070:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9071: 
 9072:     /* Other stuffs, more or less useful */    
 9073:     while((c=getc(ficpar))=='#' && c!= EOF){
 9074:       ungetc(c,ficpar);
 9075:       fgets(line, MAXLINE, ficpar);
 9076:       fputs(line,stdout);
 9077:       fputs(line,ficparo);
 9078:     }
 9079:     ungetc(c,ficpar);
 9080:     
 9081:     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);
 9082:     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);
 9083:     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);
 9084:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 9085:     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);
 9086:     
 9087:     while((c=getc(ficpar))=='#' && c!= EOF){
 9088:       ungetc(c,ficpar);
 9089:       fgets(line, MAXLINE, ficpar);
 9090:       fputs(line,stdout);
 9091:       fputs(line,ficparo);
 9092:     }
 9093:     ungetc(c,ficpar);
 9094:     
 9095:     
 9096:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 9097:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 9098:     
 9099:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 9100:     fprintf(ficlog,"pop_based=%d\n",popbased);
 9101:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 9102:     fprintf(ficres,"pop_based=%d\n",popbased);   
 9103:     
 9104:     while((c=getc(ficpar))=='#' && c!= EOF){
 9105:       ungetc(c,ficpar);
 9106:       fgets(line, MAXLINE, ficpar);
 9107:       fputs(line,stdout);
 9108:       fputs(line,ficparo);
 9109:     }
 9110:     ungetc(c,ficpar);
 9111:     
 9112:     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);
 9113:     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);
 9114:     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);
 9115:     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);
 9116:     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);
 9117:     /* day and month of proj2 are not used but only year anproj2.*/
 9118:     
 9119:     while((c=getc(ficpar))=='#' && c!= EOF){
 9120:       ungetc(c,ficpar);
 9121:       fgets(line, MAXLINE, ficpar);
 9122:       fputs(line,stdout);
 9123:       fputs(line,ficparo);
 9124:     }
 9125:     ungetc(c,ficpar);
 9126:     
 9127:     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);
 9128:     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);
 9129:     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);
 9130:     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);
 9131:     /* day and month of proj2 are not used but only year anproj2.*/
 9132:     
 9133:     
 9134:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 9135:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 9136:     
 9137:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9138:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
 9139:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9140: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9141: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9142:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9143: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9144: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9145:     }else
 9146:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
 9147:     
 9148:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
 9149: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
 9150: 		 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
 9151:       
 9152:    /*------------ free_vector  -------------*/
 9153:    /*  chdir(path); */
 9154:  
 9155:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
 9156:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
 9157:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
 9158:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
 9159:     free_lvector(num,1,n);
 9160:     free_vector(agedc,1,n);
 9161:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 9162:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 9163:     fclose(ficparo);
 9164:     fclose(ficres);
 9165: 
 9166: 
 9167:     /* Other results (useful)*/
 9168: 
 9169: 
 9170:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9171:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 9172:     prlim=matrix(1,nlstate,1,nlstate);
 9173:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 9174:     fclose(ficrespl);
 9175: 
 9176:     /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9177:     /*#include "prevlim.h"*/  /* Use ficresplb, ficlog */
 9178:     bprlim=matrix(1,nlstate,1,nlstate);
 9179:     back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 9180:     fclose(ficresplb);
 9181: 
 9182:     
 9183: #ifdef FREEEXIT2
 9184: #include "freeexit2.h"
 9185: #endif
 9186: 
 9187:     /*------------- h Pij x at various ages ------------*/
 9188:     /*#include "hpijx.h"*/
 9189:     hPijx(p, bage, fage);
 9190:     fclose(ficrespij);
 9191: 
 9192:     hBijx(p, bage, fage);
 9193:     fclose(ficrespijb);
 9194: 
 9195:   /*-------------- Variance of one-step probabilities---*/
 9196:     k=1;
 9197:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 9198: 
 9199: 
 9200:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 9201:     for(i=1;i<=AGESUP;i++)
 9202:       for(j=1;j<=NCOVMAX;j++)
 9203: 	for(k=1;k<=NCOVMAX;k++)
 9204: 	  probs[i][j][k]=0.;
 9205: 
 9206:     /*---------- Forecasting ------------------*/
 9207:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 9208:     if(prevfcast==1){
 9209:       /*    if(stepm ==1){*/
 9210:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 9211:     }
 9212:     if(backcast==1){
 9213:       prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff);
 9214:     }
 9215:     /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 9216:     /*      }  */
 9217:     /*      else{ */
 9218:     /*        erreur=108; */
 9219:     /*        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); */
 9220:     /*        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); */
 9221:     /*      } */
 9222:     
 9223:  
 9224:     /* ------ Other prevalence ratios------------ */
 9225: 
 9226:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 9227: 
 9228:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 9229:     /*  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",\
 9230: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 9231:     */
 9232:     free_ivector(wav,1,imx);
 9233:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
 9234:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
 9235:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
 9236: 
 9237: 
 9238:     if (mobilav!=0) {
 9239:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 9240:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 9241: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 9242: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 9243:       }
 9244:     }
 9245: 
 9246: 
 9247:     /*---------- Health expectancies, no variances ------------*/
 9248: 
 9249:     strcpy(filerese,"E_");
 9250:     strcat(filerese,fileresu);
 9251:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 9252:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9253:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9254:     }
 9255:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
 9256:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
 9257:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9258:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9259:           
 9260:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9261: 	fprintf(ficreseij,"\n#****** ");
 9262: 	for(j=1;j<=cptcoveff;j++) {
 9263: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9264: 	}
 9265: 	fprintf(ficreseij,"******\n");
 9266: 
 9267: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9268: 	oldm=oldms;savm=savms;
 9269: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 9270:       
 9271: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9272:       /*}*/
 9273:     }
 9274:     fclose(ficreseij);
 9275:     printf("done evsij\n");fflush(stdout);
 9276:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
 9277: 
 9278:     /*---------- Health expectancies and variances ------------*/
 9279: 
 9280: 
 9281:     strcpy(filerest,"T_");
 9282:     strcat(filerest,fileresu);
 9283:     if((ficrest=fopen(filerest,"w"))==NULL) {
 9284:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 9285:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 9286:     }
 9287:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
 9288:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
 9289: 
 9290: 
 9291:     strcpy(fileresstde,"STDE_");
 9292:     strcat(fileresstde,fileresu);
 9293:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 9294:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9295:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9296:     }
 9297:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9298:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9299: 
 9300:     strcpy(filerescve,"CVE_");
 9301:     strcat(filerescve,fileresu);
 9302:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 9303:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9304:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9305:     }
 9306:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9307:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9308: 
 9309:     strcpy(fileresv,"V_");
 9310:     strcat(fileresv,fileresu);
 9311:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 9312:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 9313:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 9314:     }
 9315:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
 9316:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
 9317: 
 9318:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9319:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9320:           
 9321:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9322:       fprintf(ficrest,"\n#****** ");
 9323:       for(j=1;j<=cptcoveff;j++) 
 9324: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9325:       fprintf(ficrest,"******\n");
 9326:       
 9327:       fprintf(ficresstdeij,"\n#****** ");
 9328:       fprintf(ficrescveij,"\n#****** ");
 9329:       for(j=1;j<=cptcoveff;j++) {
 9330: 	fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9331: 	fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9332:       }
 9333:       fprintf(ficresstdeij,"******\n");
 9334:       fprintf(ficrescveij,"******\n");
 9335:       
 9336:       fprintf(ficresvij,"\n#****** ");
 9337:       for(j=1;j<=cptcoveff;j++) 
 9338: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9339:       fprintf(ficresvij,"******\n");
 9340:       
 9341:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9342:       oldm=oldms;savm=savms;
 9343:       printf(" cvevsij %d, ",k);
 9344:       fprintf(ficlog, " cvevsij %d, ",k);
 9345:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
 9346:       printf(" end cvevsij \n ");
 9347:       fprintf(ficlog, " end cvevsij \n ");
 9348:       
 9349:       /*
 9350:        */
 9351:       /* goto endfree; */
 9352:       
 9353:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9354:       pstamp(ficrest);
 9355:       
 9356:       
 9357:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 9358: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
 9359: 	cptcod= 0; /* To be deleted */
 9360: 	printf("varevsij %d \n",vpopbased);
 9361: 	fprintf(ficlog, "varevsij %d \n",vpopbased);
 9362: 	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 */
 9363: 	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 ");
 9364: 	if(vpopbased==1)
 9365: 	  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);
 9366: 	else
 9367: 	  fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 9368: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
 9369: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 9370: 	fprintf(ficrest,"\n");
 9371: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
 9372: 	epj=vector(1,nlstate+1);
 9373: 	printf("Computing age specific period (stable) prevalences in each health state \n");
 9374: 	fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
 9375: 	for(age=bage; age <=fage ;age++){
 9376: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
 9377: 	  if (vpopbased==1) {
 9378: 	    if(mobilav ==0){
 9379: 	      for(i=1; i<=nlstate;i++)
 9380: 		prlim[i][i]=probs[(int)age][i][k];
 9381: 	    }else{ /* mobilav */ 
 9382: 	      for(i=1; i<=nlstate;i++)
 9383: 		prlim[i][i]=mobaverage[(int)age][i][k];
 9384: 	    }
 9385: 	  }
 9386: 	  
 9387: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
 9388: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
 9389: 	  /* printf(" age %4.0f ",age); */
 9390: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 9391: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
 9392: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
 9393: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 9394: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
 9395: 	    }
 9396: 	    epj[nlstate+1] +=epj[j];
 9397: 	  }
 9398: 	  /* printf(" age %4.0f \n",age); */
 9399: 	  
 9400: 	  for(i=1, vepp=0.;i <=nlstate;i++)
 9401: 	    for(j=1;j <=nlstate;j++)
 9402: 	      vepp += vareij[i][j][(int)age];
 9403: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 9404: 	  for(j=1;j <=nlstate;j++){
 9405: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 9406: 	  }
 9407: 	  fprintf(ficrest,"\n");
 9408: 	}
 9409:       } /* End vpopbased */
 9410:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9411:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9412:       free_vector(epj,1,nlstate+1);
 9413:       printf("done \n");fflush(stdout);
 9414:       fprintf(ficlog,"done\n");fflush(ficlog);
 9415:       
 9416:       /*}*/
 9417:     } /* End k */
 9418:     free_vector(weight,1,n);
 9419:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 9420:     free_imatrix(s,1,maxwav+1,1,n);
 9421:     free_matrix(anint,1,maxwav,1,n); 
 9422:     free_matrix(mint,1,maxwav,1,n);
 9423:     free_ivector(cod,1,n);
 9424:     free_ivector(tab,1,NCOVMAX);
 9425:     fclose(ficresstdeij);
 9426:     fclose(ficrescveij);
 9427:     fclose(ficresvij);
 9428:     fclose(ficrest);
 9429:     printf("done Health expectancies\n");fflush(stdout);
 9430:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
 9431:     fclose(ficpar);
 9432:   
 9433:     /*------- Variance of period (stable) prevalence------*/   
 9434: 
 9435:     strcpy(fileresvpl,"VPL_");
 9436:     strcat(fileresvpl,fileresu);
 9437:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 9438:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 9439:       exit(0);
 9440:     }
 9441:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
 9442:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
 9443: 
 9444:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9445:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9446:           
 9447:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9448:     	fprintf(ficresvpl,"\n#****** ");
 9449: 	for(j=1;j<=cptcoveff;j++) 
 9450: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9451: 	fprintf(ficresvpl,"******\n");
 9452:       
 9453: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 9454: 	oldm=oldms;savm=savms;
 9455: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
 9456: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 9457:       /*}*/
 9458:     }
 9459: 
 9460:     fclose(ficresvpl);
 9461:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
 9462:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
 9463: 
 9464:     /*---------- End : free ----------------*/
 9465:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 9466:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 9467:   }  /* mle==-3 arrives here for freeing */
 9468:  /* endfree:*/
 9469:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9470:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 9471:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9472:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9473:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9474:     free_matrix(covar,0,NCOVMAX,1,n);
 9475:     free_matrix(matcov,1,npar,1,npar);
 9476:     free_matrix(hess,1,npar,1,npar);
 9477:     /*free_vector(delti,1,npar);*/
 9478:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9479:     free_matrix(agev,1,maxwav,1,imx);
 9480:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 9481: 
 9482:     free_ivector(ncodemax,1,NCOVMAX);
 9483:     free_ivector(ncodemaxwundef,1,NCOVMAX);
 9484:     free_ivector(Tvar,1,NCOVMAX);
 9485:     free_ivector(Tprod,1,NCOVMAX);
 9486:     free_ivector(Tvaraff,1,NCOVMAX);
 9487:     free_ivector(Tage,1,NCOVMAX);
 9488: 
 9489:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 9490:     /* free_imatrix(codtab,1,100,1,10); */
 9491:   fflush(fichtm);
 9492:   fflush(ficgp);
 9493:   
 9494: 
 9495:   if((nberr >0) || (nbwarn>0)){
 9496:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
 9497:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
 9498:   }else{
 9499:     printf("End of Imach\n");
 9500:     fprintf(ficlog,"End of Imach\n");
 9501:   }
 9502:   printf("See log file on %s\n",filelog);
 9503:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 9504:   /*(void) gettimeofday(&end_time,&tzp);*/
 9505:   rend_time = time(NULL);  
 9506:   end_time = *localtime(&rend_time);
 9507:   /* tml = *localtime(&end_time.tm_sec); */
 9508:   strcpy(strtend,asctime(&end_time));
 9509:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 9510:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 9511:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9512: 
 9513:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9514:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9515:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9516:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 9517: /*   if(fileappend(fichtm,optionfilehtm)){ */
 9518:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9519:   fclose(fichtm);
 9520:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9521:   fclose(fichtmcov);
 9522:   fclose(ficgp);
 9523:   fclose(ficlog);
 9524:   /*------ End -----------*/
 9525: 
 9526: 
 9527:    printf("Before Current directory %s!\n",pathcd);
 9528: #ifdef WIN32
 9529:    if (_chdir(pathcd) != 0)
 9530: 	   printf("Can't move to directory %s!\n",path);
 9531:    if(_getcwd(pathcd,MAXLINE) > 0)
 9532: #else
 9533:    if(chdir(pathcd) != 0)
 9534: 	   printf("Can't move to directory %s!\n", path);
 9535:    if (getcwd(pathcd, MAXLINE) > 0)
 9536: #endif 
 9537:     printf("Current directory %s!\n",pathcd);
 9538:   /*strcat(plotcmd,CHARSEPARATOR);*/
 9539:   sprintf(plotcmd,"gnuplot");
 9540: #ifdef _WIN32
 9541:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 9542: #endif
 9543:   if(!stat(plotcmd,&info)){
 9544:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9545:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 9546:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 9547:     }else
 9548:       strcpy(pplotcmd,plotcmd);
 9549: #ifdef __unix
 9550:     strcpy(plotcmd,GNUPLOTPROGRAM);
 9551:     if(!stat(plotcmd,&info)){
 9552:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9553:     }else
 9554:       strcpy(pplotcmd,plotcmd);
 9555: #endif
 9556:   }else
 9557:     strcpy(pplotcmd,plotcmd);
 9558:   
 9559:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 9560:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 9561: 
 9562:   if((outcmd=system(plotcmd)) != 0){
 9563:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 9564:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 9565:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 9566:     if((outcmd=system(plotcmd)) != 0)
 9567:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 9568:   }
 9569:   printf(" Successful, please wait...");
 9570:   while (z[0] != 'q') {
 9571:     /* chdir(path); */
 9572:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 9573:     scanf("%s",z);
 9574: /*     if (z[0] == 'c') system("./imach"); */
 9575:     if (z[0] == 'e') {
 9576: #ifdef __APPLE__
 9577:       sprintf(pplotcmd, "open %s", optionfilehtm);
 9578: #elif __linux
 9579:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 9580: #else
 9581:       sprintf(pplotcmd, "%s", optionfilehtm);
 9582: #endif
 9583:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 9584:       system(pplotcmd);
 9585:     }
 9586:     else if (z[0] == 'g') system(plotcmd);
 9587:     else if (z[0] == 'q') exit(0);
 9588:   }
 9589:   end:
 9590:   while (z[0] != 'q') {
 9591:     printf("\nType  q for exiting: "); fflush(stdout);
 9592:     scanf("%s",z);
 9593:   }
 9594: }

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