File:  [Local Repository] / imach / src / imach.c
Revision 1.192: download - view: text, annotated - select for diffs
Thu Jul 16 16:49:02 2015 UTC (8 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Fixing some outputs

    1: /* $Id: imach.c,v 1.192 2015/07/16 16:49:02 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.192  2015/07/16 16:49:02  brouard
    5:   Summary: Fixing some outputs
    6: 
    7:   Revision 1.191  2015/07/14 10:00:33  brouard
    8:   Summary: Some fixes
    9: 
   10:   Revision 1.190  2015/05/05 08:51:13  brouard
   11:   Summary: Adding digits in output parameters (7 digits instead of 6)
   12: 
   13:   Fix 1+age+.
   14: 
   15:   Revision 1.189  2015/04/30 14:45:16  brouard
   16:   Summary: 0.98q2
   17: 
   18:   Revision 1.188  2015/04/30 08:27:53  brouard
   19:   *** empty log message ***
   20: 
   21:   Revision 1.187  2015/04/29 09:11:15  brouard
   22:   *** empty log message ***
   23: 
   24:   Revision 1.186  2015/04/23 12:01:52  brouard
   25:   Summary: V1*age is working now, version 0.98q1
   26: 
   27:   Some codes had been disabled in order to simplify and Vn*age was
   28:   working in the optimization phase, ie, giving correct MLE parameters,
   29:   but, as usual, outputs were not correct and program core dumped.
   30: 
   31:   Revision 1.185  2015/03/11 13:26:42  brouard
   32:   Summary: Inclusion of compile and links command line for Intel Compiler
   33: 
   34:   Revision 1.184  2015/03/11 11:52:39  brouard
   35:   Summary: Back from Windows 8. Intel Compiler
   36: 
   37:   Revision 1.183  2015/03/10 20:34:32  brouard
   38:   Summary: 0.98q0, trying with directest, mnbrak fixed
   39: 
   40:   We use directest instead of original Powell test; probably no
   41:   incidence on the results, but better justifications;
   42:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
   43:   wrong results.
   44: 
   45:   Revision 1.182  2015/02/12 08:19:57  brouard
   46:   Summary: Trying to keep directest which seems simpler and more general
   47:   Author: Nicolas Brouard
   48: 
   49:   Revision 1.181  2015/02/11 23:22:24  brouard
   50:   Summary: Comments on Powell added
   51: 
   52:   Author:
   53: 
   54:   Revision 1.180  2015/02/11 17:33:45  brouard
   55:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
   56: 
   57:   Revision 1.179  2015/01/04 09:57:06  brouard
   58:   Summary: back to OS/X
   59: 
   60:   Revision 1.178  2015/01/04 09:35:48  brouard
   61:   *** empty log message ***
   62: 
   63:   Revision 1.177  2015/01/03 18:40:56  brouard
   64:   Summary: Still testing ilc32 on OSX
   65: 
   66:   Revision 1.176  2015/01/03 16:45:04  brouard
   67:   *** empty log message ***
   68: 
   69:   Revision 1.175  2015/01/03 16:33:42  brouard
   70:   *** empty log message ***
   71: 
   72:   Revision 1.174  2015/01/03 16:15:49  brouard
   73:   Summary: Still in cross-compilation
   74: 
   75:   Revision 1.173  2015/01/03 12:06:26  brouard
   76:   Summary: trying to detect cross-compilation
   77: 
   78:   Revision 1.172  2014/12/27 12:07:47  brouard
   79:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   80: 
   81:   Revision 1.171  2014/12/23 13:26:59  brouard
   82:   Summary: Back from Visual C
   83: 
   84:   Still problem with utsname.h on Windows
   85: 
   86:   Revision 1.170  2014/12/23 11:17:12  brouard
   87:   Summary: Cleaning some \%% back to %%
   88: 
   89:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   90: 
   91:   Revision 1.169  2014/12/22 23:08:31  brouard
   92:   Summary: 0.98p
   93: 
   94:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   95: 
   96:   Revision 1.168  2014/12/22 15:17:42  brouard
   97:   Summary: update
   98: 
   99:   Revision 1.167  2014/12/22 13:50:56  brouard
  100:   Summary: Testing uname and compiler version and if compiled 32 or 64
  101: 
  102:   Testing on Linux 64
  103: 
  104:   Revision 1.166  2014/12/22 11:40:47  brouard
  105:   *** empty log message ***
  106: 
  107:   Revision 1.165  2014/12/16 11:20:36  brouard
  108:   Summary: After compiling on Visual C
  109: 
  110:   * imach.c (Module): Merging 1.61 to 1.162
  111: 
  112:   Revision 1.164  2014/12/16 10:52:11  brouard
  113:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  114: 
  115:   * imach.c (Module): Merging 1.61 to 1.162
  116: 
  117:   Revision 1.163  2014/12/16 10:30:11  brouard
  118:   * imach.c (Module): Merging 1.61 to 1.162
  119: 
  120:   Revision 1.162  2014/09/25 11:43:39  brouard
  121:   Summary: temporary backup 0.99!
  122: 
  123:   Revision 1.1  2014/09/16 11:06:58  brouard
  124:   Summary: With some code (wrong) for nlopt
  125: 
  126:   Author:
  127: 
  128:   Revision 1.161  2014/09/15 20:41:41  brouard
  129:   Summary: Problem with macro SQR on Intel compiler
  130: 
  131:   Revision 1.160  2014/09/02 09:24:05  brouard
  132:   *** empty log message ***
  133: 
  134:   Revision 1.159  2014/09/01 10:34:10  brouard
  135:   Summary: WIN32
  136:   Author: Brouard
  137: 
  138:   Revision 1.158  2014/08/27 17:11:51  brouard
  139:   *** empty log message ***
  140: 
  141:   Revision 1.157  2014/08/27 16:26:55  brouard
  142:   Summary: Preparing windows Visual studio version
  143:   Author: Brouard
  144: 
  145:   In order to compile on Visual studio, time.h is now correct and time_t
  146:   and tm struct should be used. difftime should be used but sometimes I
  147:   just make the differences in raw time format (time(&now).
  148:   Trying to suppress #ifdef LINUX
  149:   Add xdg-open for __linux in order to open default browser.
  150: 
  151:   Revision 1.156  2014/08/25 20:10:10  brouard
  152:   *** empty log message ***
  153: 
  154:   Revision 1.155  2014/08/25 18:32:34  brouard
  155:   Summary: New compile, minor changes
  156:   Author: Brouard
  157: 
  158:   Revision 1.154  2014/06/20 17:32:08  brouard
  159:   Summary: Outputs now all graphs of convergence to period prevalence
  160: 
  161:   Revision 1.153  2014/06/20 16:45:46  brouard
  162:   Summary: If 3 live state, convergence to period prevalence on same graph
  163:   Author: Brouard
  164: 
  165:   Revision 1.152  2014/06/18 17:54:09  brouard
  166:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  167: 
  168:   Revision 1.151  2014/06/18 16:43:30  brouard
  169:   *** empty log message ***
  170: 
  171:   Revision 1.150  2014/06/18 16:42:35  brouard
  172:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  173:   Author: brouard
  174: 
  175:   Revision 1.149  2014/06/18 15:51:14  brouard
  176:   Summary: Some fixes in parameter files errors
  177:   Author: Nicolas Brouard
  178: 
  179:   Revision 1.148  2014/06/17 17:38:48  brouard
  180:   Summary: Nothing new
  181:   Author: Brouard
  182: 
  183:   Just a new packaging for OS/X version 0.98nS
  184: 
  185:   Revision 1.147  2014/06/16 10:33:11  brouard
  186:   *** empty log message ***
  187: 
  188:   Revision 1.146  2014/06/16 10:20:28  brouard
  189:   Summary: Merge
  190:   Author: Brouard
  191: 
  192:   Merge, before building revised version.
  193: 
  194:   Revision 1.145  2014/06/10 21:23:15  brouard
  195:   Summary: Debugging with valgrind
  196:   Author: Nicolas Brouard
  197: 
  198:   Lot of changes in order to output the results with some covariates
  199:   After the Edimburgh REVES conference 2014, it seems mandatory to
  200:   improve the code.
  201:   No more memory valgrind error but a lot has to be done in order to
  202:   continue the work of splitting the code into subroutines.
  203:   Also, decodemodel has been improved. Tricode is still not
  204:   optimal. nbcode should be improved. Documentation has been added in
  205:   the source code.
  206: 
  207:   Revision 1.143  2014/01/26 09:45:38  brouard
  208:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  209: 
  210:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  211:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  212: 
  213:   Revision 1.142  2014/01/26 03:57:36  brouard
  214:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  215: 
  216:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  217: 
  218:   Revision 1.141  2014/01/26 02:42:01  brouard
  219:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  220: 
  221:   Revision 1.140  2011/09/02 10:37:54  brouard
  222:   Summary: times.h is ok with mingw32 now.
  223: 
  224:   Revision 1.139  2010/06/14 07:50:17  brouard
  225:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  226:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  227: 
  228:   Revision 1.138  2010/04/30 18:19:40  brouard
  229:   *** empty log message ***
  230: 
  231:   Revision 1.137  2010/04/29 18:11:38  brouard
  232:   (Module): Checking covariates for more complex models
  233:   than V1+V2. A lot of change to be done. Unstable.
  234: 
  235:   Revision 1.136  2010/04/26 20:30:53  brouard
  236:   (Module): merging some libgsl code. Fixing computation
  237:   of likelione (using inter/intrapolation if mle = 0) in order to
  238:   get same likelihood as if mle=1.
  239:   Some cleaning of code and comments added.
  240: 
  241:   Revision 1.135  2009/10/29 15:33:14  brouard
  242:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  243: 
  244:   Revision 1.134  2009/10/29 13:18:53  brouard
  245:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  246: 
  247:   Revision 1.133  2009/07/06 10:21:25  brouard
  248:   just nforces
  249: 
  250:   Revision 1.132  2009/07/06 08:22:05  brouard
  251:   Many tings
  252: 
  253:   Revision 1.131  2009/06/20 16:22:47  brouard
  254:   Some dimensions resccaled
  255: 
  256:   Revision 1.130  2009/05/26 06:44:34  brouard
  257:   (Module): Max Covariate is now set to 20 instead of 8. A
  258:   lot of cleaning with variables initialized to 0. Trying to make
  259:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  260: 
  261:   Revision 1.129  2007/08/31 13:49:27  lievre
  262:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  263: 
  264:   Revision 1.128  2006/06/30 13:02:05  brouard
  265:   (Module): Clarifications on computing e.j
  266: 
  267:   Revision 1.127  2006/04/28 18:11:50  brouard
  268:   (Module): Yes the sum of survivors was wrong since
  269:   imach-114 because nhstepm was no more computed in the age
  270:   loop. Now we define nhstepma in the age loop.
  271:   (Module): In order to speed up (in case of numerous covariates) we
  272:   compute health expectancies (without variances) in a first step
  273:   and then all the health expectancies with variances or standard
  274:   deviation (needs data from the Hessian matrices) which slows the
  275:   computation.
  276:   In the future we should be able to stop the program is only health
  277:   expectancies and graph are needed without standard deviations.
  278: 
  279:   Revision 1.126  2006/04/28 17:23:28  brouard
  280:   (Module): Yes the sum of survivors was wrong since
  281:   imach-114 because nhstepm was no more computed in the age
  282:   loop. Now we define nhstepma in the age loop.
  283:   Version 0.98h
  284: 
  285:   Revision 1.125  2006/04/04 15:20:31  lievre
  286:   Errors in calculation of health expectancies. Age was not initialized.
  287:   Forecasting file added.
  288: 
  289:   Revision 1.124  2006/03/22 17:13:53  lievre
  290:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  291:   The log-likelihood is printed in the log file
  292: 
  293:   Revision 1.123  2006/03/20 10:52:43  brouard
  294:   * imach.c (Module): <title> changed, corresponds to .htm file
  295:   name. <head> headers where missing.
  296: 
  297:   * imach.c (Module): Weights can have a decimal point as for
  298:   English (a comma might work with a correct LC_NUMERIC environment,
  299:   otherwise the weight is truncated).
  300:   Modification of warning when the covariates values are not 0 or
  301:   1.
  302:   Version 0.98g
  303: 
  304:   Revision 1.122  2006/03/20 09:45:41  brouard
  305:   (Module): Weights can have a decimal point as for
  306:   English (a comma might work with a correct LC_NUMERIC environment,
  307:   otherwise the weight is truncated).
  308:   Modification of warning when the covariates values are not 0 or
  309:   1.
  310:   Version 0.98g
  311: 
  312:   Revision 1.121  2006/03/16 17:45:01  lievre
  313:   * imach.c (Module): Comments concerning covariates added
  314: 
  315:   * imach.c (Module): refinements in the computation of lli if
  316:   status=-2 in order to have more reliable computation if stepm is
  317:   not 1 month. Version 0.98f
  318: 
  319:   Revision 1.120  2006/03/16 15:10:38  lievre
  320:   (Module): refinements in the computation of lli if
  321:   status=-2 in order to have more reliable computation if stepm is
  322:   not 1 month. Version 0.98f
  323: 
  324:   Revision 1.119  2006/03/15 17:42:26  brouard
  325:   (Module): Bug if status = -2, the loglikelihood was
  326:   computed as likelihood omitting the logarithm. Version O.98e
  327: 
  328:   Revision 1.118  2006/03/14 18:20:07  brouard
  329:   (Module): varevsij Comments added explaining the second
  330:   table of variances if popbased=1 .
  331:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  332:   (Module): Function pstamp added
  333:   (Module): Version 0.98d
  334: 
  335:   Revision 1.117  2006/03/14 17:16:22  brouard
  336:   (Module): varevsij Comments added explaining the second
  337:   table of variances if popbased=1 .
  338:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  339:   (Module): Function pstamp added
  340:   (Module): Version 0.98d
  341: 
  342:   Revision 1.116  2006/03/06 10:29:27  brouard
  343:   (Module): Variance-covariance wrong links and
  344:   varian-covariance of ej. is needed (Saito).
  345: 
  346:   Revision 1.115  2006/02/27 12:17:45  brouard
  347:   (Module): One freematrix added in mlikeli! 0.98c
  348: 
  349:   Revision 1.114  2006/02/26 12:57:58  brouard
  350:   (Module): Some improvements in processing parameter
  351:   filename with strsep.
  352: 
  353:   Revision 1.113  2006/02/24 14:20:24  brouard
  354:   (Module): Memory leaks checks with valgrind and:
  355:   datafile was not closed, some imatrix were not freed and on matrix
  356:   allocation too.
  357: 
  358:   Revision 1.112  2006/01/30 09:55:26  brouard
  359:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  360: 
  361:   Revision 1.111  2006/01/25 20:38:18  brouard
  362:   (Module): Lots of cleaning and bugs added (Gompertz)
  363:   (Module): Comments can be added in data file. Missing date values
  364:   can be a simple dot '.'.
  365: 
  366:   Revision 1.110  2006/01/25 00:51:50  brouard
  367:   (Module): Lots of cleaning and bugs added (Gompertz)
  368: 
  369:   Revision 1.109  2006/01/24 19:37:15  brouard
  370:   (Module): Comments (lines starting with a #) are allowed in data.
  371: 
  372:   Revision 1.108  2006/01/19 18:05:42  lievre
  373:   Gnuplot problem appeared...
  374:   To be fixed
  375: 
  376:   Revision 1.107  2006/01/19 16:20:37  brouard
  377:   Test existence of gnuplot in imach path
  378: 
  379:   Revision 1.106  2006/01/19 13:24:36  brouard
  380:   Some cleaning and links added in html output
  381: 
  382:   Revision 1.105  2006/01/05 20:23:19  lievre
  383:   *** empty log message ***
  384: 
  385:   Revision 1.104  2005/09/30 16:11:43  lievre
  386:   (Module): sump fixed, loop imx fixed, and simplifications.
  387:   (Module): If the status is missing at the last wave but we know
  388:   that the person is alive, then we can code his/her status as -2
  389:   (instead of missing=-1 in earlier versions) and his/her
  390:   contributions to the likelihood is 1 - Prob of dying from last
  391:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  392:   the healthy state at last known wave). Version is 0.98
  393: 
  394:   Revision 1.103  2005/09/30 15:54:49  lievre
  395:   (Module): sump fixed, loop imx fixed, and simplifications.
  396: 
  397:   Revision 1.102  2004/09/15 17:31:30  brouard
  398:   Add the possibility to read data file including tab characters.
  399: 
  400:   Revision 1.101  2004/09/15 10:38:38  brouard
  401:   Fix on curr_time
  402: 
  403:   Revision 1.100  2004/07/12 18:29:06  brouard
  404:   Add version for Mac OS X. Just define UNIX in Makefile
  405: 
  406:   Revision 1.99  2004/06/05 08:57:40  brouard
  407:   *** empty log message ***
  408: 
  409:   Revision 1.98  2004/05/16 15:05:56  brouard
  410:   New version 0.97 . First attempt to estimate force of mortality
  411:   directly from the data i.e. without the need of knowing the health
  412:   state at each age, but using a Gompertz model: log u =a + b*age .
  413:   This is the basic analysis of mortality and should be done before any
  414:   other analysis, in order to test if the mortality estimated from the
  415:   cross-longitudinal survey is different from the mortality estimated
  416:   from other sources like vital statistic data.
  417: 
  418:   The same imach parameter file can be used but the option for mle should be -3.
  419: 
  420:   Agnès, who wrote this part of the code, tried to keep most of the
  421:   former routines in order to include the new code within the former code.
  422: 
  423:   The output is very simple: only an estimate of the intercept and of
  424:   the slope with 95% confident intervals.
  425: 
  426:   Current limitations:
  427:   A) Even if you enter covariates, i.e. with the
  428:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  429:   B) There is no computation of Life Expectancy nor Life Table.
  430: 
  431:   Revision 1.97  2004/02/20 13:25:42  lievre
  432:   Version 0.96d. Population forecasting command line is (temporarily)
  433:   suppressed.
  434: 
  435:   Revision 1.96  2003/07/15 15:38:55  brouard
  436:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  437:   rewritten within the same printf. Workaround: many printfs.
  438: 
  439:   Revision 1.95  2003/07/08 07:54:34  brouard
  440:   * imach.c (Repository):
  441:   (Repository): Using imachwizard code to output a more meaningful covariance
  442:   matrix (cov(a12,c31) instead of numbers.
  443: 
  444:   Revision 1.94  2003/06/27 13:00:02  brouard
  445:   Just cleaning
  446: 
  447:   Revision 1.93  2003/06/25 16:33:55  brouard
  448:   (Module): On windows (cygwin) function asctime_r doesn't
  449:   exist so I changed back to asctime which exists.
  450:   (Module): Version 0.96b
  451: 
  452:   Revision 1.92  2003/06/25 16:30:45  brouard
  453:   (Module): On windows (cygwin) function asctime_r doesn't
  454:   exist so I changed back to asctime which exists.
  455: 
  456:   Revision 1.91  2003/06/25 15:30:29  brouard
  457:   * imach.c (Repository): Duplicated warning errors corrected.
  458:   (Repository): Elapsed time after each iteration is now output. It
  459:   helps to forecast when convergence will be reached. Elapsed time
  460:   is stamped in powell.  We created a new html file for the graphs
  461:   concerning matrix of covariance. It has extension -cov.htm.
  462: 
  463:   Revision 1.90  2003/06/24 12:34:15  brouard
  464:   (Module): Some bugs corrected for windows. Also, when
  465:   mle=-1 a template is output in file "or"mypar.txt with the design
  466:   of the covariance matrix to be input.
  467: 
  468:   Revision 1.89  2003/06/24 12:30:52  brouard
  469:   (Module): Some bugs corrected for windows. Also, when
  470:   mle=-1 a template is output in file "or"mypar.txt with the design
  471:   of the covariance matrix to be input.
  472: 
  473:   Revision 1.88  2003/06/23 17:54:56  brouard
  474:   * 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.
  475: 
  476:   Revision 1.87  2003/06/18 12:26:01  brouard
  477:   Version 0.96
  478: 
  479:   Revision 1.86  2003/06/17 20:04:08  brouard
  480:   (Module): Change position of html and gnuplot routines and added
  481:   routine fileappend.
  482: 
  483:   Revision 1.85  2003/06/17 13:12:43  brouard
  484:   * imach.c (Repository): Check when date of death was earlier that
  485:   current date of interview. It may happen when the death was just
  486:   prior to the death. In this case, dh was negative and likelihood
  487:   was wrong (infinity). We still send an "Error" but patch by
  488:   assuming that the date of death was just one stepm after the
  489:   interview.
  490:   (Repository): Because some people have very long ID (first column)
  491:   we changed int to long in num[] and we added a new lvector for
  492:   memory allocation. But we also truncated to 8 characters (left
  493:   truncation)
  494:   (Repository): No more line truncation errors.
  495: 
  496:   Revision 1.84  2003/06/13 21:44:43  brouard
  497:   * imach.c (Repository): Replace "freqsummary" at a correct
  498:   place. It differs from routine "prevalence" which may be called
  499:   many times. Probs is memory consuming and must be used with
  500:   parcimony.
  501:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  502: 
  503:   Revision 1.83  2003/06/10 13:39:11  lievre
  504:   *** empty log message ***
  505: 
  506:   Revision 1.82  2003/06/05 15:57:20  brouard
  507:   Add log in  imach.c and  fullversion number is now printed.
  508: 
  509: */
  510: /*
  511:    Interpolated Markov Chain
  512: 
  513:   Short summary of the programme:
  514:   
  515:   This program computes Healthy Life Expectancies from
  516:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  517:   first survey ("cross") where individuals from different ages are
  518:   interviewed on their health status or degree of disability (in the
  519:   case of a health survey which is our main interest) -2- at least a
  520:   second wave of interviews ("longitudinal") which measure each change
  521:   (if any) in individual health status.  Health expectancies are
  522:   computed from the time spent in each health state according to a
  523:   model. More health states you consider, more time is necessary to reach the
  524:   Maximum Likelihood of the parameters involved in the model.  The
  525:   simplest model is the multinomial logistic model where pij is the
  526:   probability to be observed in state j at the second wave
  527:   conditional to be observed in state i at the first wave. Therefore
  528:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  529:   'age' is age and 'sex' is a covariate. If you want to have a more
  530:   complex model than "constant and age", you should modify the program
  531:   where the markup *Covariates have to be included here again* invites
  532:   you to do it.  More covariates you add, slower the
  533:   convergence.
  534: 
  535:   The advantage of this computer programme, compared to a simple
  536:   multinomial logistic model, is clear when the delay between waves is not
  537:   identical for each individual. Also, if a individual missed an
  538:   intermediate interview, the information is lost, but taken into
  539:   account using an interpolation or extrapolation.  
  540: 
  541:   hPijx is the probability to be observed in state i at age x+h
  542:   conditional to the observed state i at age x. The delay 'h' can be
  543:   split into an exact number (nh*stepm) of unobserved intermediate
  544:   states. This elementary transition (by month, quarter,
  545:   semester or year) is modelled as a multinomial logistic.  The hPx
  546:   matrix is simply the matrix product of nh*stepm elementary matrices
  547:   and the contribution of each individual to the likelihood is simply
  548:   hPijx.
  549: 
  550:   Also this programme outputs the covariance matrix of the parameters but also
  551:   of the life expectancies. It also computes the period (stable) prevalence. 
  552:   
  553:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  554:            Institut national d'études démographiques, Paris.
  555:   This software have been partly granted by Euro-REVES, a concerted action
  556:   from the European Union.
  557:   It is copyrighted identically to a GNU software product, ie programme and
  558:   software can be distributed freely for non commercial use. Latest version
  559:   can be accessed at http://euroreves.ined.fr/imach .
  560: 
  561:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  562:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  563:   
  564:   **********************************************************************/
  565: /*
  566:   main
  567:   read parameterfile
  568:   read datafile
  569:   concatwav
  570:   freqsummary
  571:   if (mle >= 1)
  572:     mlikeli
  573:   print results files
  574:   if mle==1 
  575:      computes hessian
  576:   read end of parameter file: agemin, agemax, bage, fage, estepm
  577:       begin-prev-date,...
  578:   open gnuplot file
  579:   open html file
  580:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  581:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  582:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  583:     freexexit2 possible for memory heap.
  584: 
  585:   h Pij x                         | pij_nom  ficrestpij
  586:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  587:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  588:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  589: 
  590:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  591:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  592:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  593:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  594:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  595: 
  596:   forecasting if prevfcast==1 prevforecast call prevalence()
  597:   health expectancies
  598:   Variance-covariance of DFLE
  599:   prevalence()
  600:    movingaverage()
  601:   varevsij() 
  602:   if popbased==1 varevsij(,popbased)
  603:   total life expectancies
  604:   Variance of period (stable) prevalence
  605:  end
  606: */
  607: 
  608: /* #define DEBUG */
  609: /* #define DEBUGBRENT */
  610: #define POWELL /* Instead of NLOPT */
  611: #define POWELLF1F3 /* Skip test */
  612: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  613: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  614: 
  615: #include <math.h>
  616: #include <stdio.h>
  617: #include <stdlib.h>
  618: #include <string.h>
  619: 
  620: #ifdef _WIN32
  621: #include <io.h>
  622: #include <windows.h>
  623: #include <tchar.h>
  624: #else
  625: #include <unistd.h>
  626: #endif
  627: 
  628: #include <limits.h>
  629: #include <sys/types.h>
  630: 
  631: #if defined(__GNUC__)
  632: #include <sys/utsname.h> /* Doesn't work on Windows */
  633: #endif
  634: 
  635: #include <sys/stat.h>
  636: #include <errno.h>
  637: /* extern int errno; */
  638: 
  639: /* #ifdef LINUX */
  640: /* #include <time.h> */
  641: /* #include "timeval.h" */
  642: /* #else */
  643: /* #include <sys/time.h> */
  644: /* #endif */
  645: 
  646: #include <time.h>
  647: 
  648: #ifdef GSL
  649: #include <gsl/gsl_errno.h>
  650: #include <gsl/gsl_multimin.h>
  651: #endif
  652: 
  653: 
  654: #ifdef NLOPT
  655: #include <nlopt.h>
  656: typedef struct {
  657:   double (* function)(double [] );
  658: } myfunc_data ;
  659: #endif
  660: 
  661: /* #include <libintl.h> */
  662: /* #define _(String) gettext (String) */
  663: 
  664: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  665: 
  666: #define GNUPLOTPROGRAM "gnuplot"
  667: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  668: #define FILENAMELENGTH 132
  669: 
  670: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  671: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  672: 
  673: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  674: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  675: 
  676: #define NINTERVMAX 8
  677: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  678: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  679: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  680: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  681: #define MAXN 20000
  682: #define YEARM 12. /**< Number of months per year */
  683: #define AGESUP 130
  684: #define AGEBASE 40
  685: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  686: #ifdef _WIN32
  687: #define DIRSEPARATOR '\\'
  688: #define CHARSEPARATOR "\\"
  689: #define ODIRSEPARATOR '/'
  690: #else
  691: #define DIRSEPARATOR '/'
  692: #define CHARSEPARATOR "/"
  693: #define ODIRSEPARATOR '\\'
  694: #endif
  695: 
  696: /* $Id: imach.c,v 1.192 2015/07/16 16:49:02 brouard Exp $ */
  697: /* $State: Exp $ */
  698: 
  699: char version[]="Imach version 0.98q3, July 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  700: char fullversion[]="$Revision: 1.192 $ $Date: 2015/07/16 16:49:02 $"; 
  701: char strstart[80];
  702: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  703: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  704: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  705: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  706: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  707: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  708: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  709: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  710: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  711: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  712: int cptcov=0; /* Working variable */
  713: int npar=NPARMAX;
  714: int nlstate=2; /* Number of live states */
  715: int ndeath=1; /* Number of dead states */
  716: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  717: int popbased=0;
  718: 
  719: int *wav; /* Number of waves for this individuual 0 is possible */
  720: int maxwav=0; /* Maxim number of waves */
  721: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  722: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  723: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  724: 		   to the likelihood and the sum of weights (done by funcone)*/
  725: int mle=1, weightopt=0;
  726: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  727: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  728: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  729: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  730: int countcallfunc=0;  /* Count the number of calls to func */
  731: double jmean=1; /* Mean space between 2 waves */
  732: double **matprod2(); /* test */
  733: double **oldm, **newm, **savm; /* Working pointers to matrices */
  734: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  735: /*FILE *fic ; */ /* Used in readdata only */
  736: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  737: FILE *ficlog, *ficrespow;
  738: int globpr=0; /* Global variable for printing or not */
  739: double fretone; /* Only one call to likelihood */
  740: long ipmx=0; /* Number of contributions */
  741: double sw; /* Sum of weights */
  742: char filerespow[FILENAMELENGTH];
  743: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  744: FILE *ficresilk;
  745: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  746: FILE *ficresprobmorprev;
  747: FILE *fichtm, *fichtmcov; /* Html File */
  748: FILE *ficreseij;
  749: char filerese[FILENAMELENGTH];
  750: FILE *ficresstdeij;
  751: char fileresstde[FILENAMELENGTH];
  752: FILE *ficrescveij;
  753: char filerescve[FILENAMELENGTH];
  754: FILE  *ficresvij;
  755: char fileresv[FILENAMELENGTH];
  756: FILE  *ficresvpl;
  757: char fileresvpl[FILENAMELENGTH];
  758: char title[MAXLINE];
  759: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  760: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  761: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  762: char command[FILENAMELENGTH];
  763: int  outcmd=0;
  764: 
  765: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  766: 
  767: char filelog[FILENAMELENGTH]; /* Log file */
  768: char filerest[FILENAMELENGTH];
  769: char fileregp[FILENAMELENGTH];
  770: char popfile[FILENAMELENGTH];
  771: 
  772: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  773: 
  774: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  775: /* struct timezone tzp; */
  776: /* extern int gettimeofday(); */
  777: struct tm tml, *gmtime(), *localtime();
  778: 
  779: extern time_t time();
  780: 
  781: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  782: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  783: struct tm tm;
  784: 
  785: char strcurr[80], strfor[80];
  786: 
  787: char *endptr;
  788: long lval;
  789: double dval;
  790: 
  791: #define NR_END 1
  792: #define FREE_ARG char*
  793: #define FTOL 1.0e-10
  794: 
  795: #define NRANSI 
  796: #define ITMAX 200 
  797: 
  798: #define TOL 2.0e-4 
  799: 
  800: #define CGOLD 0.3819660 
  801: #define ZEPS 1.0e-10 
  802: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  803: 
  804: #define GOLD 1.618034 
  805: #define GLIMIT 100.0 
  806: #define TINY 1.0e-20 
  807: 
  808: static double maxarg1,maxarg2;
  809: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  810: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  811:   
  812: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  813: #define rint(a) floor(a+0.5)
  814: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  815: #define mytinydouble 1.0e-16
  816: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  817: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  818: /* static double dsqrarg; */
  819: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  820: static double sqrarg;
  821: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  822: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  823: int agegomp= AGEGOMP;
  824: 
  825: int imx; 
  826: int stepm=1;
  827: /* Stepm, step in month: minimum step interpolation*/
  828: 
  829: int estepm;
  830: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  831: 
  832: int m,nb;
  833: long *num;
  834: int firstpass=0, lastpass=4,*cod, *Tage,*cens;
  835: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  836: 		   covariate for which somebody answered excluding 
  837: 		   undefined. Usually 2: 0 and 1. */
  838: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  839: 			     covariate for which somebody answered including 
  840: 			     undefined. Usually 3: -1, 0 and 1. */
  841: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  842: double **pmmij, ***probs;
  843: double *ageexmed,*agecens;
  844: double dateintmean=0;
  845: 
  846: double *weight;
  847: int **s; /* Status */
  848: double *agedc;
  849: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  850: 		  * covar=matrix(0,NCOVMAX,1,n); 
  851: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  852: double  idx; 
  853: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  854: int *Ndum; /** Freq of modality (tricode */
  855: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  856: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  857: double *lsurv, *lpop, *tpop;
  858: 
  859: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  860: double ftolhess; /**< Tolerance for computing hessian */
  861: 
  862: /**************** split *************************/
  863: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  864: {
  865:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  866:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  867:   */ 
  868:   char	*ss;				/* pointer */
  869:   int	l1=0, l2=0;				/* length counters */
  870: 
  871:   l1 = strlen(path );			/* length of path */
  872:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  873:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  874:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  875:     strcpy( name, path );		/* we got the fullname name because no directory */
  876:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  877:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  878:     /* get current working directory */
  879:     /*    extern  char* getcwd ( char *buf , int len);*/
  880: #ifdef WIN32
  881:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  882: #else
  883: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  884: #endif
  885:       return( GLOCK_ERROR_GETCWD );
  886:     }
  887:     /* got dirc from getcwd*/
  888:     printf(" DIRC = %s \n",dirc);
  889:   } else {				/* strip direcotry from path */
  890:     ss++;				/* after this, the filename */
  891:     l2 = strlen( ss );			/* length of filename */
  892:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  893:     strcpy( name, ss );		/* save file name */
  894:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  895:     dirc[l1-l2] = '\0';			/* add zero */
  896:     printf(" DIRC2 = %s \n",dirc);
  897:   }
  898:   /* We add a separator at the end of dirc if not exists */
  899:   l1 = strlen( dirc );			/* length of directory */
  900:   if( dirc[l1-1] != DIRSEPARATOR ){
  901:     dirc[l1] =  DIRSEPARATOR;
  902:     dirc[l1+1] = 0; 
  903:     printf(" DIRC3 = %s \n",dirc);
  904:   }
  905:   ss = strrchr( name, '.' );		/* find last / */
  906:   if (ss >0){
  907:     ss++;
  908:     strcpy(ext,ss);			/* save extension */
  909:     l1= strlen( name);
  910:     l2= strlen(ss)+1;
  911:     strncpy( finame, name, l1-l2);
  912:     finame[l1-l2]= 0;
  913:   }
  914: 
  915:   return( 0 );				/* we're done */
  916: }
  917: 
  918: 
  919: /******************************************/
  920: 
  921: void replace_back_to_slash(char *s, char*t)
  922: {
  923:   int i;
  924:   int lg=0;
  925:   i=0;
  926:   lg=strlen(t);
  927:   for(i=0; i<= lg; i++) {
  928:     (s[i] = t[i]);
  929:     if (t[i]== '\\') s[i]='/';
  930:   }
  931: }
  932: 
  933: char *trimbb(char *out, char *in)
  934: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  935:   char *s;
  936:   s=out;
  937:   while (*in != '\0'){
  938:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  939:       in++;
  940:     }
  941:     *out++ = *in++;
  942:   }
  943:   *out='\0';
  944:   return s;
  945: }
  946: 
  947: /* char *substrchaine(char *out, char *in, char *chain) */
  948: /* { */
  949: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
  950: /*   char *s, *t; */
  951: /*   t=in;s=out; */
  952: /*   while ((*in != *chain) && (*in != '\0')){ */
  953: /*     *out++ = *in++; */
  954: /*   } */
  955: 
  956: /*   /\* *in matches *chain *\/ */
  957: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
  958: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  959: /*   } */
  960: /*   in--; chain--; */
  961: /*   while ( (*in != '\0')){ */
  962: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  963: /*     *out++ = *in++; */
  964: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  965: /*   } */
  966: /*   *out='\0'; */
  967: /*   out=s; */
  968: /*   return out; */
  969: /* } */
  970: char *substrchaine(char *out, char *in, char *chain)
  971: {
  972:   /* Substract chain 'chain' from 'in', return and output 'out' */
  973:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
  974: 
  975:   char *strloc;
  976: 
  977:   strcpy (out, in); 
  978:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
  979:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
  980:   if(strloc != NULL){ 
  981:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
  982:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
  983:     /* strcpy (strloc, strloc +strlen(chain));*/
  984:   }
  985:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
  986:   return out;
  987: }
  988: 
  989: 
  990: char *cutl(char *blocc, char *alocc, char *in, char occ)
  991: {
  992:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
  993:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  994:      gives blocc="abcdef" and alocc="ghi2j".
  995:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  996:   */
  997:   char *s, *t;
  998:   t=in;s=in;
  999:   while ((*in != occ) && (*in != '\0')){
 1000:     *alocc++ = *in++;
 1001:   }
 1002:   if( *in == occ){
 1003:     *(alocc)='\0';
 1004:     s=++in;
 1005:   }
 1006:  
 1007:   if (s == t) {/* occ not found */
 1008:     *(alocc-(in-s))='\0';
 1009:     in=s;
 1010:   }
 1011:   while ( *in != '\0'){
 1012:     *blocc++ = *in++;
 1013:   }
 1014: 
 1015:   *blocc='\0';
 1016:   return t;
 1017: }
 1018: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1019: {
 1020:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1021:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1022:      gives blocc="abcdef2ghi" and alocc="j".
 1023:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1024:   */
 1025:   char *s, *t;
 1026:   t=in;s=in;
 1027:   while (*in != '\0'){
 1028:     while( *in == occ){
 1029:       *blocc++ = *in++;
 1030:       s=in;
 1031:     }
 1032:     *blocc++ = *in++;
 1033:   }
 1034:   if (s == t) /* occ not found */
 1035:     *(blocc-(in-s))='\0';
 1036:   else
 1037:     *(blocc-(in-s)-1)='\0';
 1038:   in=s;
 1039:   while ( *in != '\0'){
 1040:     *alocc++ = *in++;
 1041:   }
 1042: 
 1043:   *alocc='\0';
 1044:   return s;
 1045: }
 1046: 
 1047: int nbocc(char *s, char occ)
 1048: {
 1049:   int i,j=0;
 1050:   int lg=20;
 1051:   i=0;
 1052:   lg=strlen(s);
 1053:   for(i=0; i<= lg; i++) {
 1054:   if  (s[i] == occ ) j++;
 1055:   }
 1056:   return j;
 1057: }
 1058: 
 1059: /* void cutv(char *u,char *v, char*t, char occ) */
 1060: /* { */
 1061: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1062: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1063: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1064: /*   int i,lg,j,p=0; */
 1065: /*   i=0; */
 1066: /*   lg=strlen(t); */
 1067: /*   for(j=0; j<=lg-1; j++) { */
 1068: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1069: /*   } */
 1070: 
 1071: /*   for(j=0; j<p; j++) { */
 1072: /*     (u[j] = t[j]); */
 1073: /*   } */
 1074: /*      u[p]='\0'; */
 1075: 
 1076: /*    for(j=0; j<= lg; j++) { */
 1077: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1078: /*   } */
 1079: /* } */
 1080: 
 1081: #ifdef _WIN32
 1082: char * strsep(char **pp, const char *delim)
 1083: {
 1084:   char *p, *q;
 1085:          
 1086:   if ((p = *pp) == NULL)
 1087:     return 0;
 1088:   if ((q = strpbrk (p, delim)) != NULL)
 1089:   {
 1090:     *pp = q + 1;
 1091:     *q = '\0';
 1092:   }
 1093:   else
 1094:     *pp = 0;
 1095:   return p;
 1096: }
 1097: #endif
 1098: 
 1099: /********************** nrerror ********************/
 1100: 
 1101: void nrerror(char error_text[])
 1102: {
 1103:   fprintf(stderr,"ERREUR ...\n");
 1104:   fprintf(stderr,"%s\n",error_text);
 1105:   exit(EXIT_FAILURE);
 1106: }
 1107: /*********************** vector *******************/
 1108: double *vector(int nl, int nh)
 1109: {
 1110:   double *v;
 1111:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1112:   if (!v) nrerror("allocation failure in vector");
 1113:   return v-nl+NR_END;
 1114: }
 1115: 
 1116: /************************ free vector ******************/
 1117: void free_vector(double*v, int nl, int nh)
 1118: {
 1119:   free((FREE_ARG)(v+nl-NR_END));
 1120: }
 1121: 
 1122: /************************ivector *******************************/
 1123: int *ivector(long nl,long nh)
 1124: {
 1125:   int *v;
 1126:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1127:   if (!v) nrerror("allocation failure in ivector");
 1128:   return v-nl+NR_END;
 1129: }
 1130: 
 1131: /******************free ivector **************************/
 1132: void free_ivector(int *v, long nl, long nh)
 1133: {
 1134:   free((FREE_ARG)(v+nl-NR_END));
 1135: }
 1136: 
 1137: /************************lvector *******************************/
 1138: long *lvector(long nl,long nh)
 1139: {
 1140:   long *v;
 1141:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1142:   if (!v) nrerror("allocation failure in ivector");
 1143:   return v-nl+NR_END;
 1144: }
 1145: 
 1146: /******************free lvector **************************/
 1147: void free_lvector(long *v, long nl, long nh)
 1148: {
 1149:   free((FREE_ARG)(v+nl-NR_END));
 1150: }
 1151: 
 1152: /******************* imatrix *******************************/
 1153: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1154:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1155: { 
 1156:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1157:   int **m; 
 1158:   
 1159:   /* allocate pointers to rows */ 
 1160:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1161:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1162:   m += NR_END; 
 1163:   m -= nrl; 
 1164:   
 1165:   
 1166:   /* allocate rows and set pointers to them */ 
 1167:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1168:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1169:   m[nrl] += NR_END; 
 1170:   m[nrl] -= ncl; 
 1171:   
 1172:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1173:   
 1174:   /* return pointer to array of pointers to rows */ 
 1175:   return m; 
 1176: } 
 1177: 
 1178: /****************** free_imatrix *************************/
 1179: void free_imatrix(m,nrl,nrh,ncl,nch)
 1180:       int **m;
 1181:       long nch,ncl,nrh,nrl; 
 1182:      /* free an int matrix allocated by imatrix() */ 
 1183: { 
 1184:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1185:   free((FREE_ARG) (m+nrl-NR_END)); 
 1186: } 
 1187: 
 1188: /******************* matrix *******************************/
 1189: double **matrix(long nrl, long nrh, long ncl, long nch)
 1190: {
 1191:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1192:   double **m;
 1193: 
 1194:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1195:   if (!m) nrerror("allocation failure 1 in matrix()");
 1196:   m += NR_END;
 1197:   m -= nrl;
 1198: 
 1199:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1200:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1201:   m[nrl] += NR_END;
 1202:   m[nrl] -= ncl;
 1203: 
 1204:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1205:   return m;
 1206:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1207: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1208: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1209:    */
 1210: }
 1211: 
 1212: /*************************free matrix ************************/
 1213: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1214: {
 1215:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1216:   free((FREE_ARG)(m+nrl-NR_END));
 1217: }
 1218: 
 1219: /******************* ma3x *******************************/
 1220: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1221: {
 1222:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1223:   double ***m;
 1224: 
 1225:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1226:   if (!m) nrerror("allocation failure 1 in matrix()");
 1227:   m += NR_END;
 1228:   m -= nrl;
 1229: 
 1230:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1231:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1232:   m[nrl] += NR_END;
 1233:   m[nrl] -= ncl;
 1234: 
 1235:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1236: 
 1237:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1238:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1239:   m[nrl][ncl] += NR_END;
 1240:   m[nrl][ncl] -= nll;
 1241:   for (j=ncl+1; j<=nch; j++) 
 1242:     m[nrl][j]=m[nrl][j-1]+nlay;
 1243:   
 1244:   for (i=nrl+1; i<=nrh; i++) {
 1245:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1246:     for (j=ncl+1; j<=nch; j++) 
 1247:       m[i][j]=m[i][j-1]+nlay;
 1248:   }
 1249:   return m; 
 1250:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1251:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1252:   */
 1253: }
 1254: 
 1255: /*************************free ma3x ************************/
 1256: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1257: {
 1258:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1259:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1260:   free((FREE_ARG)(m+nrl-NR_END));
 1261: }
 1262: 
 1263: /*************** function subdirf ***********/
 1264: char *subdirf(char fileres[])
 1265: {
 1266:   /* Caution optionfilefiname is hidden */
 1267:   strcpy(tmpout,optionfilefiname);
 1268:   strcat(tmpout,"/"); /* Add to the right */
 1269:   strcat(tmpout,fileres);
 1270:   return tmpout;
 1271: }
 1272: 
 1273: /*************** function subdirf2 ***********/
 1274: char *subdirf2(char fileres[], char *preop)
 1275: {
 1276:   
 1277:   /* Caution optionfilefiname is hidden */
 1278:   strcpy(tmpout,optionfilefiname);
 1279:   strcat(tmpout,"/");
 1280:   strcat(tmpout,preop);
 1281:   strcat(tmpout,fileres);
 1282:   return tmpout;
 1283: }
 1284: 
 1285: /*************** function subdirf3 ***********/
 1286: char *subdirf3(char fileres[], char *preop, char *preop2)
 1287: {
 1288:   
 1289:   /* Caution optionfilefiname is hidden */
 1290:   strcpy(tmpout,optionfilefiname);
 1291:   strcat(tmpout,"/");
 1292:   strcat(tmpout,preop);
 1293:   strcat(tmpout,preop2);
 1294:   strcat(tmpout,fileres);
 1295:   return tmpout;
 1296: }
 1297: 
 1298: char *asc_diff_time(long time_sec, char ascdiff[])
 1299: {
 1300:   long sec_left, days, hours, minutes;
 1301:   days = (time_sec) / (60*60*24);
 1302:   sec_left = (time_sec) % (60*60*24);
 1303:   hours = (sec_left) / (60*60) ;
 1304:   sec_left = (sec_left) %(60*60);
 1305:   minutes = (sec_left) /60;
 1306:   sec_left = (sec_left) % (60);
 1307:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1308:   return ascdiff;
 1309: }
 1310: 
 1311: /***************** f1dim *************************/
 1312: extern int ncom; 
 1313: extern double *pcom,*xicom;
 1314: extern double (*nrfunc)(double []); 
 1315:  
 1316: double f1dim(double x) 
 1317: { 
 1318:   int j; 
 1319:   double f;
 1320:   double *xt; 
 1321:  
 1322:   xt=vector(1,ncom); 
 1323:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1324:   f=(*nrfunc)(xt); 
 1325:   free_vector(xt,1,ncom); 
 1326:   return f; 
 1327: } 
 1328: 
 1329: /*****************brent *************************/
 1330: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1331: {
 1332:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1333:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1334:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1335:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1336:    * returned function value. 
 1337:   */
 1338:   int iter; 
 1339:   double a,b,d,etemp;
 1340:   double fu=0,fv,fw,fx;
 1341:   double ftemp=0.;
 1342:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1343:   double e=0.0; 
 1344:  
 1345:   a=(ax < cx ? ax : cx); 
 1346:   b=(ax > cx ? ax : cx); 
 1347:   x=w=v=bx; 
 1348:   fw=fv=fx=(*f)(x); 
 1349:   for (iter=1;iter<=ITMAX;iter++) { 
 1350:     xm=0.5*(a+b); 
 1351:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1352:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1353:     printf(".");fflush(stdout);
 1354:     fprintf(ficlog,".");fflush(ficlog);
 1355: #ifdef DEBUGBRENT
 1356:     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);
 1357:     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);
 1358:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1359: #endif
 1360:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1361:       *xmin=x; 
 1362:       return fx; 
 1363:     } 
 1364:     ftemp=fu;
 1365:     if (fabs(e) > tol1) { 
 1366:       r=(x-w)*(fx-fv); 
 1367:       q=(x-v)*(fx-fw); 
 1368:       p=(x-v)*q-(x-w)*r; 
 1369:       q=2.0*(q-r); 
 1370:       if (q > 0.0) p = -p; 
 1371:       q=fabs(q); 
 1372:       etemp=e; 
 1373:       e=d; 
 1374:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1375: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1376:       else { 
 1377: 	d=p/q; 
 1378: 	u=x+d; 
 1379: 	if (u-a < tol2 || b-u < tol2) 
 1380: 	  d=SIGN(tol1,xm-x); 
 1381:       } 
 1382:     } else { 
 1383:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1384:     } 
 1385:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1386:     fu=(*f)(u); 
 1387:     if (fu <= fx) { 
 1388:       if (u >= x) a=x; else b=x; 
 1389:       SHFT(v,w,x,u) 
 1390:       SHFT(fv,fw,fx,fu) 
 1391:     } else { 
 1392:       if (u < x) a=u; else b=u; 
 1393:       if (fu <= fw || w == x) { 
 1394: 	v=w; 
 1395: 	w=u; 
 1396: 	fv=fw; 
 1397: 	fw=fu; 
 1398:       } else if (fu <= fv || v == x || v == w) { 
 1399: 	v=u; 
 1400: 	fv=fu; 
 1401:       } 
 1402:     } 
 1403:   } 
 1404:   nrerror("Too many iterations in brent"); 
 1405:   *xmin=x; 
 1406:   return fx; 
 1407: } 
 1408: 
 1409: /****************** mnbrak ***********************/
 1410: 
 1411: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1412: 	    double (*func)(double)) 
 1413: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1414: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1415: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1416: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1417:    */
 1418:   double ulim,u,r,q, dum;
 1419:   double fu; 
 1420: 
 1421:   double scale=10.;
 1422:   int iterscale=0;
 1423: 
 1424:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1425:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1426: 
 1427: 
 1428:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1429:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1430:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1431:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1432:   /* } */
 1433: 
 1434:   if (*fb > *fa) { 
 1435:     SHFT(dum,*ax,*bx,dum) 
 1436:     SHFT(dum,*fb,*fa,dum) 
 1437:   } 
 1438:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1439:   *fc=(*func)(*cx); 
 1440: #ifdef DEBUG
 1441:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1442:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1443: #endif
 1444:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1445:     r=(*bx-*ax)*(*fb-*fc); 
 1446:     q=(*bx-*cx)*(*fb-*fa); 
 1447:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1448:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1449:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1450:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1451:       fu=(*func)(u); 
 1452: #ifdef DEBUG
 1453:       /* f(x)=A(x-u)**2+f(u) */
 1454:       double A, fparabu; 
 1455:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1456:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1457:       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);
 1458:       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);
 1459:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1460:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1461:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1462:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1463: #endif 
 1464: #ifdef MNBRAKORIGINAL
 1465: #else
 1466: /*       if (fu > *fc) { */
 1467: /* #ifdef DEBUG */
 1468: /*       printf("mnbrak4  fu > fc \n"); */
 1469: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1470: /* #endif */
 1471: /* 	/\* 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 *\\/  *\/ */
 1472: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1473: /* 	dum=u; /\* Shifting c and u *\/ */
 1474: /* 	u = *cx; */
 1475: /* 	*cx = dum; */
 1476: /* 	dum = fu; */
 1477: /* 	fu = *fc; */
 1478: /* 	*fc =dum; */
 1479: /*       } else { /\* end *\/ */
 1480: /* #ifdef DEBUG */
 1481: /*       printf("mnbrak3  fu < fc \n"); */
 1482: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1483: /* #endif */
 1484: /* 	dum=u; /\* Shifting c and u *\/ */
 1485: /* 	u = *cx; */
 1486: /* 	*cx = dum; */
 1487: /* 	dum = fu; */
 1488: /* 	fu = *fc; */
 1489: /* 	*fc =dum; */
 1490: /*       } */
 1491: #ifdef DEBUG
 1492:       printf("mnbrak34  fu < or >= fc \n");
 1493:       fprintf(ficlog, "mnbrak34 fu < fc\n");
 1494: #endif
 1495:       dum=u; /* Shifting c and u */
 1496:       u = *cx;
 1497:       *cx = dum;
 1498:       dum = fu;
 1499:       fu = *fc;
 1500:       *fc =dum;
 1501: #endif
 1502:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1503: #ifdef DEBUG
 1504:       printf("mnbrak2  u after c but before ulim\n");
 1505:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1506: #endif
 1507:       fu=(*func)(u); 
 1508:       if (fu < *fc) { 
 1509: #ifdef DEBUG
 1510:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1511:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1512: #endif
 1513: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1514: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1515:       } 
 1516:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1517: #ifdef DEBUG
 1518:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1519:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1520: #endif
 1521:       u=ulim; 
 1522:       fu=(*func)(u); 
 1523:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1524: #ifdef DEBUG
 1525:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1526:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1527: #endif
 1528:       u=(*cx)+GOLD*(*cx-*bx); 
 1529:       fu=(*func)(u); 
 1530:     } /* end tests */
 1531:     SHFT(*ax,*bx,*cx,u) 
 1532:     SHFT(*fa,*fb,*fc,fu) 
 1533: #ifdef DEBUG
 1534:       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);
 1535:       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);
 1536: #endif
 1537:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1538: } 
 1539: 
 1540: /*************** linmin ************************/
 1541: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1542: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1543: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1544: the value of func at the returned location p . This is actually all accomplished by calling the
 1545: routines mnbrak and brent .*/
 1546: int ncom; 
 1547: double *pcom,*xicom;
 1548: double (*nrfunc)(double []); 
 1549:  
 1550: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1551: { 
 1552:   double brent(double ax, double bx, double cx, 
 1553: 	       double (*f)(double), double tol, double *xmin); 
 1554:   double f1dim(double x); 
 1555:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1556: 	      double *fc, double (*func)(double)); 
 1557:   int j; 
 1558:   double xx,xmin,bx,ax; 
 1559:   double fx,fb,fa;
 1560: 
 1561:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
 1562:  
 1563:   ncom=n; 
 1564:   pcom=vector(1,n); 
 1565:   xicom=vector(1,n); 
 1566:   nrfunc=func; 
 1567:   for (j=1;j<=n;j++) { 
 1568:     pcom[j]=p[j]; 
 1569:     xicom[j]=xi[j]; 
 1570:   } 
 1571: 
 1572:   /* axs=0.0; */
 1573:   /* xxss=1; /\* 1 and using scale *\/ */
 1574:   xxs=1;
 1575:   /* do{ */
 1576:     ax=0.;
 1577:     xx= xxs;
 1578:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1579:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1580:     /* 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))   */
 1581:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1582:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1583:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1584:     /* 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]]*/
 1585:   /*   if (fx != fx){ */
 1586:   /* 	xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
 1587:   /* 	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); */
 1588:   /*   } */
 1589:   /* }while(fx != fx); */
 1590: 
 1591: #ifdef DEBUGLINMIN
 1592:   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);
 1593: #endif
 1594:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1595:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1596:   /* fmin = f(p[j] + xmin * xi[j]) */
 1597:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1598:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1599: #ifdef DEBUG
 1600:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1601:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1602: #endif
 1603: #ifdef DEBUGLINMIN
 1604:   printf("linmin end ");
 1605: #endif
 1606:   for (j=1;j<=n;j++) { 
 1607:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
 1608:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
 1609:     /* if(xxs <1.0) */
 1610:     /*   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 ); */
 1611:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1612:   } 
 1613:   /* printf("\n"); */
 1614: #ifdef DEBUGLINMIN
 1615:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1616:   for (j=1;j<=n;j++) { 
 1617:     printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1618:     if(j % ncovmodel == 0)
 1619:       printf("\n");
 1620:   }
 1621: #endif
 1622:   free_vector(xicom,1,n); 
 1623:   free_vector(pcom,1,n); 
 1624: } 
 1625: 
 1626: 
 1627: /*************** powell ************************/
 1628: /*
 1629: Minimization of a function func of n variables. Input consists of an initial starting point
 1630: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1631: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1632: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1633: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1634: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1635:  */
 1636: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1637: 	    double (*func)(double [])) 
 1638: { 
 1639:   void linmin(double p[], double xi[], int n, double *fret, 
 1640: 	      double (*func)(double [])); 
 1641:   int i,ibig,j; 
 1642:   double del,t,*pt,*ptt,*xit;
 1643:   double directest;
 1644:   double fp,fptt;
 1645:   double *xits;
 1646:   int niterf, itmp;
 1647: 
 1648:   pt=vector(1,n); 
 1649:   ptt=vector(1,n); 
 1650:   xit=vector(1,n); 
 1651:   xits=vector(1,n); 
 1652:   *fret=(*func)(p); 
 1653:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1654:     rcurr_time = time(NULL);  
 1655:   for (*iter=1;;++(*iter)) { 
 1656:     fp=(*fret); /* From former iteration or initial value */
 1657:     ibig=0; 
 1658:     del=0.0; 
 1659:     rlast_time=rcurr_time;
 1660:     /* (void) gettimeofday(&curr_time,&tzp); */
 1661:     rcurr_time = time(NULL);  
 1662:     curr_time = *localtime(&rcurr_time);
 1663:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1664:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1665: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1666:     for (i=1;i<=n;i++) {
 1667:       printf(" %d %.12f",i, p[i]);
 1668:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1669:       fprintf(ficrespow," %.12lf", p[i]);
 1670:     }
 1671:     printf("\n");
 1672:     fprintf(ficlog,"\n");
 1673:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1674:     if(*iter <=3){
 1675:       tml = *localtime(&rcurr_time);
 1676:       strcpy(strcurr,asctime(&tml));
 1677:       rforecast_time=rcurr_time; 
 1678:       itmp = strlen(strcurr);
 1679:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1680: 	strcurr[itmp-1]='\0';
 1681:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1682:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1683:       for(niterf=10;niterf<=30;niterf+=10){
 1684: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1685: 	forecast_time = *localtime(&rforecast_time);
 1686: 	strcpy(strfor,asctime(&forecast_time));
 1687: 	itmp = strlen(strfor);
 1688: 	if(strfor[itmp-1]=='\n')
 1689: 	strfor[itmp-1]='\0';
 1690: 	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);
 1691: 	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);
 1692:       }
 1693:     }
 1694:     for (i=1;i<=n;i++) { /* For each direction i */
 1695:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1696:       fptt=(*fret); 
 1697: #ifdef DEBUG
 1698: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1699: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1700: #endif
 1701: 	  printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1702:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1703:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1704: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1705:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1706: 	/* because that direction will be replaced unless the gain del is small */
 1707: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1708: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1709: 	/* with the new direction. */
 1710: 	del=fabs(fptt-(*fret)); 
 1711: 	ibig=i; 
 1712:       } 
 1713: #ifdef DEBUG
 1714:       printf("%d %.12e",i,(*fret));
 1715:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1716:       for (j=1;j<=n;j++) {
 1717: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1718: 	printf(" x(%d)=%.12e",j,xit[j]);
 1719: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1720:       }
 1721:       for(j=1;j<=n;j++) {
 1722: 	printf(" p(%d)=%.12e",j,p[j]);
 1723: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1724:       }
 1725:       printf("\n");
 1726:       fprintf(ficlog,"\n");
 1727: #endif
 1728:     } /* end loop on each direction i */
 1729:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1730:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1731:     /* New value of last point Pn is not computed, P(n-1) */
 1732:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1733:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1734:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1735:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1736:       /* decreased of more than 3.84  */
 1737:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1738:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1739:       /* By adding 10 parameters more the gain should be 18.31 */
 1740: 
 1741:       /* Starting the program with initial values given by a former maximization will simply change */
 1742:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1743:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1744:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1745: #ifdef DEBUG
 1746:       int k[2],l;
 1747:       k[0]=1;
 1748:       k[1]=-1;
 1749:       printf("Max: %.12e",(*func)(p));
 1750:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1751:       for (j=1;j<=n;j++) {
 1752: 	printf(" %.12e",p[j]);
 1753: 	fprintf(ficlog," %.12e",p[j]);
 1754:       }
 1755:       printf("\n");
 1756:       fprintf(ficlog,"\n");
 1757:       for(l=0;l<=1;l++) {
 1758: 	for (j=1;j<=n;j++) {
 1759: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1760: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1761: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1762: 	}
 1763: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1764: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1765:       }
 1766: #endif
 1767: 
 1768: 
 1769:       free_vector(xit,1,n); 
 1770:       free_vector(xits,1,n); 
 1771:       free_vector(ptt,1,n); 
 1772:       free_vector(pt,1,n); 
 1773:       return; 
 1774:     } /* enough precision */ 
 1775:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1776:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1777:       ptt[j]=2.0*p[j]-pt[j]; 
 1778:       xit[j]=p[j]-pt[j]; 
 1779:       pt[j]=p[j]; 
 1780:     } 
 1781:     fptt=(*func)(ptt); /* f_3 */
 1782: #ifdef POWELLF1F3
 1783: #else
 1784:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1785: #endif
 1786:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1787:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1788:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1789:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1790:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1791:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1792:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1793: #ifdef NRCORIGINAL
 1794:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1795: #else
 1796:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1797:       t= t- del*SQR(fp-fptt);
 1798: #endif
 1799:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
 1800: #ifdef DEBUG
 1801:       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);
 1802:       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);
 1803:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1804: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1805:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1806: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1807:       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);
 1808:       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);
 1809: #endif
 1810: #ifdef POWELLORIGINAL
 1811:       if (t < 0.0) { /* Then we use it for new direction */
 1812: #else
 1813:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1814: 	printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
 1815:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1816:         fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
 1817:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1818:       } 
 1819:       if (directest < 0.0) { /* Then we use it for new direction */
 1820: #endif
 1821: #ifdef DEBUGLINMIN
 1822: 	printf("Before linmin in direction P%d-P0\n",n);
 1823: 	for (j=1;j<=n;j++) { 
 1824: 	  printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1825: 	  if(j % ncovmodel == 0)
 1826: 	    printf("\n");
 1827: 	}
 1828: #endif
 1829: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 1830: #ifdef DEBUGLINMIN
 1831: 	for (j=1;j<=n;j++) { 
 1832: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1833: 	  if(j % ncovmodel == 0)
 1834: 	    printf("\n");
 1835: 	}
 1836: #endif
 1837: 	for (j=1;j<=n;j++) { 
 1838: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 1839: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 1840: 	}
 1841: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1842: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1843: 
 1844: #ifdef DEBUG
 1845: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1846: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1847: 	for(j=1;j<=n;j++){
 1848: 	  printf(" %.12e",xit[j]);
 1849: 	  fprintf(ficlog," %.12e",xit[j]);
 1850: 	}
 1851: 	printf("\n");
 1852: 	fprintf(ficlog,"\n");
 1853: #endif
 1854:       } /* end of t or directest negative */
 1855: #ifdef POWELLF1F3
 1856: #else
 1857:     } /* end if (fptt < fp)  */
 1858: #endif
 1859:   } /* loop iteration */ 
 1860: } 
 1861: 
 1862: /**** Prevalence limit (stable or period prevalence)  ****************/
 1863: 
 1864: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1865: {
 1866:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1867:      matrix by transitions matrix until convergence is reached */
 1868:   
 1869:   int i, ii,j,k;
 1870:   double min, max, maxmin, maxmax,sumnew=0.;
 1871:   /* double **matprod2(); */ /* test */
 1872:   double **out, cov[NCOVMAX+1], **pmij();
 1873:   double **newm;
 1874:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1875:   
 1876:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1877:     for (j=1;j<=nlstate+ndeath;j++){
 1878:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1879:     }
 1880:   
 1881:   cov[1]=1.;
 1882:   
 1883:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1884:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1885:     newm=savm;
 1886:     /* Covariates have to be included here again */
 1887:     cov[2]=agefin;
 1888:     if(nagesqr==1)
 1889:       cov[3]= agefin*agefin;;
 1890:     for (k=1; k<=cptcovn;k++) {
 1891:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1892:       /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
 1893:     }
 1894:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1895:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
 1896:     for (k=1; k<=cptcovprod;k++) /* Useless */
 1897:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1898:     
 1899:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1900:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1901:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1902:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1903:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1904:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1905:     
 1906:     savm=oldm;
 1907:     oldm=newm;
 1908:     maxmax=0.;
 1909:     for(j=1;j<=nlstate;j++){
 1910:       min=1.;
 1911:       max=0.;
 1912:       for(i=1; i<=nlstate; i++) {
 1913: 	sumnew=0;
 1914: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1915: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1916:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1917: 	max=FMAX(max,prlim[i][j]);
 1918: 	min=FMIN(min,prlim[i][j]);
 1919:       }
 1920:       maxmin=max-min;
 1921:       maxmax=FMAX(maxmax,maxmin);
 1922:     } /* j loop */
 1923:     if(maxmax < ftolpl){
 1924:       return prlim;
 1925:     }
 1926:   } /* age loop */
 1927:   return prlim; /* should not reach here */
 1928: }
 1929: 
 1930: /*************** transition probabilities ***************/ 
 1931: 
 1932: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1933: {
 1934:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1935:      computes the probability to be observed in state j being in state i by appying the
 1936:      model to the ncovmodel covariates (including constant and age).
 1937:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1938:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1939:      ncth covariate in the global vector x is given by the formula:
 1940:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1941:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1942:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1943:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1944:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1945:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1946:   */
 1947:   double s1, lnpijopii;
 1948:   /*double t34;*/
 1949:   int i,j, nc, ii, jj;
 1950: 
 1951:     for(i=1; i<= nlstate; i++){
 1952:       for(j=1; j<i;j++){
 1953: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1954: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1955: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1956: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1957: 	}
 1958: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1959: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1960:       }
 1961:       for(j=i+1; j<=nlstate+ndeath;j++){
 1962: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1963: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1964: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1965: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1966: 	}
 1967: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1968:       }
 1969:     }
 1970:     
 1971:     for(i=1; i<= nlstate; i++){
 1972:       s1=0;
 1973:       for(j=1; j<i; j++){
 1974: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1975: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1976:       }
 1977:       for(j=i+1; j<=nlstate+ndeath; j++){
 1978: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1979: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1980:       }
 1981:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1982:       ps[i][i]=1./(s1+1.);
 1983:       /* Computing other pijs */
 1984:       for(j=1; j<i; j++)
 1985: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1986:       for(j=i+1; j<=nlstate+ndeath; j++)
 1987: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1988:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1989:     } /* end i */
 1990:     
 1991:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1992:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1993: 	ps[ii][jj]=0;
 1994: 	ps[ii][ii]=1;
 1995:       }
 1996:     }
 1997:     
 1998:     
 1999:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2000:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2001:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2002:     /*   } */
 2003:     /*   printf("\n "); */
 2004:     /* } */
 2005:     /* printf("\n ");printf("%lf ",cov[2]);*/
 2006:     /*
 2007:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2008:       goto end;*/
 2009:     return ps;
 2010: }
 2011: 
 2012: /**************** Product of 2 matrices ******************/
 2013: 
 2014: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2015: {
 2016:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2017:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2018:   /* in, b, out are matrice of pointers which should have been initialized 
 2019:      before: only the contents of out is modified. The function returns
 2020:      a pointer to pointers identical to out */
 2021:   int i, j, k;
 2022:   for(i=nrl; i<= nrh; i++)
 2023:     for(k=ncolol; k<=ncoloh; k++){
 2024:       out[i][k]=0.;
 2025:       for(j=ncl; j<=nch; j++)
 2026:   	out[i][k] +=in[i][j]*b[j][k];
 2027:     }
 2028:   return out;
 2029: }
 2030: 
 2031: 
 2032: /************* Higher Matrix Product ***************/
 2033: 
 2034: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2035: {
 2036:   /* Computes the transition matrix starting at age 'age' over 
 2037:      'nhstepm*hstepm*stepm' months (i.e. until
 2038:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2039:      nhstepm*hstepm matrices. 
 2040:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2041:      (typically every 2 years instead of every month which is too big 
 2042:      for the memory).
 2043:      Model is determined by parameters x and covariates have to be 
 2044:      included manually here. 
 2045: 
 2046:      */
 2047: 
 2048:   int i, j, d, h, k;
 2049:   double **out, cov[NCOVMAX+1];
 2050:   double **newm;
 2051:   double agexact;
 2052: 
 2053:   /* Hstepm could be zero and should return the unit matrix */
 2054:   for (i=1;i<=nlstate+ndeath;i++)
 2055:     for (j=1;j<=nlstate+ndeath;j++){
 2056:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2057:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2058:     }
 2059:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2060:   for(h=1; h <=nhstepm; h++){
 2061:     for(d=1; d <=hstepm; d++){
 2062:       newm=savm;
 2063:       /* Covariates have to be included here again */
 2064:       cov[1]=1.;
 2065:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 2066:       cov[2]=agexact;
 2067:       if(nagesqr==1)
 2068: 	cov[3]= agexact*agexact;
 2069:       for (k=1; k<=cptcovn;k++) 
 2070: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 2071:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2072: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2073: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 2074:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2075: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 2076: 
 2077: 
 2078:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2079:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2080:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2081: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2082:       savm=oldm;
 2083:       oldm=newm;
 2084:     }
 2085:     for(i=1; i<=nlstate+ndeath; i++)
 2086:       for(j=1;j<=nlstate+ndeath;j++) {
 2087: 	po[i][j][h]=newm[i][j];
 2088: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2089:       }
 2090:     /*printf("h=%d ",h);*/
 2091:   } /* end h */
 2092: /*     printf("\n H=%d \n",h); */
 2093:   return po;
 2094: }
 2095: 
 2096: #ifdef NLOPT
 2097:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2098:   double fret;
 2099:   double *xt;
 2100:   int j;
 2101:   myfunc_data *d2 = (myfunc_data *) pd;
 2102: /* xt = (p1-1); */
 2103:   xt=vector(1,n); 
 2104:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2105: 
 2106:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2107:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2108:   printf("Function = %.12lf ",fret);
 2109:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2110:   printf("\n");
 2111:  free_vector(xt,1,n);
 2112:   return fret;
 2113: }
 2114: #endif
 2115: 
 2116: /*************** log-likelihood *************/
 2117: double func( double *x)
 2118: {
 2119:   int i, ii, j, k, mi, d, kk;
 2120:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2121:   double **out;
 2122:   double sw; /* Sum of weights */
 2123:   double lli; /* Individual log likelihood */
 2124:   int s1, s2;
 2125:   double bbh, survp;
 2126:   long ipmx;
 2127:   double agexact;
 2128:   /*extern weight */
 2129:   /* We are differentiating ll according to initial status */
 2130:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2131:   /*for(i=1;i<imx;i++) 
 2132:     printf(" %d\n",s[4][i]);
 2133:   */
 2134: 
 2135:   ++countcallfunc;
 2136: 
 2137:   cov[1]=1.;
 2138: 
 2139:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2140: 
 2141:   if(mle==1){
 2142:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2143:       /* Computes the values of the ncovmodel covariates of the model
 2144: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2145: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2146: 	 to be observed in j being in i according to the model.
 2147:        */
 2148:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2149: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2150:       }
 2151:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2152: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2153: 	 has been calculated etc */
 2154:       for(mi=1; mi<= wav[i]-1; mi++){
 2155: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2156: 	  for (j=1;j<=nlstate+ndeath;j++){
 2157: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2158: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2159: 	  }
 2160: 	for(d=0; d<dh[mi][i]; d++){
 2161: 	  newm=savm;
 2162: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2163: 	  cov[2]=agexact;
 2164: 	  if(nagesqr==1)
 2165: 	    cov[3]= agexact*agexact;
 2166: 	  for (kk=1; kk<=cptcovage;kk++) {
 2167: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2168: 	  }
 2169: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2170: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2171: 	  savm=oldm;
 2172: 	  oldm=newm;
 2173: 	} /* end mult */
 2174:       
 2175: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2176: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2177: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2178: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2179: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2180: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2181: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2182: 	 * probability in order to take into account the bias as a fraction of the way
 2183: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2184: 	 * -stepm/2 to stepm/2 .
 2185: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2186: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2187: 	 */
 2188: 	s1=s[mw[mi][i]][i];
 2189: 	s2=s[mw[mi+1][i]][i];
 2190: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2191: 	/* bias bh is positive if real duration
 2192: 	 * is higher than the multiple of stepm and negative otherwise.
 2193: 	 */
 2194: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2195: 	if( s2 > nlstate){ 
 2196: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2197: 	     then the contribution to the likelihood is the probability to 
 2198: 	     die between last step unit time and current  step unit time, 
 2199: 	     which is also equal to probability to die before dh 
 2200: 	     minus probability to die before dh-stepm . 
 2201: 	     In version up to 0.92 likelihood was computed
 2202: 	as if date of death was unknown. Death was treated as any other
 2203: 	health state: the date of the interview describes the actual state
 2204: 	and not the date of a change in health state. The former idea was
 2205: 	to consider that at each interview the state was recorded
 2206: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2207: 	introduced the exact date of death then we should have modified
 2208: 	the contribution of an exact death to the likelihood. This new
 2209: 	contribution is smaller and very dependent of the step unit
 2210: 	stepm. It is no more the probability to die between last interview
 2211: 	and month of death but the probability to survive from last
 2212: 	interview up to one month before death multiplied by the
 2213: 	probability to die within a month. Thanks to Chris
 2214: 	Jackson for correcting this bug.  Former versions increased
 2215: 	mortality artificially. The bad side is that we add another loop
 2216: 	which slows down the processing. The difference can be up to 10%
 2217: 	lower mortality.
 2218: 	  */
 2219: 	/* If, at the beginning of the maximization mostly, the
 2220: 	   cumulative probability or probability to be dead is
 2221: 	   constant (ie = 1) over time d, the difference is equal to
 2222: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2223: 	   s1 at precedent wave, to be dead a month before current
 2224: 	   wave is equal to probability, being at state s1 at
 2225: 	   precedent wave, to be dead at mont of the current
 2226: 	   wave. Then the observed probability (that this person died)
 2227: 	   is null according to current estimated parameter. In fact,
 2228: 	   it should be very low but not zero otherwise the log go to
 2229: 	   infinity.
 2230: 	*/
 2231: /* #ifdef INFINITYORIGINAL */
 2232: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2233: /* #else */
 2234: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2235: /* 	    lli=log(mytinydouble); */
 2236: /* 	  else */
 2237: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2238: /* #endif */
 2239: 	    lli=log(out[s1][s2] - savm[s1][s2]);
 2240: 
 2241: 	} else if  (s2==-2) {
 2242: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2243: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2244: 	  /*survp += out[s1][j]; */
 2245: 	  lli= log(survp);
 2246: 	}
 2247: 	
 2248:  	else if  (s2==-4) { 
 2249: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2250: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2251:  	  lli= log(survp); 
 2252:  	} 
 2253: 
 2254:  	else if  (s2==-5) { 
 2255:  	  for (j=1,survp=0. ; j<=2; j++)  
 2256: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2257:  	  lli= log(survp); 
 2258:  	} 
 2259: 	
 2260: 	else{
 2261: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2262: 	  /*  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 */
 2263: 	} 
 2264: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2265: 	/*if(lli ==000.0)*/
 2266: 	/*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); */
 2267:   	ipmx +=1;
 2268: 	sw += weight[i];
 2269: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2270: 	/* if (lli < log(mytinydouble)){ */
 2271: 	/*   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); */
 2272: 	/*   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]); */
 2273: 	/* } */
 2274:       } /* end of wave */
 2275:     } /* end of individual */
 2276:   }  else if(mle==2){
 2277:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2278:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2279:       for(mi=1; mi<= wav[i]-1; mi++){
 2280: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2281: 	  for (j=1;j<=nlstate+ndeath;j++){
 2282: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2283: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2284: 	  }
 2285: 	for(d=0; d<=dh[mi][i]; d++){
 2286: 	  newm=savm;
 2287: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2288: 	  cov[2]=agexact;
 2289: 	  if(nagesqr==1)
 2290: 	    cov[3]= agexact*agexact;
 2291: 	  for (kk=1; kk<=cptcovage;kk++) {
 2292: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2293: 	  }
 2294: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2295: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2296: 	  savm=oldm;
 2297: 	  oldm=newm;
 2298: 	} /* end mult */
 2299:       
 2300: 	s1=s[mw[mi][i]][i];
 2301: 	s2=s[mw[mi+1][i]][i];
 2302: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2303: 	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 */
 2304: 	ipmx +=1;
 2305: 	sw += weight[i];
 2306: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2307:       } /* end of wave */
 2308:     } /* end of individual */
 2309:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2310:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2311:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2312:       for(mi=1; mi<= wav[i]-1; mi++){
 2313: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2314: 	  for (j=1;j<=nlstate+ndeath;j++){
 2315: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2316: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2317: 	  }
 2318: 	for(d=0; d<dh[mi][i]; d++){
 2319: 	  newm=savm;
 2320: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2321: 	  cov[2]=agexact;
 2322: 	  if(nagesqr==1)
 2323: 	    cov[3]= agexact*agexact;
 2324: 	  for (kk=1; kk<=cptcovage;kk++) {
 2325: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2326: 	  }
 2327: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2328: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2329: 	  savm=oldm;
 2330: 	  oldm=newm;
 2331: 	} /* end mult */
 2332:       
 2333: 	s1=s[mw[mi][i]][i];
 2334: 	s2=s[mw[mi+1][i]][i];
 2335: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2336: 	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 */
 2337: 	ipmx +=1;
 2338: 	sw += weight[i];
 2339: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2340:       } /* end of wave */
 2341:     } /* end of individual */
 2342:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2343:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2344:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2345:       for(mi=1; mi<= wav[i]-1; mi++){
 2346: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2347: 	  for (j=1;j<=nlstate+ndeath;j++){
 2348: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2349: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2350: 	  }
 2351: 	for(d=0; d<dh[mi][i]; d++){
 2352: 	  newm=savm;
 2353: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2354: 	  cov[2]=agexact;
 2355: 	  if(nagesqr==1)
 2356: 	    cov[3]= agexact*agexact;
 2357: 	  for (kk=1; kk<=cptcovage;kk++) {
 2358: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2359: 	  }
 2360: 	
 2361: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2362: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2363: 	  savm=oldm;
 2364: 	  oldm=newm;
 2365: 	} /* end mult */
 2366:       
 2367: 	s1=s[mw[mi][i]][i];
 2368: 	s2=s[mw[mi+1][i]][i];
 2369: 	if( s2 > nlstate){ 
 2370: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2371: 	}else{
 2372: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2373: 	}
 2374: 	ipmx +=1;
 2375: 	sw += weight[i];
 2376: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2377: /* 	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]); */
 2378:       } /* end of wave */
 2379:     } /* end of individual */
 2380:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2381:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2382:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2383:       for(mi=1; mi<= wav[i]-1; mi++){
 2384: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2385: 	  for (j=1;j<=nlstate+ndeath;j++){
 2386: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2387: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2388: 	  }
 2389: 	for(d=0; d<dh[mi][i]; d++){
 2390: 	  newm=savm;
 2391: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2392: 	  cov[2]=agexact;
 2393: 	  if(nagesqr==1)
 2394: 	    cov[3]= agexact*agexact;
 2395: 	  for (kk=1; kk<=cptcovage;kk++) {
 2396: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2397: 	  }
 2398: 	
 2399: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2400: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2401: 	  savm=oldm;
 2402: 	  oldm=newm;
 2403: 	} /* end mult */
 2404:       
 2405: 	s1=s[mw[mi][i]][i];
 2406: 	s2=s[mw[mi+1][i]][i];
 2407: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2408: 	ipmx +=1;
 2409: 	sw += weight[i];
 2410: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2411: 	/*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]);*/
 2412:       } /* end of wave */
 2413:     } /* end of individual */
 2414:   } /* End of if */
 2415:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2416:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2417:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2418:   return -l;
 2419: }
 2420: 
 2421: /*************** log-likelihood *************/
 2422: double funcone( double *x)
 2423: {
 2424:   /* Same as likeli but slower because of a lot of printf and if */
 2425:   int i, ii, j, k, mi, d, kk;
 2426:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2427:   double **out;
 2428:   double lli; /* Individual log likelihood */
 2429:   double llt;
 2430:   int s1, s2;
 2431:   double bbh, survp;
 2432:   double agexact;
 2433:   /*extern weight */
 2434:   /* We are differentiating ll according to initial status */
 2435:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2436:   /*for(i=1;i<imx;i++) 
 2437:     printf(" %d\n",s[4][i]);
 2438:   */
 2439:   cov[1]=1.;
 2440: 
 2441:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2442: 
 2443:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2444:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2445:     for(mi=1; mi<= wav[i]-1; mi++){
 2446:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2447: 	for (j=1;j<=nlstate+ndeath;j++){
 2448: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2449: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2450: 	}
 2451:       for(d=0; d<dh[mi][i]; d++){
 2452: 	newm=savm;
 2453: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2454: 	cov[2]=agexact;
 2455: 	if(nagesqr==1)
 2456: 	  cov[3]= agexact*agexact;
 2457: 	for (kk=1; kk<=cptcovage;kk++) {
 2458: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2459: 	}
 2460: 
 2461: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2462: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2463: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2464: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2465: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2466: 	savm=oldm;
 2467: 	oldm=newm;
 2468:       } /* end mult */
 2469:       
 2470:       s1=s[mw[mi][i]][i];
 2471:       s2=s[mw[mi+1][i]][i];
 2472:       bbh=(double)bh[mi][i]/(double)stepm; 
 2473:       /* bias is positive if real duration
 2474:        * is higher than the multiple of stepm and negative otherwise.
 2475:        */
 2476:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2477: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2478:       } else if  (s2==-2) {
 2479: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2480: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2481: 	lli= log(survp);
 2482:       }else if (mle==1){
 2483: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2484:       } else if(mle==2){
 2485: 	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 */
 2486:       } else if(mle==3){  /* exponential inter-extrapolation */
 2487: 	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 */
 2488:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2489: 	lli=log(out[s1][s2]); /* Original formula */
 2490:       } else{  /* mle=0 back to 1 */
 2491: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2492: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2493:       } /* End of if */
 2494:       ipmx +=1;
 2495:       sw += weight[i];
 2496:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2497:       /*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]); */
 2498:       if(globpr){
 2499: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2500:  %11.6f %11.6f %11.6f ", \
 2501: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2502: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2503: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2504: 	  llt +=ll[k]*gipmx/gsw;
 2505: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2506: 	}
 2507: 	fprintf(ficresilk," %10.6f\n", -llt);
 2508:       }
 2509:     } /* end of wave */
 2510:   } /* end of individual */
 2511:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2512:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2513:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2514:   if(globpr==0){ /* First time we count the contributions and weights */
 2515:     gipmx=ipmx;
 2516:     gsw=sw;
 2517:   }
 2518:   return -l;
 2519: }
 2520: 
 2521: 
 2522: /*************** function likelione ***********/
 2523: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2524: {
 2525:   /* This routine should help understanding what is done with 
 2526:      the selection of individuals/waves and
 2527:      to check the exact contribution to the likelihood.
 2528:      Plotting could be done.
 2529:    */
 2530:   int k;
 2531: 
 2532:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2533:     strcpy(fileresilk,"ilk"); 
 2534:     strcat(fileresilk,fileres);
 2535:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2536:       printf("Problem with resultfile: %s\n", fileresilk);
 2537:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2538:     }
 2539:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
 2540:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2541:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2542:     for(k=1; k<=nlstate; k++) 
 2543:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2544:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2545:   }
 2546: 
 2547:   *fretone=(*funcone)(p);
 2548:   if(*globpri !=0){
 2549:     fclose(ficresilk);
 2550:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2551:     fflush(fichtm); 
 2552:   } 
 2553:   return;
 2554: }
 2555: 
 2556: 
 2557: /*********** Maximum Likelihood Estimation ***************/
 2558: 
 2559: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2560: {
 2561:   int i,j, iter=0;
 2562:   double **xi;
 2563:   double fret;
 2564:   double fretone; /* Only one call to likelihood */
 2565:   /*  char filerespow[FILENAMELENGTH];*/
 2566: 
 2567: #ifdef NLOPT
 2568:   int creturn;
 2569:   nlopt_opt opt;
 2570:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2571:   double *lb;
 2572:   double minf; /* the minimum objective value, upon return */
 2573:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2574:   myfunc_data dinst, *d = &dinst;
 2575: #endif
 2576: 
 2577: 
 2578:   xi=matrix(1,npar,1,npar);
 2579:   for (i=1;i<=npar;i++)
 2580:     for (j=1;j<=npar;j++)
 2581:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2582:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2583:   strcpy(filerespow,"pow"); 
 2584:   strcat(filerespow,fileres);
 2585:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2586:     printf("Problem with resultfile: %s\n", filerespow);
 2587:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2588:   }
 2589:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2590:   for (i=1;i<=nlstate;i++)
 2591:     for(j=1;j<=nlstate+ndeath;j++)
 2592:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2593:   fprintf(ficrespow,"\n");
 2594: #ifdef POWELL
 2595:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2596: #endif
 2597: 
 2598: #ifdef NLOPT
 2599: #ifdef NEWUOA
 2600:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2601: #else
 2602:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2603: #endif
 2604:   lb=vector(0,npar-1);
 2605:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2606:   nlopt_set_lower_bounds(opt, lb);
 2607:   nlopt_set_initial_step1(opt, 0.1);
 2608:   
 2609:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2610:   d->function = func;
 2611:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2612:   nlopt_set_min_objective(opt, myfunc, d);
 2613:   nlopt_set_xtol_rel(opt, ftol);
 2614:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2615:     printf("nlopt failed! %d\n",creturn); 
 2616:   }
 2617:   else {
 2618:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2619:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2620:     iter=1; /* not equal */
 2621:   }
 2622:   nlopt_destroy(opt);
 2623: #endif
 2624:   free_matrix(xi,1,npar,1,npar);
 2625:   fclose(ficrespow);
 2626:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2627:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2628:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2629: 
 2630: }
 2631: 
 2632: /**** Computes Hessian and covariance matrix ***/
 2633: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2634: {
 2635:   double  **a,**y,*x,pd;
 2636:   double **hess;
 2637:   int i, j;
 2638:   int *indx;
 2639: 
 2640:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2641:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2642:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2643:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2644:   double gompertz(double p[]);
 2645:   hess=matrix(1,npar,1,npar);
 2646: 
 2647:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2648:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2649:   for (i=1;i<=npar;i++){
 2650:     printf("%d",i);fflush(stdout);
 2651:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2652:    
 2653:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2654:     
 2655:     /*  printf(" %f ",p[i]);
 2656: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2657:   }
 2658:   
 2659:   for (i=1;i<=npar;i++) {
 2660:     for (j=1;j<=npar;j++)  {
 2661:       if (j>i) { 
 2662: 	printf(".%d%d",i,j);fflush(stdout);
 2663: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2664: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2665: 	
 2666: 	hess[j][i]=hess[i][j];    
 2667: 	/*printf(" %lf ",hess[i][j]);*/
 2668:       }
 2669:     }
 2670:   }
 2671:   printf("\n");
 2672:   fprintf(ficlog,"\n");
 2673: 
 2674:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2675:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2676:   
 2677:   a=matrix(1,npar,1,npar);
 2678:   y=matrix(1,npar,1,npar);
 2679:   x=vector(1,npar);
 2680:   indx=ivector(1,npar);
 2681:   for (i=1;i<=npar;i++)
 2682:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2683:   ludcmp(a,npar,indx,&pd);
 2684: 
 2685:   for (j=1;j<=npar;j++) {
 2686:     for (i=1;i<=npar;i++) x[i]=0;
 2687:     x[j]=1;
 2688:     lubksb(a,npar,indx,x);
 2689:     for (i=1;i<=npar;i++){ 
 2690:       matcov[i][j]=x[i];
 2691:     }
 2692:   }
 2693: 
 2694:   printf("\n#Hessian matrix#\n");
 2695:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2696:   for (i=1;i<=npar;i++) { 
 2697:     for (j=1;j<=npar;j++) { 
 2698:       printf("%.3e ",hess[i][j]);
 2699:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2700:     }
 2701:     printf("\n");
 2702:     fprintf(ficlog,"\n");
 2703:   }
 2704: 
 2705:   /* Recompute Inverse */
 2706:   for (i=1;i<=npar;i++)
 2707:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2708:   ludcmp(a,npar,indx,&pd);
 2709: 
 2710:   /*  printf("\n#Hessian matrix recomputed#\n");
 2711: 
 2712:   for (j=1;j<=npar;j++) {
 2713:     for (i=1;i<=npar;i++) x[i]=0;
 2714:     x[j]=1;
 2715:     lubksb(a,npar,indx,x);
 2716:     for (i=1;i<=npar;i++){ 
 2717:       y[i][j]=x[i];
 2718:       printf("%.3e ",y[i][j]);
 2719:       fprintf(ficlog,"%.3e ",y[i][j]);
 2720:     }
 2721:     printf("\n");
 2722:     fprintf(ficlog,"\n");
 2723:   }
 2724:   */
 2725: 
 2726:   free_matrix(a,1,npar,1,npar);
 2727:   free_matrix(y,1,npar,1,npar);
 2728:   free_vector(x,1,npar);
 2729:   free_ivector(indx,1,npar);
 2730:   free_matrix(hess,1,npar,1,npar);
 2731: 
 2732: 
 2733: }
 2734: 
 2735: /*************** hessian matrix ****************/
 2736: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2737: {
 2738:   int i;
 2739:   int l=1, lmax=20;
 2740:   double k1,k2;
 2741:   double p2[MAXPARM+1]; /* identical to x */
 2742:   double res;
 2743:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2744:   double fx;
 2745:   int k=0,kmax=10;
 2746:   double l1;
 2747: 
 2748:   fx=func(x);
 2749:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2750:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2751:     l1=pow(10,l);
 2752:     delts=delt;
 2753:     for(k=1 ; k <kmax; k=k+1){
 2754:       delt = delta*(l1*k);
 2755:       p2[theta]=x[theta] +delt;
 2756:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2757:       p2[theta]=x[theta]-delt;
 2758:       k2=func(p2)-fx;
 2759:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2760:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2761:       
 2762: #ifdef DEBUGHESS
 2763:       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);
 2764:       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);
 2765: #endif
 2766:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2767:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2768: 	k=kmax;
 2769:       }
 2770:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2771: 	k=kmax; l=lmax*10;
 2772:       }
 2773:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2774: 	delts=delt;
 2775:       }
 2776:     }
 2777:   }
 2778:   delti[theta]=delts;
 2779:   return res; 
 2780:   
 2781: }
 2782: 
 2783: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2784: {
 2785:   int i;
 2786:   int l=1, lmax=20;
 2787:   double k1,k2,k3,k4,res,fx;
 2788:   double p2[MAXPARM+1];
 2789:   int k;
 2790: 
 2791:   fx=func(x);
 2792:   for (k=1; k<=2; k++) {
 2793:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2794:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2795:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2796:     k1=func(p2)-fx;
 2797:   
 2798:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2799:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2800:     k2=func(p2)-fx;
 2801:   
 2802:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2803:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2804:     k3=func(p2)-fx;
 2805:   
 2806:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2807:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2808:     k4=func(p2)-fx;
 2809:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2810: #ifdef DEBUG
 2811:     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);
 2812:     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);
 2813: #endif
 2814:   }
 2815:   return res;
 2816: }
 2817: 
 2818: /************** Inverse of matrix **************/
 2819: void ludcmp(double **a, int n, int *indx, double *d) 
 2820: { 
 2821:   int i,imax,j,k; 
 2822:   double big,dum,sum,temp; 
 2823:   double *vv; 
 2824:  
 2825:   vv=vector(1,n); 
 2826:   *d=1.0; 
 2827:   for (i=1;i<=n;i++) { 
 2828:     big=0.0; 
 2829:     for (j=1;j<=n;j++) 
 2830:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2831:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2832:     vv[i]=1.0/big; 
 2833:   } 
 2834:   for (j=1;j<=n;j++) { 
 2835:     for (i=1;i<j;i++) { 
 2836:       sum=a[i][j]; 
 2837:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2838:       a[i][j]=sum; 
 2839:     } 
 2840:     big=0.0; 
 2841:     for (i=j;i<=n;i++) { 
 2842:       sum=a[i][j]; 
 2843:       for (k=1;k<j;k++) 
 2844: 	sum -= a[i][k]*a[k][j]; 
 2845:       a[i][j]=sum; 
 2846:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2847: 	big=dum; 
 2848: 	imax=i; 
 2849:       } 
 2850:     } 
 2851:     if (j != imax) { 
 2852:       for (k=1;k<=n;k++) { 
 2853: 	dum=a[imax][k]; 
 2854: 	a[imax][k]=a[j][k]; 
 2855: 	a[j][k]=dum; 
 2856:       } 
 2857:       *d = -(*d); 
 2858:       vv[imax]=vv[j]; 
 2859:     } 
 2860:     indx[j]=imax; 
 2861:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2862:     if (j != n) { 
 2863:       dum=1.0/(a[j][j]); 
 2864:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2865:     } 
 2866:   } 
 2867:   free_vector(vv,1,n);  /* Doesn't work */
 2868: ;
 2869: } 
 2870: 
 2871: void lubksb(double **a, int n, int *indx, double b[]) 
 2872: { 
 2873:   int i,ii=0,ip,j; 
 2874:   double sum; 
 2875:  
 2876:   for (i=1;i<=n;i++) { 
 2877:     ip=indx[i]; 
 2878:     sum=b[ip]; 
 2879:     b[ip]=b[i]; 
 2880:     if (ii) 
 2881:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2882:     else if (sum) ii=i; 
 2883:     b[i]=sum; 
 2884:   } 
 2885:   for (i=n;i>=1;i--) { 
 2886:     sum=b[i]; 
 2887:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2888:     b[i]=sum/a[i][i]; 
 2889:   } 
 2890: } 
 2891: 
 2892: void pstamp(FILE *fichier)
 2893: {
 2894:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2895: }
 2896: 
 2897: /************ Frequencies ********************/
 2898: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
 2899: {  /* Some frequencies */
 2900:   
 2901:   int i, m, jk, j1, bool, z1,j;
 2902:   int first;
 2903:   double ***freq; /* Frequencies */
 2904:   double *pp, **prop;
 2905:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2906:   char fileresp[FILENAMELENGTH];
 2907:   
 2908:   pp=vector(1,nlstate);
 2909:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2910:   strcpy(fileresp,"p");
 2911:   strcat(fileresp,fileres);
 2912:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2913:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2914:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2915:     exit(0);
 2916:   }
 2917:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2918:   j1=0;
 2919:   
 2920:   j=cptcoveff;
 2921:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2922: 
 2923:   first=1;
 2924: 
 2925:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2926:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2927:   /*    j1++; */
 2928:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2929:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2930: 	scanf("%d", i);*/
 2931:       for (i=-5; i<=nlstate+ndeath; i++)  
 2932: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2933: 	  for(m=iagemin; m <= iagemax+3; m++)
 2934: 	    freq[i][jk][m]=0;
 2935:       
 2936:       for (i=1; i<=nlstate; i++)  
 2937: 	for(m=iagemin; m <= iagemax+3; m++)
 2938: 	  prop[i][m]=0;
 2939:       
 2940:       dateintsum=0;
 2941:       k2cpt=0;
 2942:       for (i=1; i<=imx; i++) {
 2943: 	bool=1;
 2944: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2945: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2946:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2947:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2948:               bool=0;
 2949:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
 2950:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2951:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2952:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2953:             } 
 2954: 	}
 2955:  
 2956: 	if (bool==1){
 2957: 	  for(m=firstpass; m<=lastpass; m++){
 2958: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2959: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2960: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2961: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2962: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2963: 	      if (m<lastpass) {
 2964: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2965: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2966: 	      }
 2967: 	      
 2968: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2969: 		dateintsum=dateintsum+k2;
 2970: 		k2cpt++;
 2971: 	      }
 2972: 	      /*}*/
 2973: 	  }
 2974: 	}
 2975:       } /* end i */
 2976:        
 2977:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2978:       pstamp(ficresp);
 2979:       if  (cptcovn>0) {
 2980: 	fprintf(ficresp, "\n#********** Variable "); 
 2981: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2982: 	fprintf(ficresp, "**********\n#");
 2983: 	fprintf(ficlog, "\n#********** Variable "); 
 2984: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2985: 	fprintf(ficlog, "**********\n#");
 2986:       }
 2987:       for(i=1; i<=nlstate;i++) 
 2988: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2989:       fprintf(ficresp, "\n");
 2990:       
 2991:       for(i=iagemin; i <= iagemax+3; i++){
 2992: 	if(i==iagemax+3){
 2993: 	  fprintf(ficlog,"Total");
 2994: 	}else{
 2995: 	  if(first==1){
 2996: 	    first=0;
 2997: 	    printf("See log file for details...\n");
 2998: 	  }
 2999: 	  fprintf(ficlog,"Age %d", i);
 3000: 	}
 3001: 	for(jk=1; jk <=nlstate ; jk++){
 3002: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 3003: 	    pp[jk] += freq[jk][m][i]; 
 3004: 	}
 3005: 	for(jk=1; jk <=nlstate ; jk++){
 3006: 	  for(m=-1, pos=0; m <=0 ; m++)
 3007: 	    pos += freq[jk][m][i];
 3008: 	  if(pp[jk]>=1.e-10){
 3009: 	    if(first==1){
 3010: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3011: 	    }
 3012: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3013: 	  }else{
 3014: 	    if(first==1)
 3015: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3016: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3017: 	  }
 3018: 	}
 3019: 
 3020: 	for(jk=1; jk <=nlstate ; jk++){
 3021: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 3022: 	    pp[jk] += freq[jk][m][i];
 3023: 	}	
 3024: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 3025: 	  pos += pp[jk];
 3026: 	  posprop += prop[jk][i];
 3027: 	}
 3028: 	for(jk=1; jk <=nlstate ; jk++){
 3029: 	  if(pos>=1.e-5){
 3030: 	    if(first==1)
 3031: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3032: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3033: 	  }else{
 3034: 	    if(first==1)
 3035: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3036: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3037: 	  }
 3038: 	  if( i <= iagemax){
 3039: 	    if(pos>=1.e-5){
 3040: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3041: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 3042: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 3043: 	    }
 3044: 	    else
 3045: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 3046: 	  }
 3047: 	}
 3048: 	
 3049: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 3050: 	  for(m=-1; m <=nlstate+ndeath; m++)
 3051: 	    if(freq[jk][m][i] !=0 ) {
 3052: 	    if(first==1)
 3053: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 3054: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 3055: 	    }
 3056: 	if(i <= iagemax)
 3057: 	  fprintf(ficresp,"\n");
 3058: 	if(first==1)
 3059: 	  printf("Others in log...\n");
 3060: 	fprintf(ficlog,"\n");
 3061:       }
 3062:       /*}*/
 3063:   }
 3064:   dateintmean=dateintsum/k2cpt; 
 3065:  
 3066:   fclose(ficresp);
 3067:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 3068:   free_vector(pp,1,nlstate);
 3069:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 3070:   /* End of Freq */
 3071: }
 3072: 
 3073: /************ Prevalence ********************/
 3074: 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)
 3075: {  
 3076:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3077:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3078:      We still use firstpass and lastpass as another selection.
 3079:   */
 3080:  
 3081:   int i, m, jk, j1, bool, z1,j;
 3082: 
 3083:   double **prop;
 3084:   double posprop; 
 3085:   double  y2; /* in fractional years */
 3086:   int iagemin, iagemax;
 3087:   int first; /** to stop verbosity which is redirected to log file */
 3088: 
 3089:   iagemin= (int) agemin;
 3090:   iagemax= (int) agemax;
 3091:   /*pp=vector(1,nlstate);*/
 3092:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 3093:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3094:   j1=0;
 3095:   
 3096:   /*j=cptcoveff;*/
 3097:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3098:   
 3099:   first=1;
 3100:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3101:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 3102:       j1++;*/
 3103:       
 3104:       for (i=1; i<=nlstate; i++)  
 3105: 	for(m=iagemin; m <= iagemax+3; m++)
 3106: 	  prop[i][m]=0.0;
 3107:      
 3108:       for (i=1; i<=imx; i++) { /* Each individual */
 3109: 	bool=1;
 3110: 	if  (cptcovn>0) {
 3111: 	  for (z1=1; z1<=cptcoveff; z1++) 
 3112: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 3113: 	      bool=0;
 3114: 	} 
 3115: 	if (bool==1) { 
 3116: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 3117: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3118: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3119: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3120: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3121: 	      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); 
 3122:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 3123: 		/*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]]);*/
 3124:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 3125:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 3126:  	      } 
 3127: 	    }
 3128: 	  } /* end selection of waves */
 3129: 	}
 3130:       }
 3131:       for(i=iagemin; i <= iagemax+3; i++){  
 3132:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 3133:  	  posprop += prop[jk][i]; 
 3134:  	} 
 3135: 	
 3136:  	for(jk=1; jk <=nlstate ; jk++){	    
 3137:  	  if( i <=  iagemax){ 
 3138:  	    if(posprop>=1.e-5){ 
 3139:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 3140:  	    } else{
 3141: 	      if(first==1){
 3142: 		first=0;
 3143: 		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]);
 3144: 	      }
 3145: 	    }
 3146:  	  } 
 3147:  	}/* end jk */ 
 3148:       }/* end i */ 
 3149:     /*} *//* end i1 */
 3150:   } /* end j1 */
 3151:   
 3152:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 3153:   /*free_vector(pp,1,nlstate);*/
 3154:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 3155: }  /* End of prevalence */
 3156: 
 3157: /************* Waves Concatenation ***************/
 3158: 
 3159: 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)
 3160: {
 3161:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 3162:      Death is a valid wave (if date is known).
 3163:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 3164:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3165:      and mw[mi+1][i]. dh depends on stepm.
 3166:      */
 3167: 
 3168:   int i, mi, m;
 3169:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 3170:      double sum=0., jmean=0.;*/
 3171:   int first;
 3172:   int j, k=0,jk, ju, jl;
 3173:   double sum=0.;
 3174:   first=0;
 3175:   jmin=100000;
 3176:   jmax=-1;
 3177:   jmean=0.;
 3178:   for(i=1; i<=imx; i++){
 3179:     mi=0;
 3180:     m=firstpass;
 3181:     while(s[m][i] <= nlstate){
 3182:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 3183: 	mw[++mi][i]=m;
 3184:       if(m >=lastpass)
 3185: 	break;
 3186:       else
 3187: 	m++;
 3188:     }/* end while */
 3189:     if (s[m][i] > nlstate){
 3190:       mi++;	/* Death is another wave */
 3191:       /* if(mi==0)  never been interviewed correctly before death */
 3192: 	 /* Only death is a correct wave */
 3193:       mw[mi][i]=m;
 3194:     }
 3195: 
 3196:     wav[i]=mi;
 3197:     if(mi==0){
 3198:       nbwarn++;
 3199:       if(first==0){
 3200: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 3201: 	first=1;
 3202:       }
 3203:       if(first==1){
 3204: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 3205:       }
 3206:     } /* end mi==0 */
 3207:   } /* End individuals */
 3208: 
 3209:   for(i=1; i<=imx; i++){
 3210:     for(mi=1; mi<wav[i];mi++){
 3211:       if (stepm <=0)
 3212: 	dh[mi][i]=1;
 3213:       else{
 3214: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 3215: 	  if (agedc[i] < 2*AGESUP) {
 3216: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 3217: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 3218: 	    else if(j<0){
 3219: 	      nberr++;
 3220: 	      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]);
 3221: 	      j=1; /* Temporary Dangerous patch */
 3222: 	      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);
 3223: 	      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]);
 3224: 	      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);
 3225: 	    }
 3226: 	    k=k+1;
 3227: 	    if (j >= jmax){
 3228: 	      jmax=j;
 3229: 	      ijmax=i;
 3230: 	    }
 3231: 	    if (j <= jmin){
 3232: 	      jmin=j;
 3233: 	      ijmin=i;
 3234: 	    }
 3235: 	    sum=sum+j;
 3236: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 3237: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 3238: 	  }
 3239: 	}
 3240: 	else{
 3241: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 3242: /* 	  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]); */
 3243: 
 3244: 	  k=k+1;
 3245: 	  if (j >= jmax) {
 3246: 	    jmax=j;
 3247: 	    ijmax=i;
 3248: 	  }
 3249: 	  else if (j <= jmin){
 3250: 	    jmin=j;
 3251: 	    ijmin=i;
 3252: 	  }
 3253: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 3254: 	  /*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]);*/
 3255: 	  if(j<0){
 3256: 	    nberr++;
 3257: 	    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]);
 3258: 	    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]);
 3259: 	  }
 3260: 	  sum=sum+j;
 3261: 	}
 3262: 	jk= j/stepm;
 3263: 	jl= j -jk*stepm;
 3264: 	ju= j -(jk+1)*stepm;
 3265: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 3266: 	  if(jl==0){
 3267: 	    dh[mi][i]=jk;
 3268: 	    bh[mi][i]=0;
 3269: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 3270: 		  * to avoid the price of an extra matrix product in likelihood */
 3271: 	    dh[mi][i]=jk+1;
 3272: 	    bh[mi][i]=ju;
 3273: 	  }
 3274: 	}else{
 3275: 	  if(jl <= -ju){
 3276: 	    dh[mi][i]=jk;
 3277: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 3278: 				 * is higher than the multiple of stepm and negative otherwise.
 3279: 				 */
 3280: 	  }
 3281: 	  else{
 3282: 	    dh[mi][i]=jk+1;
 3283: 	    bh[mi][i]=ju;
 3284: 	  }
 3285: 	  if(dh[mi][i]==0){
 3286: 	    dh[mi][i]=1; /* At least one step */
 3287: 	    bh[mi][i]=ju; /* At least one step */
 3288: 	    /*  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);*/
 3289: 	  }
 3290: 	} /* end if mle */
 3291:       }
 3292:     } /* end wave */
 3293:   }
 3294:   jmean=sum/k;
 3295:   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);
 3296:   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);
 3297:  }
 3298: 
 3299: /*********** Tricode ****************************/
 3300: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 3301: {
 3302:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 3303:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 3304:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 3305:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 3306:    * nbcode[Tvar[j]][1]= 
 3307:   */
 3308: 
 3309:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 3310:   int modmaxcovj=0; /* Modality max of covariates j */
 3311:   int cptcode=0; /* Modality max of covariates j */
 3312:   int modmincovj=0; /* Modality min of covariates j */
 3313: 
 3314: 
 3315:   cptcoveff=0; 
 3316:  
 3317:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 3318: 
 3319:   /* Loop on covariates without age and products */
 3320:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 3321:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 3322:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 3323: 			       modality of this covariate Vj*/ 
 3324:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 3325: 				    * If product of Vn*Vm, still boolean *:
 3326: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 3327: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 3328:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 3329: 				      modality of the nth covariate of individual i. */
 3330:       if (ij > modmaxcovj)
 3331:         modmaxcovj=ij; 
 3332:       else if (ij < modmincovj) 
 3333: 	modmincovj=ij; 
 3334:       if ((ij < -1) && (ij > NCOVMAX)){
 3335: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 3336: 	exit(1);
 3337:       }else
 3338:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 3339:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 3340:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 3341:       /* getting the maximum value of the modality of the covariate
 3342: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 3343: 	 female is 1, then modmaxcovj=1.*/
 3344:     } /* end for loop on individuals i */
 3345:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3346:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3347:     cptcode=modmaxcovj;
 3348:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3349:    /*for (i=0; i<=cptcode; i++) {*/
 3350:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 3351:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 3352:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 3353:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 3354: 	if( k != -1){
 3355: 	  ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 3356: 			     covariate for which somebody answered excluding 
 3357: 			     undefined. Usually 2: 0 and 1. */
 3358: 	}
 3359: 	ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 3360: 			     covariate for which somebody answered including 
 3361: 			     undefined. Usually 3: -1, 0 and 1. */
 3362:       }
 3363:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3364: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3365:     } /* Ndum[-1] number of undefined modalities */
 3366: 
 3367:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3368:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 3369:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 3370:        modmincovj=3; modmaxcovj = 7;
 3371:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 3372:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 3373:        defining two dummy variables: variables V1_1 and V1_2.
 3374:        nbcode[Tvar[j]][ij]=k;
 3375:        nbcode[Tvar[j]][1]=0;
 3376:        nbcode[Tvar[j]][2]=1;
 3377:        nbcode[Tvar[j]][3]=2;
 3378:     */
 3379:     ij=0; /* ij is similar to i but can jumps over null modalities */
 3380:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 to 1*/
 3381:     	if (Ndum[i] == 0) { /* If at least one individual responded to this modality k */
 3382: 	  break;
 3383: 	}
 3384: 	ij++;
 3385: 	nbcode[Tvar[j]][ij]=i;  /* stores the original modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
 3386: 	cptcode = ij; /* New max modality for covar j */
 3387:     } /* end of loop on modality i=-1 to 1 or more */
 3388:       
 3389:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 3390:     /* 	/\*recode from 0 *\/ */
 3391:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 3392:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3393:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 3394:     /* 	} */
 3395:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 3396:     /* 	if (ij > ncodemax[j]) { */
 3397:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 3398:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 3399:     /* 	  break; */
 3400:     /* 	} */
 3401:     /*   }  /\* end of loop on modality k *\/ */
 3402:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3403:   
 3404:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3405:   
 3406:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 3407:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3408:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3409:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 3410:  } 
 3411: 
 3412:  ij=0;
 3413:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3414:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3415:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3416:      ij++;
 3417:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3418:      Tvaraff[ij]=i; /*For printing (unclear) */
 3419:    }else{
 3420:        /* Tvaraff[ij]=0; */
 3421:    }
 3422:  }
 3423:  /* ij--; */
 3424:  cptcoveff=ij; /*Number of total covariates*/
 3425: 
 3426: }
 3427: 
 3428: 
 3429: /*********** Health Expectancies ****************/
 3430: 
 3431: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3432: 
 3433: {
 3434:   /* Health expectancies, no variances */
 3435:   int i, j, nhstepm, hstepm, h, nstepm;
 3436:   int nhstepma, nstepma; /* Decreasing with age */
 3437:   double age, agelim, hf;
 3438:   double ***p3mat;
 3439:   double eip;
 3440: 
 3441:   pstamp(ficreseij);
 3442:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3443:   fprintf(ficreseij,"# Age");
 3444:   for(i=1; i<=nlstate;i++){
 3445:     for(j=1; j<=nlstate;j++){
 3446:       fprintf(ficreseij," e%1d%1d ",i,j);
 3447:     }
 3448:     fprintf(ficreseij," e%1d. ",i);
 3449:   }
 3450:   fprintf(ficreseij,"\n");
 3451: 
 3452:   
 3453:   if(estepm < stepm){
 3454:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3455:   }
 3456:   else  hstepm=estepm;   
 3457:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3458:    * This is mainly to measure the difference between two models: for example
 3459:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3460:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3461:    * progression in between and thus overestimating or underestimating according
 3462:    * to the curvature of the survival function. If, for the same date, we 
 3463:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3464:    * to compare the new estimate of Life expectancy with the same linear 
 3465:    * hypothesis. A more precise result, taking into account a more precise
 3466:    * curvature will be obtained if estepm is as small as stepm. */
 3467: 
 3468:   /* For example we decided to compute the life expectancy with the smallest unit */
 3469:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3470:      nhstepm is the number of hstepm from age to agelim 
 3471:      nstepm is the number of stepm from age to agelin. 
 3472:      Look at hpijx to understand the reason of that which relies in memory size
 3473:      and note for a fixed period like estepm months */
 3474:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3475:      survival function given by stepm (the optimization length). Unfortunately it
 3476:      means that if the survival funtion is printed only each two years of age and if
 3477:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3478:      results. So we changed our mind and took the option of the best precision.
 3479:   */
 3480:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3481: 
 3482:   agelim=AGESUP;
 3483:   /* If stepm=6 months */
 3484:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3485:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3486:     
 3487: /* nhstepm age range expressed in number of stepm */
 3488:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3489:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3490:   /* if (stepm >= YEARM) hstepm=1;*/
 3491:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3492:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3493: 
 3494:   for (age=bage; age<=fage; age ++){ 
 3495:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3496:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3497:     /* if (stepm >= YEARM) hstepm=1;*/
 3498:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3499: 
 3500:     /* If stepm=6 months */
 3501:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3502:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3503:     
 3504:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3505:     
 3506:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3507:     
 3508:     printf("%d|",(int)age);fflush(stdout);
 3509:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3510:     
 3511:     /* Computing expectancies */
 3512:     for(i=1; i<=nlstate;i++)
 3513:       for(j=1; j<=nlstate;j++)
 3514: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3515: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3516: 	  
 3517: 	  /* 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]);*/
 3518: 
 3519: 	}
 3520: 
 3521:     fprintf(ficreseij,"%3.0f",age );
 3522:     for(i=1; i<=nlstate;i++){
 3523:       eip=0;
 3524:       for(j=1; j<=nlstate;j++){
 3525: 	eip +=eij[i][j][(int)age];
 3526: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3527:       }
 3528:       fprintf(ficreseij,"%9.4f", eip );
 3529:     }
 3530:     fprintf(ficreseij,"\n");
 3531:     
 3532:   }
 3533:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3534:   printf("\n");
 3535:   fprintf(ficlog,"\n");
 3536:   
 3537: }
 3538: 
 3539: 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[] )
 3540: 
 3541: {
 3542:   /* Covariances of health expectancies eij and of total life expectancies according
 3543:    to initial status i, ei. .
 3544:   */
 3545:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3546:   int nhstepma, nstepma; /* Decreasing with age */
 3547:   double age, agelim, hf;
 3548:   double ***p3matp, ***p3matm, ***varhe;
 3549:   double **dnewm,**doldm;
 3550:   double *xp, *xm;
 3551:   double **gp, **gm;
 3552:   double ***gradg, ***trgradg;
 3553:   int theta;
 3554: 
 3555:   double eip, vip;
 3556: 
 3557:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3558:   xp=vector(1,npar);
 3559:   xm=vector(1,npar);
 3560:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3561:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3562:   
 3563:   pstamp(ficresstdeij);
 3564:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3565:   fprintf(ficresstdeij,"# Age");
 3566:   for(i=1; i<=nlstate;i++){
 3567:     for(j=1; j<=nlstate;j++)
 3568:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3569:     fprintf(ficresstdeij," e%1d. ",i);
 3570:   }
 3571:   fprintf(ficresstdeij,"\n");
 3572: 
 3573:   pstamp(ficrescveij);
 3574:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3575:   fprintf(ficrescveij,"# Age");
 3576:   for(i=1; i<=nlstate;i++)
 3577:     for(j=1; j<=nlstate;j++){
 3578:       cptj= (j-1)*nlstate+i;
 3579:       for(i2=1; i2<=nlstate;i2++)
 3580: 	for(j2=1; j2<=nlstate;j2++){
 3581: 	  cptj2= (j2-1)*nlstate+i2;
 3582: 	  if(cptj2 <= cptj)
 3583: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3584: 	}
 3585:     }
 3586:   fprintf(ficrescveij,"\n");
 3587:   
 3588:   if(estepm < stepm){
 3589:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3590:   }
 3591:   else  hstepm=estepm;   
 3592:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3593:    * This is mainly to measure the difference between two models: for example
 3594:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3595:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3596:    * progression in between and thus overestimating or underestimating according
 3597:    * to the curvature of the survival function. If, for the same date, we 
 3598:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3599:    * to compare the new estimate of Life expectancy with the same linear 
 3600:    * hypothesis. A more precise result, taking into account a more precise
 3601:    * curvature will be obtained if estepm is as small as stepm. */
 3602: 
 3603:   /* For example we decided to compute the life expectancy with the smallest unit */
 3604:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3605:      nhstepm is the number of hstepm from age to agelim 
 3606:      nstepm is the number of stepm from age to agelin. 
 3607:      Look at hpijx to understand the reason of that which relies in memory size
 3608:      and note for a fixed period like estepm months */
 3609:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3610:      survival function given by stepm (the optimization length). Unfortunately it
 3611:      means that if the survival funtion is printed only each two years of age and if
 3612:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3613:      results. So we changed our mind and took the option of the best precision.
 3614:   */
 3615:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3616: 
 3617:   /* If stepm=6 months */
 3618:   /* nhstepm age range expressed in number of stepm */
 3619:   agelim=AGESUP;
 3620:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3621:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3622:   /* if (stepm >= YEARM) hstepm=1;*/
 3623:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3624:   
 3625:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3626:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3627:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3628:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3629:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3630:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3631: 
 3632:   for (age=bage; age<=fage; age ++){ 
 3633:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3634:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3635:     /* if (stepm >= YEARM) hstepm=1;*/
 3636:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3637: 
 3638:     /* If stepm=6 months */
 3639:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3640:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3641:     
 3642:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3643: 
 3644:     /* Computing  Variances of health expectancies */
 3645:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3646:        decrease memory allocation */
 3647:     for(theta=1; theta <=npar; theta++){
 3648:       for(i=1; i<=npar; i++){ 
 3649: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3650: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3651:       }
 3652:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3653:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3654:   
 3655:       for(j=1; j<= nlstate; j++){
 3656: 	for(i=1; i<=nlstate; i++){
 3657: 	  for(h=0; h<=nhstepm-1; h++){
 3658: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3659: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3660: 	  }
 3661: 	}
 3662:       }
 3663:      
 3664:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3665: 	for(h=0; h<=nhstepm-1; h++){
 3666: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3667: 	}
 3668:     }/* End theta */
 3669:     
 3670:     
 3671:     for(h=0; h<=nhstepm-1; h++)
 3672:       for(j=1; j<=nlstate*nlstate;j++)
 3673: 	for(theta=1; theta <=npar; theta++)
 3674: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3675:     
 3676: 
 3677:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3678:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3679: 	varhe[ij][ji][(int)age] =0.;
 3680: 
 3681:      printf("%d|",(int)age);fflush(stdout);
 3682:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3683:      for(h=0;h<=nhstepm-1;h++){
 3684:       for(k=0;k<=nhstepm-1;k++){
 3685: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3686: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3687: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3688: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3689: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3690:       }
 3691:     }
 3692: 
 3693:     /* Computing expectancies */
 3694:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3695:     for(i=1; i<=nlstate;i++)
 3696:       for(j=1; j<=nlstate;j++)
 3697: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3698: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3699: 	  
 3700: 	  /* 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]);*/
 3701: 
 3702: 	}
 3703: 
 3704:     fprintf(ficresstdeij,"%3.0f",age );
 3705:     for(i=1; i<=nlstate;i++){
 3706:       eip=0.;
 3707:       vip=0.;
 3708:       for(j=1; j<=nlstate;j++){
 3709: 	eip += eij[i][j][(int)age];
 3710: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3711: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3712: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3713:       }
 3714:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3715:     }
 3716:     fprintf(ficresstdeij,"\n");
 3717: 
 3718:     fprintf(ficrescveij,"%3.0f",age );
 3719:     for(i=1; i<=nlstate;i++)
 3720:       for(j=1; j<=nlstate;j++){
 3721: 	cptj= (j-1)*nlstate+i;
 3722: 	for(i2=1; i2<=nlstate;i2++)
 3723: 	  for(j2=1; j2<=nlstate;j2++){
 3724: 	    cptj2= (j2-1)*nlstate+i2;
 3725: 	    if(cptj2 <= cptj)
 3726: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3727: 	  }
 3728:       }
 3729:     fprintf(ficrescveij,"\n");
 3730:    
 3731:   }
 3732:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3733:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3734:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3735:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3736:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3737:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3738:   printf("\n");
 3739:   fprintf(ficlog,"\n");
 3740: 
 3741:   free_vector(xm,1,npar);
 3742:   free_vector(xp,1,npar);
 3743:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3744:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3745:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3746: }
 3747: 
 3748: /************ Variance ******************/
 3749: 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 ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
 3750: {
 3751:   /* Variance of health expectancies */
 3752:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3753:   /* double **newm;*/
 3754:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3755:   
 3756:   int movingaverage();
 3757:   double **dnewm,**doldm;
 3758:   double **dnewmp,**doldmp;
 3759:   int i, j, nhstepm, hstepm, h, nstepm ;
 3760:   int k;
 3761:   double *xp;
 3762:   double **gp, **gm;  /* for var eij */
 3763:   double ***gradg, ***trgradg; /*for var eij */
 3764:   double **gradgp, **trgradgp; /* for var p point j */
 3765:   double *gpp, *gmp; /* for var p point j */
 3766:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3767:   double ***p3mat;
 3768:   double age,agelim, hf;
 3769:   double ***mobaverage;
 3770:   int theta;
 3771:   char digit[4];
 3772:   char digitp[25];
 3773: 
 3774:   char fileresprobmorprev[FILENAMELENGTH];
 3775: 
 3776:   if(popbased==1){
 3777:     if(mobilav!=0)
 3778:       strcpy(digitp,"-populbased-mobilav-");
 3779:     else strcpy(digitp,"-populbased-nomobil-");
 3780:   }
 3781:   else 
 3782:     strcpy(digitp,"-stablbased-");
 3783: 
 3784:   if (mobilav!=0) {
 3785:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3786:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3787:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3788:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3789:     }
 3790:   }
 3791: 
 3792:   strcpy(fileresprobmorprev,"prmorprev"); 
 3793:   sprintf(digit,"%-d",ij);
 3794:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3795:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3796:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3797:   strcat(fileresprobmorprev,fileres);
 3798:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3799:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3800:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3801:   }
 3802:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3803:  
 3804:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3805:   pstamp(ficresprobmorprev);
 3806:   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);
 3807:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3808:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3809:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3810:     for(i=1; i<=nlstate;i++)
 3811:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3812:   }  
 3813:   fprintf(ficresprobmorprev,"\n");
 3814:   fprintf(ficgp,"\n# Routine varevsij");
 3815:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3816:   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");
 3817:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3818: /*   } */
 3819:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3820:   pstamp(ficresvij);
 3821:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3822:   if(popbased==1)
 3823:     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);
 3824:   else
 3825:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3826:   fprintf(ficresvij,"# Age");
 3827:   for(i=1; i<=nlstate;i++)
 3828:     for(j=1; j<=nlstate;j++)
 3829:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3830:   fprintf(ficresvij,"\n");
 3831: 
 3832:   xp=vector(1,npar);
 3833:   dnewm=matrix(1,nlstate,1,npar);
 3834:   doldm=matrix(1,nlstate,1,nlstate);
 3835:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3836:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3837: 
 3838:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3839:   gpp=vector(nlstate+1,nlstate+ndeath);
 3840:   gmp=vector(nlstate+1,nlstate+ndeath);
 3841:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3842:   
 3843:   if(estepm < stepm){
 3844:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3845:   }
 3846:   else  hstepm=estepm;   
 3847:   /* For example we decided to compute the life expectancy with the smallest unit */
 3848:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3849:      nhstepm is the number of hstepm from age to agelim 
 3850:      nstepm is the number of stepm from age to agelin. 
 3851:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3852:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3853:      survival function given by stepm (the optimization length). Unfortunately it
 3854:      means that if the survival funtion is printed every two years of age and if
 3855:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3856:      results. So we changed our mind and took the option of the best precision.
 3857:   */
 3858:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3859:   agelim = AGESUP;
 3860:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3861:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3862:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3863:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3864:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3865:     gp=matrix(0,nhstepm,1,nlstate);
 3866:     gm=matrix(0,nhstepm,1,nlstate);
 3867: 
 3868: 
 3869:     for(theta=1; theta <=npar; theta++){
 3870:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3871: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3872:       }
 3873:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3874:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3875: 
 3876:       if (popbased==1) {
 3877: 	if(mobilav ==0){
 3878: 	  for(i=1; i<=nlstate;i++)
 3879: 	    prlim[i][i]=probs[(int)age][i][ij];
 3880: 	}else{ /* mobilav */ 
 3881: 	  for(i=1; i<=nlstate;i++)
 3882: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3883: 	}
 3884:       }
 3885:   
 3886:       for(j=1; j<= nlstate; j++){
 3887: 	for(h=0; h<=nhstepm; h++){
 3888: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3889: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3890: 	}
 3891:       }
 3892:       /* This for computing probability of death (h=1 means
 3893:          computed over hstepm matrices product = hstepm*stepm months) 
 3894:          as a weighted average of prlim.
 3895:       */
 3896:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3897: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3898: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3899:       }    
 3900:       /* end probability of death */
 3901: 
 3902:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3903: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3904:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3905:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3906:  
 3907:       if (popbased==1) {
 3908: 	if(mobilav ==0){
 3909: 	  for(i=1; i<=nlstate;i++)
 3910: 	    prlim[i][i]=probs[(int)age][i][ij];
 3911: 	}else{ /* mobilav */ 
 3912: 	  for(i=1; i<=nlstate;i++)
 3913: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3914: 	}
 3915:       }
 3916: 
 3917:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3918: 	for(h=0; h<=nhstepm; h++){
 3919: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3920: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3921: 	}
 3922:       }
 3923:       /* This for computing probability of death (h=1 means
 3924:          computed over hstepm matrices product = hstepm*stepm months) 
 3925:          as a weighted average of prlim.
 3926:       */
 3927:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3928: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3929:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3930:       }    
 3931:       /* end probability of death */
 3932: 
 3933:       for(j=1; j<= nlstate; j++) /* vareij */
 3934: 	for(h=0; h<=nhstepm; h++){
 3935: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3936: 	}
 3937: 
 3938:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3939: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3940:       }
 3941: 
 3942:     } /* End theta */
 3943: 
 3944:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3945: 
 3946:     for(h=0; h<=nhstepm; h++) /* veij */
 3947:       for(j=1; j<=nlstate;j++)
 3948: 	for(theta=1; theta <=npar; theta++)
 3949: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3950: 
 3951:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3952:       for(theta=1; theta <=npar; theta++)
 3953: 	trgradgp[j][theta]=gradgp[theta][j];
 3954:   
 3955: 
 3956:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3957:     for(i=1;i<=nlstate;i++)
 3958:       for(j=1;j<=nlstate;j++)
 3959: 	vareij[i][j][(int)age] =0.;
 3960: 
 3961:     for(h=0;h<=nhstepm;h++){
 3962:       for(k=0;k<=nhstepm;k++){
 3963: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3964: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3965: 	for(i=1;i<=nlstate;i++)
 3966: 	  for(j=1;j<=nlstate;j++)
 3967: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3968:       }
 3969:     }
 3970:   
 3971:     /* pptj */
 3972:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3973:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3974:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3975:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3976: 	varppt[j][i]=doldmp[j][i];
 3977:     /* end ppptj */
 3978:     /*  x centered again */
 3979:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3980:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3981:  
 3982:     if (popbased==1) {
 3983:       if(mobilav ==0){
 3984: 	for(i=1; i<=nlstate;i++)
 3985: 	  prlim[i][i]=probs[(int)age][i][ij];
 3986:       }else{ /* mobilav */ 
 3987: 	for(i=1; i<=nlstate;i++)
 3988: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3989:       }
 3990:     }
 3991:              
 3992:     /* This for computing probability of death (h=1 means
 3993:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3994:        as a weighted average of prlim.
 3995:     */
 3996:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3997:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3998: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3999:     }    
 4000:     /* end probability of death */
 4001: 
 4002:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 4003:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4004:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 4005:       for(i=1; i<=nlstate;i++){
 4006: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 4007:       }
 4008:     } 
 4009:     fprintf(ficresprobmorprev,"\n");
 4010: 
 4011:     fprintf(ficresvij,"%.0f ",age );
 4012:     for(i=1; i<=nlstate;i++)
 4013:       for(j=1; j<=nlstate;j++){
 4014: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 4015:       }
 4016:     fprintf(ficresvij,"\n");
 4017:     free_matrix(gp,0,nhstepm,1,nlstate);
 4018:     free_matrix(gm,0,nhstepm,1,nlstate);
 4019:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 4020:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 4021:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4022:   } /* End age */
 4023:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 4024:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 4025:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 4026:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4027:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 4028:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 4029:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 4030: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 4031: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4032: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4033:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 4034:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 4035:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 4036:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 4037:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 4038:   /*  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.png\"> <br>\n", stepm,YEARM,digitp,digit);
 4039: */
 4040: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 4041:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 4042: 
 4043:   free_vector(xp,1,npar);
 4044:   free_matrix(doldm,1,nlstate,1,nlstate);
 4045:   free_matrix(dnewm,1,nlstate,1,npar);
 4046:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4047:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 4048:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4049:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4050:   fclose(ficresprobmorprev);
 4051:   fflush(ficgp);
 4052:   fflush(fichtm); 
 4053: }  /* end varevsij */
 4054: 
 4055: /************ Variance of prevlim ******************/
 4056: 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 ij, char strstart[])
 4057: {
 4058:   /* Variance of prevalence limit */
 4059:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 4060: 
 4061:   double **dnewm,**doldm;
 4062:   int i, j, nhstepm, hstepm;
 4063:   double *xp;
 4064:   double *gp, *gm;
 4065:   double **gradg, **trgradg;
 4066:   double age,agelim;
 4067:   int theta;
 4068:   
 4069:   pstamp(ficresvpl);
 4070:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 4071:   fprintf(ficresvpl,"# Age");
 4072:   for(i=1; i<=nlstate;i++)
 4073:       fprintf(ficresvpl," %1d-%1d",i,i);
 4074:   fprintf(ficresvpl,"\n");
 4075: 
 4076:   xp=vector(1,npar);
 4077:   dnewm=matrix(1,nlstate,1,npar);
 4078:   doldm=matrix(1,nlstate,1,nlstate);
 4079:   
 4080:   hstepm=1*YEARM; /* Every year of age */
 4081:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 4082:   agelim = AGESUP;
 4083:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4084:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4085:     if (stepm >= YEARM) hstepm=1;
 4086:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4087:     gradg=matrix(1,npar,1,nlstate);
 4088:     gp=vector(1,nlstate);
 4089:     gm=vector(1,nlstate);
 4090: 
 4091:     for(theta=1; theta <=npar; theta++){
 4092:       for(i=1; i<=npar; i++){ /* Computes gradient */
 4093: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4094:       }
 4095:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4096:       for(i=1;i<=nlstate;i++)
 4097: 	gp[i] = prlim[i][i];
 4098:     
 4099:       for(i=1; i<=npar; i++) /* Computes gradient */
 4100: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4101:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4102:       for(i=1;i<=nlstate;i++)
 4103: 	gm[i] = prlim[i][i];
 4104: 
 4105:       for(i=1;i<=nlstate;i++)
 4106: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 4107:     } /* End theta */
 4108: 
 4109:     trgradg =matrix(1,nlstate,1,npar);
 4110: 
 4111:     for(j=1; j<=nlstate;j++)
 4112:       for(theta=1; theta <=npar; theta++)
 4113: 	trgradg[j][theta]=gradg[theta][j];
 4114: 
 4115:     for(i=1;i<=nlstate;i++)
 4116:       varpl[i][(int)age] =0.;
 4117:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4118:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4119:     for(i=1;i<=nlstate;i++)
 4120:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 4121: 
 4122:     fprintf(ficresvpl,"%.0f ",age );
 4123:     for(i=1; i<=nlstate;i++)
 4124:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 4125:     fprintf(ficresvpl,"\n");
 4126:     free_vector(gp,1,nlstate);
 4127:     free_vector(gm,1,nlstate);
 4128:     free_matrix(gradg,1,npar,1,nlstate);
 4129:     free_matrix(trgradg,1,nlstate,1,npar);
 4130:   } /* End age */
 4131: 
 4132:   free_vector(xp,1,npar);
 4133:   free_matrix(doldm,1,nlstate,1,npar);
 4134:   free_matrix(dnewm,1,nlstate,1,nlstate);
 4135: 
 4136: }
 4137: 
 4138: /************ Variance of one-step probabilities  ******************/
 4139: 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[])
 4140: {
 4141:   int i, j=0,  k1, l1, tj;
 4142:   int k2, l2, j1,  z1;
 4143:   int k=0, l;
 4144:   int first=1, first1, first2;
 4145:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 4146:   double **dnewm,**doldm;
 4147:   double *xp;
 4148:   double *gp, *gm;
 4149:   double **gradg, **trgradg;
 4150:   double **mu;
 4151:   double age, cov[NCOVMAX+1];
 4152:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 4153:   int theta;
 4154:   char fileresprob[FILENAMELENGTH];
 4155:   char fileresprobcov[FILENAMELENGTH];
 4156:   char fileresprobcor[FILENAMELENGTH];
 4157:   double ***varpij;
 4158: 
 4159:   strcpy(fileresprob,"prob"); 
 4160:   strcat(fileresprob,fileres);
 4161:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 4162:     printf("Problem with resultfile: %s\n", fileresprob);
 4163:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 4164:   }
 4165:   strcpy(fileresprobcov,"probcov"); 
 4166:   strcat(fileresprobcov,fileres);
 4167:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 4168:     printf("Problem with resultfile: %s\n", fileresprobcov);
 4169:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 4170:   }
 4171:   strcpy(fileresprobcor,"probcor"); 
 4172:   strcat(fileresprobcor,fileres);
 4173:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 4174:     printf("Problem with resultfile: %s\n", fileresprobcor);
 4175:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 4176:   }
 4177:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4178:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4179:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4180:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4181:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4182:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4183:   pstamp(ficresprob);
 4184:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 4185:   fprintf(ficresprob,"# Age");
 4186:   pstamp(ficresprobcov);
 4187:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 4188:   fprintf(ficresprobcov,"# Age");
 4189:   pstamp(ficresprobcor);
 4190:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 4191:   fprintf(ficresprobcor,"# Age");
 4192: 
 4193: 
 4194:   for(i=1; i<=nlstate;i++)
 4195:     for(j=1; j<=(nlstate+ndeath);j++){
 4196:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 4197:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 4198:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 4199:     }  
 4200:  /* fprintf(ficresprob,"\n");
 4201:   fprintf(ficresprobcov,"\n");
 4202:   fprintf(ficresprobcor,"\n");
 4203:  */
 4204:   xp=vector(1,npar);
 4205:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4206:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4207:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 4208:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 4209:   first=1;
 4210:   fprintf(ficgp,"\n# Routine varprob");
 4211:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 4212:   fprintf(fichtm,"\n");
 4213: 
 4214:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 4215:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 4216:   file %s<br>\n",optionfilehtmcov);
 4217:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 4218: and drawn. It helps understanding how is the covariance between two incidences.\
 4219:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 4220:   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. \
 4221: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 4222: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 4223: standard deviations wide on each axis. <br>\
 4224:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 4225:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 4226: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 4227: 
 4228:   cov[1]=1;
 4229:   /* tj=cptcoveff; */
 4230:   tj = (int) pow(2,cptcoveff);
 4231:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 4232:   j1=0;
 4233:   for(j1=1; j1<=tj;j1++){
 4234:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 4235:     /*j1++;*/
 4236:       if  (cptcovn>0) {
 4237: 	fprintf(ficresprob, "\n#********** Variable "); 
 4238: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4239: 	fprintf(ficresprob, "**********\n#\n");
 4240: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 4241: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4242: 	fprintf(ficresprobcov, "**********\n#\n");
 4243: 	
 4244: 	fprintf(ficgp, "\n#********** Variable "); 
 4245: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4246: 	fprintf(ficgp, "**********\n#\n");
 4247: 	
 4248: 	
 4249: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 4250: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4251: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 4252: 	
 4253: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 4254: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4255: 	fprintf(ficresprobcor, "**********\n#");    
 4256:       }
 4257:       
 4258:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 4259:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4260:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 4261:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 4262:       for (age=bage; age<=fage; age ++){ 
 4263: 	cov[2]=age;
 4264: 	if(nagesqr==1)
 4265: 	  cov[3]= age*age;
 4266: 	for (k=1; k<=cptcovn;k++) {
 4267: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 4268: 							 * 1  1 1 1 1
 4269: 							 * 2  2 1 1 1
 4270: 							 * 3  1 2 1 1
 4271: 							 */
 4272: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 4273: 	}
 4274: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4275: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 4276: 	for (k=1; k<=cptcovprod;k++)
 4277: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 4278: 	
 4279:     
 4280: 	for(theta=1; theta <=npar; theta++){
 4281: 	  for(i=1; i<=npar; i++)
 4282: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 4283: 	  
 4284: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4285: 	  
 4286: 	  k=0;
 4287: 	  for(i=1; i<= (nlstate); i++){
 4288: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4289: 	      k=k+1;
 4290: 	      gp[k]=pmmij[i][j];
 4291: 	    }
 4292: 	  }
 4293: 	  
 4294: 	  for(i=1; i<=npar; i++)
 4295: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 4296:     
 4297: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4298: 	  k=0;
 4299: 	  for(i=1; i<=(nlstate); i++){
 4300: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4301: 	      k=k+1;
 4302: 	      gm[k]=pmmij[i][j];
 4303: 	    }
 4304: 	  }
 4305:      
 4306: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 4307: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 4308: 	}
 4309: 
 4310: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 4311: 	  for(theta=1; theta <=npar; theta++)
 4312: 	    trgradg[j][theta]=gradg[theta][j];
 4313: 	
 4314: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 4315: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 4316: 
 4317: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 4318: 	
 4319: 	k=0;
 4320: 	for(i=1; i<=(nlstate); i++){
 4321: 	  for(j=1; j<=(nlstate+ndeath);j++){
 4322: 	    k=k+1;
 4323: 	    mu[k][(int) age]=pmmij[i][j];
 4324: 	  }
 4325: 	}
 4326:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 4327: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 4328: 	    varpij[i][j][(int)age] = doldm[i][j];
 4329: 
 4330: 	/*printf("\n%d ",(int)age);
 4331: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4332: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4333: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4334: 	  }*/
 4335: 
 4336: 	fprintf(ficresprob,"\n%d ",(int)age);
 4337: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 4338: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 4339: 
 4340: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 4341: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 4342: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4343: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 4344: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 4345: 	}
 4346: 	i=0;
 4347: 	for (k=1; k<=(nlstate);k++){
 4348:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 4349:  	    i++;
 4350: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 4351: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 4352: 	    for (j=1; j<=i;j++){
 4353: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 4354: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 4355: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 4356: 	    }
 4357: 	  }
 4358: 	}/* end of loop for state */
 4359:       } /* end of loop for age */
 4360:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 4361:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 4362:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4363:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4364:       
 4365:       /* Confidence intervalle of pij  */
 4366:       /*
 4367: 	fprintf(ficgp,"\nunset parametric;unset label");
 4368: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4369: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4370: 	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);
 4371: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4372: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4373: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4374:       */
 4375: 
 4376:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4377:       first1=1;first2=2;
 4378:       for (k2=1; k2<=(nlstate);k2++){
 4379: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4380: 	  if(l2==k2) continue;
 4381: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4382: 	  for (k1=1; k1<=(nlstate);k1++){
 4383: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4384: 	      if(l1==k1) continue;
 4385: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4386: 	      if(i<=j) continue;
 4387: 	      for (age=bage; age<=fage; age ++){ 
 4388: 		if ((int)age %5==0){
 4389: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4390: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4391: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4392: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4393: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4394: 		  c12=cv12/sqrt(v1*v2);
 4395: 		  /* Computing eigen value of matrix of covariance */
 4396: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4397: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4398: 		  if ((lc2 <0) || (lc1 <0) ){
 4399: 		    if(first2==1){
 4400: 		      first1=0;
 4401: 		    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);
 4402: 		    }
 4403: 		    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);
 4404: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4405: 		    /* lc2=fabs(lc2); */
 4406: 		  }
 4407: 
 4408: 		  /* Eigen vectors */
 4409: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4410: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4411: 		  v21=(lc1-v1)/cv12*v11;
 4412: 		  v12=-v21;
 4413: 		  v22=v11;
 4414: 		  tnalp=v21/v11;
 4415: 		  if(first1==1){
 4416: 		    first1=0;
 4417: 		    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);
 4418: 		  }
 4419: 		  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);
 4420: 		  /*printf(fignu*/
 4421: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4422: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4423: 		  if(first==1){
 4424: 		    first=0;
 4425:  		    fprintf(ficgp,"\nset parametric;unset label");
 4426: 		    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);
 4427: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4428: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4429:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4430: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4431: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4432: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4433: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4434: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4435: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4436: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4437: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4438: 		    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",\
 4439: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4440: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4441: 		  }else{
 4442: 		    first=0;
 4443: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4444: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4445: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4446: 		    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",\
 4447: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4448: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4449: 		  }/* if first */
 4450: 		} /* age mod 5 */
 4451: 	      } /* end loop age */
 4452: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4453: 	      first=1;
 4454: 	    } /*l12 */
 4455: 	  } /* k12 */
 4456: 	} /*l1 */
 4457:       }/* k1 */
 4458:       /* } */ /* loop covariates */
 4459:   }
 4460:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4461:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4462:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4463:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4464:   free_vector(xp,1,npar);
 4465:   fclose(ficresprob);
 4466:   fclose(ficresprobcov);
 4467:   fclose(ficresprobcor);
 4468:   fflush(ficgp);
 4469:   fflush(fichtmcov);
 4470: }
 4471: 
 4472: 
 4473: /******************* Printing html file ***********/
 4474: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4475: 		  int lastpass, int stepm, int weightopt, char model[],\
 4476: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4477: 		  int popforecast, int estepm ,\
 4478: 		  double jprev1, double mprev1,double anprev1, \
 4479: 		  double jprev2, double mprev2,double anprev2){
 4480:   int jj1, k1, i1, cpt;
 4481: 
 4482:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4483:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4484: </ul>");
 4485:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4486:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4487: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4488:    fprintf(fichtm,"\
 4489:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4490: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4491:    fprintf(fichtm,"\
 4492:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4493: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4494:    fprintf(fichtm,"\
 4495:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . 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): \
 4496:    <a href=\"%s\">%s</a> <br>\n",
 4497: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4498:    fprintf(fichtm,"\
 4499:  - Population projections by age and states: \
 4500:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4501: 
 4502: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4503: 
 4504:  m=pow(2,cptcoveff);
 4505:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4506: 
 4507:  jj1=0;
 4508:  for(k1=1; k1<=m;k1++){
 4509:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 4510:      jj1++;
 4511:      if (cptcovn > 0) {
 4512:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4513:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 4514: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4515: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);fflush(stdout);
 4516:        }
 4517:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4518:      }
 4519:      /* Pij */
 4520:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
 4521: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4522:      /* Quasi-incidences */
 4523:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4524:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
 4525: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4526:        /* Period (stable) prevalence in each health state */
 4527:        for(cpt=1; cpt<=nlstate;cpt++){
 4528: 	 fprintf(fichtm,"<br>- 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.png\">%s%d_%d.png</a><br> \
 4529: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4530:        }
 4531:      for(cpt=1; cpt<=nlstate;cpt++) {
 4532:         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) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
 4533: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4534:      }
 4535:    /* } /\* end i1 *\/ */
 4536:  }/* End k1 */
 4537:  fprintf(fichtm,"</ul>");
 4538: 
 4539: 
 4540:  fprintf(fichtm,"\
 4541: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4542:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4543: 
 4544:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4545: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4546:  fprintf(fichtm,"\
 4547:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4548: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4549: 
 4550:  fprintf(fichtm,"\
 4551:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4552: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4553:  fprintf(fichtm,"\
 4554:  - 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): \
 4555:    <a href=\"%s\">%s</a> <br>\n</li>",
 4556: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4557:  fprintf(fichtm,"\
 4558:  - (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): \
 4559:    <a href=\"%s\">%s</a> <br>\n</li>",
 4560: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4561:  fprintf(fichtm,"\
 4562:  - 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",
 4563: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4564:  fprintf(fichtm,"\
 4565:  - 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",
 4566: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4567:  fprintf(fichtm,"\
 4568:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4569: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4570: 
 4571: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4572: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4573: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4574: /* 	<br>",fileres,fileres,fileres,fileres); */
 4575: /*  else  */
 4576: /*    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); */
 4577:  fflush(fichtm);
 4578:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4579: 
 4580:  m=pow(2,cptcoveff);
 4581:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4582: 
 4583:  jj1=0;
 4584:  for(k1=1; k1<=m;k1++){
 4585:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 4586:      jj1++;
 4587:      if (cptcovn > 0) {
 4588:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4589:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4590: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4591:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4592:      }
 4593:      for(cpt=1; cpt<=nlstate;cpt++) {
 4594:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4595: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4596: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4597:      }
 4598:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4599: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4600: true period expectancies (those weighted with period prevalences are also\
 4601:  drawn in addition to the population based expectancies computed using\
 4602:  observed and cahotic prevalences: %s%d.png<br>\
 4603: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4604:    /* } /\* end i1 *\/ */
 4605:  }/* End k1 */
 4606:  fprintf(fichtm,"</ul>");
 4607:  fflush(fichtm);
 4608: }
 4609: 
 4610: /******************* Gnuplot file **************/
 4611: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4612: 
 4613:   char dirfileres[132],optfileres[132];
 4614:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4615:   int ng=0;
 4616: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4617: /*     printf("Problem with file %s",optionfilegnuplot); */
 4618: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4619: /*   } */
 4620: 
 4621:   /*#ifdef windows */
 4622:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4623:     /*#endif */
 4624:   m=pow(2,cptcoveff);
 4625: 
 4626:   strcpy(dirfileres,optionfilefiname);
 4627:   strcpy(optfileres,"vpl");
 4628:  /* 1eme*/
 4629:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4630:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4631:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4632:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4633:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4634:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4635: set ylabel \"Probability\" \n\
 4636: set ter png small size 320, 240\n\
 4637: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4638: 
 4639:      for (i=1; i<= nlstate ; i ++) {
 4640:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4641:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4642:      }
 4643:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 4644:      for (i=1; i<= nlstate ; i ++) {
 4645:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4646:        else fprintf(ficgp," %%*lf (%%*lf)");
 4647:      } 
 4648:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
 4649:      for (i=1; i<= nlstate ; i ++) {
 4650:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4651:        else fprintf(ficgp," %%*lf (%%*lf)");
 4652:      }  
 4653:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
 4654:    }
 4655:   }
 4656:   /*2 eme*/
 4657:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4658:   for (k1=1; k1<= m ; k1 ++) { 
 4659:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4660:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4661:     
 4662:     for (i=1; i<= nlstate+1 ; i ++) {
 4663:       k=2*i;
 4664:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4665:       for (j=1; j<= nlstate+1 ; j ++) {
 4666: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4667: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4668:       }   
 4669:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4670:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4671:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4672:       for (j=1; j<= nlstate+1 ; j ++) {
 4673: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4674: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4675:       }   
 4676:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4677:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4678:       for (j=1; j<= nlstate+1 ; j ++) {
 4679: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4680: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4681:       }   
 4682:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4683:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4684:     }
 4685:   }
 4686:   
 4687:   /*3eme*/
 4688:   
 4689:   for (k1=1; k1<= m ; k1 ++) { 
 4690:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4691:       /*       k=2+nlstate*(2*cpt-2); */
 4692:       k=2+(nlstate+1)*(cpt-1);
 4693:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4694:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4695: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
 4696:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4697: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4698: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4699: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4700: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4701: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4702: 	
 4703:       */
 4704:       for (i=1; i< nlstate ; i ++) {
 4705: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
 4706: 	/*	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);*/
 4707: 	
 4708:       } 
 4709:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4710:     }
 4711:   }
 4712:   
 4713:   /* CV preval stable (period) */
 4714:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4715:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4716:       k=3;
 4717:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4718:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4719:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4720: set ter png small size 320, 240\n\
 4721: unset log y\n\
 4722: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4723:       for (i=1; i<= nlstate ; i ++){
 4724: 	if(i==1)
 4725: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4726: 	else
 4727: 	  fprintf(ficgp,", '' ");
 4728: 	l=(nlstate+ndeath)*(i-1)+1;
 4729: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4730: 	for (j=1; j<= (nlstate-1) ; j ++)
 4731: 	  fprintf(ficgp,"+$%d",k+l+j);
 4732: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4733:       } /* nlstate */
 4734:       fprintf(ficgp,"\n");
 4735:     } /* end cpt state*/ 
 4736:   } /* end covariate */  
 4737:   
 4738:   /* proba elementaires */
 4739:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 4740:   for(i=1,jk=1; i <=nlstate; i++){
 4741:     fprintf(ficgp,"# initial state %d\n",i);
 4742:     for(k=1; k <=(nlstate+ndeath); k++){
 4743:       if (k != i) {
 4744: 	fprintf(ficgp,"#   current state %d\n",k);
 4745: 	for(j=1; j <=ncovmodel; j++){
 4746: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 4747: 	  jk++; 
 4748: 	}
 4749: 	fprintf(ficgp,"\n");
 4750:       }
 4751:     }
 4752:    }
 4753:   fprintf(ficgp,"##############\n#\n");
 4754: 
 4755:   /*goto avoid;*/
 4756:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
 4757:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 4758:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 4759:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 4760:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 4761:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4762:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4763:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4764:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4765:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 4766:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4767:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 4768:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 4769:   fprintf(ficgp,"#\n");
 4770:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4771:      fprintf(ficgp,"# ng=%d\n",ng);
 4772:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 4773:      for(jk=1; jk <=m; jk++) {
 4774:        fprintf(ficgp,"#    jk=%d\n",jk);
 4775:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4776:        if (ng==2)
 4777: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4778:        else
 4779: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4780:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4781:        i=1;
 4782:        for(k2=1; k2<=nlstate; k2++) {
 4783: 	 k3=i;
 4784: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4785: 	   if (k != k2){
 4786: 	     if(ng==2)
 4787: 	       if(nagesqr==0)
 4788: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4789: 	       else /* nagesqr =1 */
 4790: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 4791: 	     else
 4792: 	       if(nagesqr==0)
 4793: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4794: 	       else /* nagesqr =1 */
 4795: 		 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 4796: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4797: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 4798: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
 4799: 	       	 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4800: 	       	 ij++;
 4801: 	       }
 4802: 	       else
 4803: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4804: 	     }
 4805: 	     fprintf(ficgp,")/(1");
 4806: 	     
 4807: 	     for(k1=1; k1 <=nlstate; k1++){ 
 4808: 	       if(nagesqr==0)
 4809: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4810: 	       else /* nagesqr =1 */
 4811: 		 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);
 4812:   
 4813: 	       ij=1;
 4814: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 4815: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 4816: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4817: 		   ij++;
 4818: 		 }
 4819: 		 else
 4820: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4821: 	       }
 4822: 	       fprintf(ficgp,")");
 4823: 	     }
 4824: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4825: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4826: 	     i=i+ncovmodel;
 4827: 	   }
 4828: 	 } /* end k */
 4829:        } /* end k2 */
 4830:      } /* end jk */
 4831:    } /* end ng */
 4832:  /* avoid: */
 4833:    fflush(ficgp); 
 4834: }  /* end gnuplot */
 4835: 
 4836: 
 4837: /*************** Moving average **************/
 4838: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4839: 
 4840:   int i, cpt, cptcod;
 4841:   int modcovmax =1;
 4842:   int mobilavrange, mob;
 4843:   double age;
 4844: 
 4845:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4846: 			   a covariate has 2 modalities */
 4847:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4848: 
 4849:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4850:     if(mobilav==1) mobilavrange=5; /* default */
 4851:     else mobilavrange=mobilav;
 4852:     for (age=bage; age<=fage; age++)
 4853:       for (i=1; i<=nlstate;i++)
 4854: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4855: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4856:     /* We keep the original values on the extreme ages bage, fage and for 
 4857:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4858:        we use a 5 terms etc. until the borders are no more concerned. 
 4859:     */ 
 4860:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4861:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4862: 	for (i=1; i<=nlstate;i++){
 4863: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4864: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4865: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4866: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4867: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4868: 	      }
 4869: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4870: 	  }
 4871: 	}
 4872:       }/* end age */
 4873:     }/* end mob */
 4874:   }else return -1;
 4875:   return 0;
 4876: }/* End movingaverage */
 4877: 
 4878: 
 4879: /************** Forecasting ******************/
 4880: 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){
 4881:   /* proj1, year, month, day of starting projection 
 4882:      agemin, agemax range of age
 4883:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4884:      anproj2 year of en of projection (same day and month as proj1).
 4885:   */
 4886:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4887:   double agec; /* generic age */
 4888:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4889:   double *popeffectif,*popcount;
 4890:   double ***p3mat;
 4891:   double ***mobaverage;
 4892:   char fileresf[FILENAMELENGTH];
 4893: 
 4894:   agelim=AGESUP;
 4895:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4896:  
 4897:   strcpy(fileresf,"f"); 
 4898:   strcat(fileresf,fileres);
 4899:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4900:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4901:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4902:   }
 4903:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4904:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4905: 
 4906:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4907: 
 4908:   if (mobilav!=0) {
 4909:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4910:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4911:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4912:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4913:     }
 4914:   }
 4915: 
 4916:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4917:   if (stepm<=12) stepsize=1;
 4918:   if(estepm < stepm){
 4919:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4920:   }
 4921:   else  hstepm=estepm;   
 4922: 
 4923:   hstepm=hstepm/stepm; 
 4924:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4925:                                fractional in yp1 */
 4926:   anprojmean=yp;
 4927:   yp2=modf((yp1*12),&yp);
 4928:   mprojmean=yp;
 4929:   yp1=modf((yp2*30.5),&yp);
 4930:   jprojmean=yp;
 4931:   if(jprojmean==0) jprojmean=1;
 4932:   if(mprojmean==0) jprojmean=1;
 4933: 
 4934:   i1=cptcoveff;
 4935:   if (cptcovn < 1){i1=1;}
 4936:   
 4937:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4938:   
 4939:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4940: 
 4941: /* 	      if (h==(int)(YEARM*yearp)){ */
 4942:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4943:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4944:       k=k+1;
 4945:       fprintf(ficresf,"\n#******");
 4946:       for(j=1;j<=cptcoveff;j++) {
 4947: 	fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4948:       }
 4949:       fprintf(ficresf,"******\n");
 4950:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4951:       for(j=1; j<=nlstate+ndeath;j++){ 
 4952: 	for(i=1; i<=nlstate;i++) 	      
 4953:           fprintf(ficresf," p%d%d",i,j);
 4954: 	fprintf(ficresf," p.%d",j);
 4955:       }
 4956:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4957: 	fprintf(ficresf,"\n");
 4958: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4959: 
 4960:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4961: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4962: 	  nhstepm = nhstepm/hstepm; 
 4963: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4964: 	  oldm=oldms;savm=savms;
 4965: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4966: 	
 4967: 	  for (h=0; h<=nhstepm; h++){
 4968: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4969:               fprintf(ficresf,"\n");
 4970:               for(j=1;j<=cptcoveff;j++) 
 4971:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4972: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4973: 	    } 
 4974: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4975: 	      ppij=0.;
 4976: 	      for(i=1; i<=nlstate;i++) {
 4977: 		if (mobilav==1) 
 4978: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4979: 		else {
 4980: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4981: 		}
 4982: 		if (h*hstepm/YEARM*stepm== yearp) {
 4983: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4984: 		}
 4985: 	      } /* end i */
 4986: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4987: 		fprintf(ficresf," %.3f", ppij);
 4988: 	      }
 4989: 	    }/* end j */
 4990: 	  } /* end h */
 4991: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4992: 	} /* end agec */
 4993:       } /* end yearp */
 4994:     } /* end cptcod */
 4995:   } /* end  cptcov */
 4996:        
 4997:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4998: 
 4999:   fclose(ficresf);
 5000: }
 5001: 
 5002: /************** Forecasting *****not tested NB*************/
 5003: 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){
 5004:   
 5005:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 5006:   int *popage;
 5007:   double calagedatem, agelim, kk1, kk2;
 5008:   double *popeffectif,*popcount;
 5009:   double ***p3mat,***tabpop,***tabpopprev;
 5010:   double ***mobaverage;
 5011:   char filerespop[FILENAMELENGTH];
 5012: 
 5013:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5014:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5015:   agelim=AGESUP;
 5016:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 5017:   
 5018:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 5019:   
 5020:   
 5021:   strcpy(filerespop,"pop"); 
 5022:   strcat(filerespop,fileres);
 5023:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 5024:     printf("Problem with forecast resultfile: %s\n", filerespop);
 5025:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 5026:   }
 5027:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 5028:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 5029: 
 5030:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 5031: 
 5032:   if (mobilav!=0) {
 5033:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5034:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 5035:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 5036:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 5037:     }
 5038:   }
 5039: 
 5040:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 5041:   if (stepm<=12) stepsize=1;
 5042:   
 5043:   agelim=AGESUP;
 5044:   
 5045:   hstepm=1;
 5046:   hstepm=hstepm/stepm; 
 5047:   
 5048:   if (popforecast==1) {
 5049:     if((ficpop=fopen(popfile,"r"))==NULL) {
 5050:       printf("Problem with population file : %s\n",popfile);exit(0);
 5051:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 5052:     } 
 5053:     popage=ivector(0,AGESUP);
 5054:     popeffectif=vector(0,AGESUP);
 5055:     popcount=vector(0,AGESUP);
 5056:     
 5057:     i=1;   
 5058:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 5059:    
 5060:     imx=i;
 5061:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 5062:   }
 5063: 
 5064:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 5065:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 5066:       k=k+1;
 5067:       fprintf(ficrespop,"\n#******");
 5068:       for(j=1;j<=cptcoveff;j++) {
 5069: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5070:       }
 5071:       fprintf(ficrespop,"******\n");
 5072:       fprintf(ficrespop,"# Age");
 5073:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 5074:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 5075:       
 5076:       for (cpt=0; cpt<=0;cpt++) { 
 5077: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5078: 	
 5079:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5080: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5081: 	  nhstepm = nhstepm/hstepm; 
 5082: 	  
 5083: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5084: 	  oldm=oldms;savm=savms;
 5085: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5086: 	
 5087: 	  for (h=0; h<=nhstepm; h++){
 5088: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5089: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5090: 	    } 
 5091: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5092: 	      kk1=0.;kk2=0;
 5093: 	      for(i=1; i<=nlstate;i++) {	      
 5094: 		if (mobilav==1) 
 5095: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 5096: 		else {
 5097: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 5098: 		}
 5099: 	      }
 5100: 	      if (h==(int)(calagedatem+12*cpt)){
 5101: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 5102: 		  /*fprintf(ficrespop," %.3f", kk1);
 5103: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 5104: 	      }
 5105: 	    }
 5106: 	    for(i=1; i<=nlstate;i++){
 5107: 	      kk1=0.;
 5108: 		for(j=1; j<=nlstate;j++){
 5109: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 5110: 		}
 5111: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 5112: 	    }
 5113: 
 5114: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 5115: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 5116: 	  }
 5117: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5118: 	}
 5119:       }
 5120:  
 5121:   /******/
 5122: 
 5123:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 5124: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5125: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5126: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5127: 	  nhstepm = nhstepm/hstepm; 
 5128: 	  
 5129: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5130: 	  oldm=oldms;savm=savms;
 5131: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5132: 	  for (h=0; h<=nhstepm; h++){
 5133: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5134: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5135: 	    } 
 5136: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5137: 	      kk1=0.;kk2=0;
 5138: 	      for(i=1; i<=nlstate;i++) {	      
 5139: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 5140: 	      }
 5141: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 5142: 	    }
 5143: 	  }
 5144: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5145: 	}
 5146:       }
 5147:    } 
 5148:   }
 5149:  
 5150:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5151: 
 5152:   if (popforecast==1) {
 5153:     free_ivector(popage,0,AGESUP);
 5154:     free_vector(popeffectif,0,AGESUP);
 5155:     free_vector(popcount,0,AGESUP);
 5156:   }
 5157:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5158:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5159:   fclose(ficrespop);
 5160: } /* End of popforecast */
 5161: 
 5162: int fileappend(FILE *fichier, char *optionfich)
 5163: {
 5164:   if((fichier=fopen(optionfich,"a"))==NULL) {
 5165:     printf("Problem with file: %s\n", optionfich);
 5166:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 5167:     return (0);
 5168:   }
 5169:   fflush(fichier);
 5170:   return (1);
 5171: }
 5172: 
 5173: 
 5174: /**************** function prwizard **********************/
 5175: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 5176: {
 5177: 
 5178:   /* Wizard to print covariance matrix template */
 5179: 
 5180:   char ca[32], cb[32];
 5181:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 5182:   int numlinepar;
 5183: 
 5184:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5185:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5186:   for(i=1; i <=nlstate; i++){
 5187:     jj=0;
 5188:     for(j=1; j <=nlstate+ndeath; j++){
 5189:       if(j==i) continue;
 5190:       jj++;
 5191:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 5192:       printf("%1d%1d",i,j);
 5193:       fprintf(ficparo,"%1d%1d",i,j);
 5194:       for(k=1; k<=ncovmodel;k++){
 5195: 	/* 	  printf(" %lf",param[i][j][k]); */
 5196: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 5197: 	printf(" 0.");
 5198: 	fprintf(ficparo," 0.");
 5199:       }
 5200:       printf("\n");
 5201:       fprintf(ficparo,"\n");
 5202:     }
 5203:   }
 5204:   printf("# Scales (for hessian or gradient estimation)\n");
 5205:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 5206:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 5207:   for(i=1; i <=nlstate; i++){
 5208:     jj=0;
 5209:     for(j=1; j <=nlstate+ndeath; j++){
 5210:       if(j==i) continue;
 5211:       jj++;
 5212:       fprintf(ficparo,"%1d%1d",i,j);
 5213:       printf("%1d%1d",i,j);
 5214:       fflush(stdout);
 5215:       for(k=1; k<=ncovmodel;k++){
 5216: 	/* 	printf(" %le",delti3[i][j][k]); */
 5217: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 5218: 	printf(" 0.");
 5219: 	fprintf(ficparo," 0.");
 5220:       }
 5221:       numlinepar++;
 5222:       printf("\n");
 5223:       fprintf(ficparo,"\n");
 5224:     }
 5225:   }
 5226:   printf("# Covariance matrix\n");
 5227: /* # 121 Var(a12)\n\ */
 5228: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5229: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5230: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5231: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5232: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5233: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5234: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5235:   fflush(stdout);
 5236:   fprintf(ficparo,"# Covariance matrix\n");
 5237:   /* # 121 Var(a12)\n\ */
 5238:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5239:   /* #   ...\n\ */
 5240:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 5241:   
 5242:   for(itimes=1;itimes<=2;itimes++){
 5243:     jj=0;
 5244:     for(i=1; i <=nlstate; i++){
 5245:       for(j=1; j <=nlstate+ndeath; j++){
 5246: 	if(j==i) continue;
 5247: 	for(k=1; k<=ncovmodel;k++){
 5248: 	  jj++;
 5249: 	  ca[0]= k+'a'-1;ca[1]='\0';
 5250: 	  if(itimes==1){
 5251: 	    printf("#%1d%1d%d",i,j,k);
 5252: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 5253: 	  }else{
 5254: 	    printf("%1d%1d%d",i,j,k);
 5255: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 5256: 	    /* 	printf(" %.5le",matcov[i][j]); */
 5257: 	  }
 5258: 	  ll=0;
 5259: 	  for(li=1;li <=nlstate; li++){
 5260: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 5261: 	      if(lj==li) continue;
 5262: 	      for(lk=1;lk<=ncovmodel;lk++){
 5263: 		ll++;
 5264: 		if(ll<=jj){
 5265: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 5266: 		  if(ll<jj){
 5267: 		    if(itimes==1){
 5268: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5269: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5270: 		    }else{
 5271: 		      printf(" 0.");
 5272: 		      fprintf(ficparo," 0.");
 5273: 		    }
 5274: 		  }else{
 5275: 		    if(itimes==1){
 5276: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 5277: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 5278: 		    }else{
 5279: 		      printf(" 0.");
 5280: 		      fprintf(ficparo," 0.");
 5281: 		    }
 5282: 		  }
 5283: 		}
 5284: 	      } /* end lk */
 5285: 	    } /* end lj */
 5286: 	  } /* end li */
 5287: 	  printf("\n");
 5288: 	  fprintf(ficparo,"\n");
 5289: 	  numlinepar++;
 5290: 	} /* end k*/
 5291:       } /*end j */
 5292:     } /* end i */
 5293:   } /* end itimes */
 5294: 
 5295: } /* end of prwizard */
 5296: /******************* Gompertz Likelihood ******************************/
 5297: double gompertz(double x[])
 5298: { 
 5299:   double A,B,L=0.0,sump=0.,num=0.;
 5300:   int i,n=0; /* n is the size of the sample */
 5301: 
 5302:   for (i=0;i<=imx-1 ; i++) {
 5303:     sump=sump+weight[i];
 5304:     /*    sump=sump+1;*/
 5305:     num=num+1;
 5306:   }
 5307:  
 5308:  
 5309:   /* for (i=0; i<=imx; i++) 
 5310:      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]);*/
 5311: 
 5312:   for (i=1;i<=imx ; i++)
 5313:     {
 5314:       if (cens[i] == 1 && wav[i]>1)
 5315: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 5316:       
 5317:       if (cens[i] == 0 && wav[i]>1)
 5318: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 5319: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 5320:       
 5321:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5322:       if (wav[i] > 1 ) { /* ??? */
 5323: 	L=L+A*weight[i];
 5324: 	/* 	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]);*/
 5325:       }
 5326:     }
 5327: 
 5328:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5329:  
 5330:   return -2*L*num/sump;
 5331: }
 5332: 
 5333: #ifdef GSL
 5334: /******************* Gompertz_f Likelihood ******************************/
 5335: double gompertz_f(const gsl_vector *v, void *params)
 5336: { 
 5337:   double A,B,LL=0.0,sump=0.,num=0.;
 5338:   double *x= (double *) v->data;
 5339:   int i,n=0; /* n is the size of the sample */
 5340: 
 5341:   for (i=0;i<=imx-1 ; i++) {
 5342:     sump=sump+weight[i];
 5343:     /*    sump=sump+1;*/
 5344:     num=num+1;
 5345:   }
 5346:  
 5347:  
 5348:   /* for (i=0; i<=imx; i++) 
 5349:      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]);*/
 5350:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 5351:   for (i=1;i<=imx ; i++)
 5352:     {
 5353:       if (cens[i] == 1 && wav[i]>1)
 5354: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 5355:       
 5356:       if (cens[i] == 0 && wav[i]>1)
 5357: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 5358: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 5359:       
 5360:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5361:       if (wav[i] > 1 ) { /* ??? */
 5362: 	LL=LL+A*weight[i];
 5363: 	/* 	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]);*/
 5364:       }
 5365:     }
 5366: 
 5367:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5368:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 5369:  
 5370:   return -2*LL*num/sump;
 5371: }
 5372: #endif
 5373: 
 5374: /******************* Printing html file ***********/
 5375: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 5376: 		  int lastpass, int stepm, int weightopt, char model[],\
 5377: 		  int imx,  double p[],double **matcov,double agemortsup){
 5378:   int i,k;
 5379: 
 5380:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 5381:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 5382:   for (i=1;i<=2;i++) 
 5383:     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]));
 5384:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 5385:   fprintf(fichtm,"</ul>");
 5386: 
 5387: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 5388: 
 5389:  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>");
 5390: 
 5391:  for (k=agegomp;k<(agemortsup-2);k++) 
 5392:    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]);
 5393: 
 5394:  
 5395:   fflush(fichtm);
 5396: }
 5397: 
 5398: /******************* Gnuplot file **************/
 5399: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 5400: 
 5401:   char dirfileres[132],optfileres[132];
 5402: 
 5403:   int ng;
 5404: 
 5405: 
 5406:   /*#ifdef windows */
 5407:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5408:     /*#endif */
 5409: 
 5410: 
 5411:   strcpy(dirfileres,optionfilefiname);
 5412:   strcpy(optfileres,"vpl");
 5413:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 5414:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5415:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5416:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5417:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5418: 
 5419: } 
 5420: 
 5421: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5422: {
 5423: 
 5424:   /*-------- data file ----------*/
 5425:   FILE *fic;
 5426:   char dummy[]="                         ";
 5427:   int i=0, j=0, n=0;
 5428:   int linei, month, year,iout;
 5429:   char line[MAXLINE], linetmp[MAXLINE];
 5430:   char stra[MAXLINE], strb[MAXLINE];
 5431:   char *stratrunc;
 5432:   int lstra;
 5433: 
 5434: 
 5435:   if((fic=fopen(datafile,"r"))==NULL)    {
 5436:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5437:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5438:   }
 5439: 
 5440:   i=1;
 5441:   linei=0;
 5442:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5443:     linei=linei+1;
 5444:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5445:       if(line[j] == '\t')
 5446: 	line[j] = ' ';
 5447:     }
 5448:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5449:       ;
 5450:     };
 5451:     line[j+1]=0;  /* Trims blanks at end of line */
 5452:     if(line[0]=='#'){
 5453:       fprintf(ficlog,"Comment line\n%s\n",line);
 5454:       printf("Comment line\n%s\n",line);
 5455:       continue;
 5456:     }
 5457:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5458:     strcpy(line, linetmp);
 5459:   
 5460: 
 5461:     for (j=maxwav;j>=1;j--){
 5462:       cutv(stra, strb, line, ' '); 
 5463:       if(strb[0]=='.') { /* Missing status */
 5464: 	lval=-1;
 5465:       }else{
 5466: 	errno=0;
 5467: 	lval=strtol(strb,&endptr,10); 
 5468:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5469: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5470: 	  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);
 5471: 	  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);
 5472: 	  return 1;
 5473: 	}
 5474:       }
 5475:       s[j][i]=lval;
 5476:       
 5477:       strcpy(line,stra);
 5478:       cutv(stra, strb,line,' ');
 5479:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5480:       }
 5481:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5482: 	month=99;
 5483: 	year=9999;
 5484:       }else{
 5485: 	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);
 5486: 	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);
 5487: 	return 1;
 5488:       }
 5489:       anint[j][i]= (double) year; 
 5490:       mint[j][i]= (double)month; 
 5491:       strcpy(line,stra);
 5492:     } /* ENd Waves */
 5493:     
 5494:     cutv(stra, strb,line,' '); 
 5495:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5496:     }
 5497:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5498:       month=99;
 5499:       year=9999;
 5500:     }else{
 5501:       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);
 5502: 	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);
 5503: 	return 1;
 5504:     }
 5505:     andc[i]=(double) year; 
 5506:     moisdc[i]=(double) month; 
 5507:     strcpy(line,stra);
 5508:     
 5509:     cutv(stra, strb,line,' '); 
 5510:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5511:     }
 5512:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5513:       month=99;
 5514:       year=9999;
 5515:     }else{
 5516:       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);
 5517:       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);
 5518: 	return 1;
 5519:     }
 5520:     if (year==9999) {
 5521:       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);
 5522:       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);
 5523: 	return 1;
 5524: 
 5525:     }
 5526:     annais[i]=(double)(year);
 5527:     moisnais[i]=(double)(month); 
 5528:     strcpy(line,stra);
 5529:     
 5530:     cutv(stra, strb,line,' '); 
 5531:     errno=0;
 5532:     dval=strtod(strb,&endptr); 
 5533:     if( strb[0]=='\0' || (*endptr != '\0')){
 5534:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5535:       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);
 5536:       fflush(ficlog);
 5537:       return 1;
 5538:     }
 5539:     weight[i]=dval; 
 5540:     strcpy(line,stra);
 5541:     
 5542:     for (j=ncovcol;j>=1;j--){
 5543:       cutv(stra, strb,line,' '); 
 5544:       if(strb[0]=='.') { /* Missing status */
 5545: 	lval=-1;
 5546:       }else{
 5547: 	errno=0;
 5548: 	lval=strtol(strb,&endptr,10); 
 5549: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5550: 	  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);
 5551: 	  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);
 5552: 	  return 1;
 5553: 	}
 5554:       }
 5555:       if(lval <-1 || lval >1){
 5556: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5557:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5558:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5559:  For example, for multinomial values like 1, 2 and 3,\n \
 5560:  build V1=0 V2=0 for the reference value (1),\n \
 5561:         V1=1 V2=0 for (2) \n \
 5562:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5563:  output of IMaCh is often meaningless.\n \
 5564:  Exiting.\n",lval,linei, i,line,j);
 5565: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5566:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5567:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5568:  For example, for multinomial values like 1, 2 and 3,\n \
 5569:  build V1=0 V2=0 for the reference value (1),\n \
 5570:         V1=1 V2=0 for (2) \n \
 5571:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5572:  output of IMaCh is often meaningless.\n \
 5573:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5574: 	return 1;
 5575:       }
 5576:       covar[j][i]=(double)(lval);
 5577:       strcpy(line,stra);
 5578:     }  
 5579:     lstra=strlen(stra);
 5580:      
 5581:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5582:       stratrunc = &(stra[lstra-9]);
 5583:       num[i]=atol(stratrunc);
 5584:     }
 5585:     else
 5586:       num[i]=atol(stra);
 5587:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5588:       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;}*/
 5589:     
 5590:     i=i+1;
 5591:   } /* End loop reading  data */
 5592: 
 5593:   *imax=i-1; /* Number of individuals */
 5594:   fclose(fic);
 5595:  
 5596:   return (0);
 5597:   /* endread: */
 5598:     printf("Exiting readdata: ");
 5599:     fclose(fic);
 5600:     return (1);
 5601: 
 5602: 
 5603: 
 5604: }
 5605: void removespace(char *str) {
 5606:   char *p1 = str, *p2 = str;
 5607:   do
 5608:     while (*p2 == ' ')
 5609:       p2++;
 5610:   while (*p1++ == *p2++);
 5611: }
 5612: 
 5613: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5614:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 5615:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 5616:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 5617:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 5618:    * - cptcovage number of covariates with age*products =2
 5619:    * - cptcovs number of simple covariates
 5620:    * - 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
 5621:    *     which is a new column after the 9 (ncovcol) variables. 
 5622:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5623:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5624:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5625:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5626:  */
 5627: {
 5628:   int i, j, k, ks;
 5629:   int  j1, k1, k2;
 5630:   char modelsav[80];
 5631:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5632:   char *strpt;
 5633: 
 5634:   /*removespace(model);*/
 5635:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5636:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5637:     if (strstr(model,"AGE") !=0){
 5638:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 5639:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 5640:       return 1;
 5641:     }
 5642:     if (strstr(model,"v") !=0){
 5643:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5644:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5645:       return 1;
 5646:     }
 5647:     strcpy(modelsav,model); 
 5648:     if ((strpt=strstr(model,"age*age")) !=0){
 5649:       printf(" strpt=%s, model=%s\n",strpt, model);
 5650:       if(strpt != model){
 5651:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5652:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 5653:  corresponding column of parameters.\n",model);
 5654:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5655:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 5656:  corresponding column of parameters.\n",model); fflush(ficlog);
 5657:       return 1;
 5658:     }
 5659: 
 5660:       nagesqr=1;
 5661:       if (strstr(model,"+age*age") !=0)
 5662: 	substrchaine(modelsav, model, "+age*age");
 5663:       else if (strstr(model,"age*age+") !=0)
 5664: 	substrchaine(modelsav, model, "age*age+");
 5665:       else 
 5666: 	substrchaine(modelsav, model, "age*age");
 5667:     }else
 5668:       nagesqr=0;
 5669:     if (strlen(modelsav) >1){
 5670:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 5671:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 5672:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 5673:       cptcovt= j+1; /* Number of total covariates in the model, not including
 5674: 		   * cst, age and age*age 
 5675: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 5676:                   /* including age products which are counted in cptcovage.
 5677: 		  * but the covariates which are products must be treated 
 5678: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 5679:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5680:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5681: 
 5682:     
 5683:       /*   Design
 5684:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5685:        *  <          ncovcol=8                >
 5686:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5687:        *   k=  1    2      3       4     5       6      7        8
 5688:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5689:        *  covar[k,i], value of kth covariate if not including age for individual i:
 5690:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5691:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5692:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5693:        *  Tage[++cptcovage]=k
 5694:        *       if products, new covar are created after ncovcol with k1
 5695:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5696:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5697:        *  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
 5698:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5699:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5700:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5701:        *  <          ncovcol=8                >
 5702:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5703:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5704:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5705:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5706:        * p Tprod[1]@2={                         6, 5}
 5707:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 5708:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5709:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5710:        *How to reorganize?
 5711:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5712:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5713:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 5714:        * Struct []
 5715:        */
 5716: 
 5717:       /* This loop fills the array Tvar from the string 'model'.*/
 5718:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5719:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5720:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5721:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5722:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5723:       /* 	k=1 Tvar[1]=2 (from V2) */
 5724:       /* 	k=5 Tvar[5] */
 5725:       /* for (k=1; k<=cptcovn;k++) { */
 5726:       /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5727:       /* 	} */
 5728:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
 5729:       /*
 5730:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5731:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5732:         Tvar[k]=0;
 5733:       cptcovage=0;
 5734:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5735: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5736: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5737: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5738: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5739: 	/*scanf("%d",i);*/
 5740: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5741: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5742: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5743: 	    /* covar is not filled and then is empty */
 5744: 	    cptcovprod--;
 5745: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5746: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 5747: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 5748: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 5749: 	    /*printf("stre=%s ", stre);*/
 5750: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5751: 	    cptcovprod--;
 5752: 	    cutl(stre,strb,strc,'V');
 5753: 	    Tvar[k]=atoi(stre);
 5754: 	    cptcovage++;
 5755: 	    Tage[cptcovage]=k;
 5756: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5757: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5758: 	    cptcovn++;
 5759: 	    cptcovprodnoage++;k1++;
 5760: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5761: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5762: 				   because this model-covariate is a construction we invent a new column
 5763: 				   ncovcol + k1
 5764: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5765: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5766: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5767: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5768: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5769: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5770: 	    k2=k2+2;
 5771: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5772: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5773: 	    for (i=1; i<=lastobs;i++){
 5774: 	      /* Computes the new covariate which is a product of
 5775: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5776: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5777: 	    }
 5778: 	  } /* End age is not in the model */
 5779: 	} /* End if model includes a product */
 5780: 	else { /* no more sum */
 5781: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5782: 	  /*  scanf("%d",i);*/
 5783: 	  cutl(strd,strc,strb,'V');
 5784: 	  ks++; /**< Number of simple covariates */
 5785: 	  cptcovn++;
 5786: 	  Tvar[k]=atoi(strd);
 5787: 	}
 5788: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5789: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5790: 	  scanf("%d",i);*/
 5791:       } /* end of loop + on total covariates */
 5792:     } /* end if strlen(modelsave == 0) age*age might exist */
 5793:   } /* end if strlen(model == 0) */
 5794:   
 5795:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5796:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5797: 
 5798:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5799:   printf("cptcovprod=%d ", cptcovprod);
 5800:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5801: 
 5802:   scanf("%d ",i);*/
 5803: 
 5804: 
 5805:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5806:   /*endread:*/
 5807:     printf("Exiting decodemodel: ");
 5808:     return (1);
 5809: }
 5810: 
 5811: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5812: {
 5813:   int i, m;
 5814: 
 5815:   for (i=1; i<=imx; i++) {
 5816:     for(m=2; (m<= maxwav); m++) {
 5817:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5818: 	anint[m][i]=9999;
 5819: 	s[m][i]=-1;
 5820:       }
 5821:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5822: 	*nberr = *nberr + 1;
 5823: 	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);
 5824: 	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);
 5825: 	s[m][i]=-1;
 5826:       }
 5827:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5828: 	(*nberr)++;
 5829: 	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]); 
 5830: 	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]); 
 5831: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5832:       }
 5833:     }
 5834:   }
 5835: 
 5836:   for (i=1; i<=imx; i++)  {
 5837:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5838:     for(m=firstpass; (m<= lastpass); m++){
 5839:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5840: 	if (s[m][i] >= nlstate+1) {
 5841: 	  if(agedc[i]>0){
 5842: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5843: 	      agev[m][i]=agedc[i];
 5844: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5845: 	    }else {
 5846: 	      if ((int)andc[i]!=9999){
 5847: 		nbwarn++;
 5848: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5849: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5850: 		agev[m][i]=-1;
 5851: 	      }
 5852: 	    }
 5853: 	  } /* agedc > 0 */
 5854: 	}
 5855: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5856: 				 years but with the precision of a month */
 5857: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5858: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5859: 	    agev[m][i]=1;
 5860: 	  else if(agev[m][i] < *agemin){ 
 5861: 	    *agemin=agev[m][i];
 5862: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5863: 	  }
 5864: 	  else if(agev[m][i] >*agemax){
 5865: 	    *agemax=agev[m][i];
 5866: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5867: 	  }
 5868: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5869: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5870: 	}
 5871: 	else { /* =9 */
 5872: 	  agev[m][i]=1;
 5873: 	  s[m][i]=-1;
 5874: 	}
 5875:       }
 5876:       else /*= 0 Unknown */
 5877: 	agev[m][i]=1;
 5878:     }
 5879:     
 5880:   }
 5881:   for (i=1; i<=imx; i++)  {
 5882:     for(m=firstpass; (m<=lastpass); m++){
 5883:       if (s[m][i] > (nlstate+ndeath)) {
 5884: 	(*nberr)++;
 5885: 	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);	
 5886: 	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);	
 5887: 	return 1;
 5888:       }
 5889:     }
 5890:   }
 5891: 
 5892:   /*for (i=1; i<=imx; i++){
 5893:   for (m=firstpass; (m<lastpass); m++){
 5894:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5895: }
 5896: 
 5897: }*/
 5898: 
 5899: 
 5900:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5901:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5902: 
 5903:   return (0);
 5904:  /* endread:*/
 5905:     printf("Exiting calandcheckages: ");
 5906:     return (1);
 5907: }
 5908: 
 5909: #if defined(_MSC_VER)
 5910: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5911: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5912: //#include "stdafx.h"
 5913: //#include <stdio.h>
 5914: //#include <tchar.h>
 5915: //#include <windows.h>
 5916: //#include <iostream>
 5917: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5918: 
 5919: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5920: 
 5921: BOOL IsWow64()
 5922: {
 5923: 	BOOL bIsWow64 = FALSE;
 5924: 
 5925: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5926: 	//  (HANDLE, PBOOL);
 5927: 
 5928: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5929: 
 5930: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5931: 	const char funcName[] = "IsWow64Process";
 5932: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5933: 		GetProcAddress(module, funcName);
 5934: 
 5935: 	if (NULL != fnIsWow64Process)
 5936: 	{
 5937: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5938: 			&bIsWow64))
 5939: 			//throw std::exception("Unknown error");
 5940: 			printf("Unknown error\n");
 5941: 	}
 5942: 	return bIsWow64 != FALSE;
 5943: }
 5944: #endif
 5945: 
 5946: void syscompilerinfo(int logged)
 5947:  {
 5948:    /* #include "syscompilerinfo.h"*/
 5949:    /* command line Intel compiler 32bit windows, XP compatible:*/
 5950:    /* /GS /W3 /Gy
 5951:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 5952:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 5953:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 5954:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 5955:    */ 
 5956:    /* 64 bits */
 5957:    /*
 5958:      /GS /W3 /Gy
 5959:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 5960:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 5961:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 5962:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 5963:    /* Optimization are useless and O3 is slower than O2 */
 5964:    /*
 5965:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 5966:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 5967:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 5968:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 5969:    */
 5970:    /* Link is */ /* /OUT:"visual studio
 5971:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 5972:       /PDB:"visual studio
 5973:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 5974:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 5975:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 5976:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 5977:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 5978:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 5979:       uiAccess='false'"
 5980:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 5981:       /NOLOGO /TLBID:1
 5982:    */
 5983: #if defined __INTEL_COMPILER
 5984: #if defined(__GNUC__)
 5985: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 5986: #endif
 5987: #elif defined(__GNUC__) 
 5988: #ifndef  __APPLE__
 5989: #include <gnu/libc-version.h>  /* Only on gnu */
 5990: #endif
 5991:    struct utsname sysInfo;
 5992:    int cross = CROSS;
 5993:    if (cross){
 5994: 	   printf("Cross-");
 5995: 	   if(logged) fprintf(ficlog, "Cross-");
 5996:    }
 5997: #endif
 5998: 
 5999: #include <stdint.h>
 6000: 
 6001:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 6002: #if defined(__clang__)
 6003:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 6004: #endif
 6005: #if defined(__ICC) || defined(__INTEL_COMPILER)
 6006:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 6007: #endif
 6008: #if defined(__GNUC__) || defined(__GNUG__)
 6009:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 6010: #endif
 6011: #if defined(__HP_cc) || defined(__HP_aCC)
 6012:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 6013: #endif
 6014: #if defined(__IBMC__) || defined(__IBMCPP__)
 6015:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 6016: #endif
 6017: #if defined(_MSC_VER)
 6018:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 6019: #endif
 6020: #if defined(__PGI)
 6021:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 6022: #endif
 6023: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 6024:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 6025: #endif
 6026:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 6027:    
 6028: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 6029: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 6030:     // Windows (x64 and x86)
 6031:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 6032: #elif __unix__ // all unices, not all compilers
 6033:     // Unix
 6034:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 6035: #elif __linux__
 6036:     // linux
 6037:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 6038: #elif __APPLE__
 6039:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 6040:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 6041: #endif
 6042: 
 6043: /*  __MINGW32__	  */
 6044: /*  __CYGWIN__	 */
 6045: /* __MINGW64__  */
 6046: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 6047: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 6048: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 6049: /* _WIN64  // Defined for applications for Win64. */
 6050: /* _M_X64 // Defined for compilations that target x64 processors. */
 6051: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 6052: 
 6053: #if UINTPTR_MAX == 0xffffffff
 6054:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 6055: #elif UINTPTR_MAX == 0xffffffffffffffff
 6056:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 6057: #else
 6058:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 6059: #endif
 6060: 
 6061: #if defined(__GNUC__)
 6062: # if defined(__GNUC_PATCHLEVEL__)
 6063: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 6064:                             + __GNUC_MINOR__ * 100 \
 6065:                             + __GNUC_PATCHLEVEL__)
 6066: # else
 6067: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 6068:                             + __GNUC_MINOR__ * 100)
 6069: # endif
 6070:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 6071:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 6072: 
 6073:    if (uname(&sysInfo) != -1) {
 6074:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 6075: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 6076:    }
 6077:    else
 6078:       perror("uname() error");
 6079:    //#ifndef __INTEL_COMPILER 
 6080: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 6081:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 6082:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 6083: #endif
 6084: #endif
 6085: 
 6086:    //   void main()
 6087:    //   {
 6088: #if defined(_MSC_VER)
 6089:    if (IsWow64()){
 6090: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6091: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6092:    }
 6093:    else{
 6094: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6095: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6096:    }
 6097:    //	   printf("\nPress Enter to continue...");
 6098:    //	   getchar();
 6099:    //   }
 6100: 
 6101: #endif
 6102:    
 6103: 
 6104:  }
 6105: 
 6106: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
 6107:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6108:   int i, j, k, i1 ;
 6109:   double ftolpl = 1.e-10;
 6110:   double age, agebase, agelim;
 6111: 
 6112:     strcpy(filerespl,"pl");
 6113:     strcat(filerespl,fileres);
 6114:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6115:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6116:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6117:     }
 6118:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6119:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6120:     pstamp(ficrespl);
 6121:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 6122:     fprintf(ficrespl,"#Age ");
 6123:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6124:     fprintf(ficrespl,"\n");
 6125:   
 6126:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 6127: 
 6128:     agebase=ageminpar;
 6129:     agelim=agemaxpar;
 6130: 
 6131:     i1=pow(2,cptcoveff);
 6132:     if (cptcovn < 1){i1=1;}
 6133: 
 6134:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6135:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 6136:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6137: 	k=k+1;
 6138: 	/* to clean */
 6139: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
 6140: 	fprintf(ficrespl,"\n#******");
 6141: 	printf("\n#******");
 6142: 	fprintf(ficlog,"\n#******");
 6143: 	for(j=1;j<=cptcoveff;j++) {
 6144: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6145: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6146: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6147: 	}
 6148: 	fprintf(ficrespl,"******\n");
 6149: 	printf("******\n");
 6150: 	fprintf(ficlog,"******\n");
 6151: 
 6152: 	fprintf(ficrespl,"#Age ");
 6153: 	for(j=1;j<=cptcoveff;j++) {
 6154: 	  fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6155: 	}
 6156: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6157: 	fprintf(ficrespl,"\n");
 6158: 	
 6159: 	for (age=agebase; age<=agelim; age++){
 6160: 	/* for (age=agebase; age<=agebase; age++){ */
 6161: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6162: 	  fprintf(ficrespl,"%.0f ",age );
 6163: 	  for(j=1;j<=cptcoveff;j++)
 6164: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6165: 	  for(i=1; i<=nlstate;i++)
 6166: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6167: 	  fprintf(ficrespl,"\n");
 6168: 	} /* Age */
 6169: 	/* was end of cptcod */
 6170:     } /* cptcov */
 6171: 	return 0;
 6172: }
 6173: 
 6174: int hPijx(double *p, int bage, int fage){
 6175:     /*------------- h Pij x at various ages ------------*/
 6176: 
 6177:   int stepsize;
 6178:   int agelim;
 6179:   int hstepm;
 6180:   int nhstepm;
 6181:   int h, i, i1, j, k;
 6182: 
 6183:   double agedeb;
 6184:   double ***p3mat;
 6185: 
 6186:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 6187:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6188:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 6189:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 6190:     }
 6191:     printf("Computing pij: result on file '%s' \n", filerespij);
 6192:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6193:   
 6194:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6195:     /*if (stepm<=24) stepsize=2;*/
 6196: 
 6197:     agelim=AGESUP;
 6198:     hstepm=stepsize*YEARM; /* Every year of age */
 6199:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6200: 
 6201:     /* hstepm=1;   aff par mois*/
 6202:     pstamp(ficrespij);
 6203:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6204:     i1= pow(2,cptcoveff);
 6205:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 6206:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 6207:    /*  	k=k+1;  */
 6208:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6209:       fprintf(ficrespij,"\n#****** ");
 6210:       for(j=1;j<=cptcoveff;j++) 
 6211: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6212:       fprintf(ficrespij,"******\n");
 6213:       
 6214:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6215: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6216: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6217: 	
 6218: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6219: 	
 6220: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6221: 	oldm=oldms;savm=savms;
 6222: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6223: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6224: 	for(i=1; i<=nlstate;i++)
 6225: 	  for(j=1; j<=nlstate+ndeath;j++)
 6226: 	    fprintf(ficrespij," %1d-%1d",i,j);
 6227: 	fprintf(ficrespij,"\n");
 6228: 	for (h=0; h<=nhstepm; h++){
 6229: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 6230: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 6231: 	  for(i=1; i<=nlstate;i++)
 6232: 	    for(j=1; j<=nlstate+ndeath;j++)
 6233: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6234: 	  fprintf(ficrespij,"\n");
 6235: 	}
 6236: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6237: 	fprintf(ficrespij,"\n");
 6238:       }
 6239:       /*}*/
 6240:     }
 6241: 	return 0;
 6242: }
 6243: 
 6244: 
 6245: /***********************************************/
 6246: /**************** Main Program *****************/
 6247: /***********************************************/
 6248: 
 6249: int main(int argc, char *argv[])
 6250: {
 6251: #ifdef GSL
 6252:   const gsl_multimin_fminimizer_type *T;
 6253:   size_t iteri = 0, it;
 6254:   int rval = GSL_CONTINUE;
 6255:   int status = GSL_SUCCESS;
 6256:   double ssval;
 6257: #endif
 6258:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 6259:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 6260: 
 6261:   int jj, ll, li, lj, lk;
 6262:   int numlinepar=0; /* Current linenumber of parameter file */
 6263:   int itimes;
 6264:   int NDIM=2;
 6265:   int vpopbased=0;
 6266: 
 6267:   char ca[32], cb[32];
 6268:   /*  FILE *fichtm; *//* Html File */
 6269:   /* FILE *ficgp;*/ /*Gnuplot File */
 6270:   struct stat info;
 6271:   double agedeb=0.;
 6272:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 6273: 
 6274:   double fret;
 6275:   double dum=0.; /* Dummy variable */
 6276:   double ***p3mat;
 6277:   double ***mobaverage;
 6278: 
 6279:   char line[MAXLINE];
 6280:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 6281:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 6282:   char *tok, *val; /* pathtot */
 6283:   int firstobs=1, lastobs=10;
 6284:   int c,  h , cpt;
 6285:   int jl=0;
 6286:   int i1, j1, jk, stepsize=0;
 6287:   int *tab; 
 6288:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 6289:   int mobilav=0,popforecast=0;
 6290:   int hstepm=0, nhstepm=0;
 6291:   int agemortsup;
 6292:   float  sumlpop=0.;
 6293:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 6294:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 6295: 
 6296:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 6297:   double ftolpl=FTOL;
 6298:   double **prlim;
 6299:   double ***param; /* Matrix of parameters */
 6300:   double  *p;
 6301:   double **matcov; /* Matrix of covariance */
 6302:   double ***delti3; /* Scale */
 6303:   double *delti; /* Scale */
 6304:   double ***eij, ***vareij;
 6305:   double **varpl; /* Variances of prevalence limits by age */
 6306:   double *epj, vepp;
 6307: 
 6308:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 6309:   double **ximort;
 6310:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 6311:   int *dcwave;
 6312: 
 6313:   char z[1]="c";
 6314: 
 6315:   /*char  *strt;*/
 6316:   char strtend[80];
 6317: 
 6318: 
 6319: /*   setlocale (LC_ALL, ""); */
 6320: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 6321: /*   textdomain (PACKAGE); */
 6322: /*   setlocale (LC_CTYPE, ""); */
 6323: /*   setlocale (LC_MESSAGES, ""); */
 6324: 
 6325:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 6326:   rstart_time = time(NULL);  
 6327:   /*  (void) gettimeofday(&start_time,&tzp);*/
 6328:   start_time = *localtime(&rstart_time);
 6329:   curr_time=start_time;
 6330:   /*tml = *localtime(&start_time.tm_sec);*/
 6331:   /* strcpy(strstart,asctime(&tml)); */
 6332:   strcpy(strstart,asctime(&start_time));
 6333: 
 6334: /*  printf("Localtime (at start)=%s",strstart); */
 6335: /*  tp.tm_sec = tp.tm_sec +86400; */
 6336: /*  tm = *localtime(&start_time.tm_sec); */
 6337: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 6338: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 6339: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 6340: /*   tp.tm_sec = mktime(&tmg); */
 6341: /*   strt=asctime(&tmg); */
 6342: /*   printf("Time(after) =%s",strstart);  */
 6343: /*  (void) time (&time_value);
 6344: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 6345: *  tm = *localtime(&time_value);
 6346: *  strstart=asctime(&tm);
 6347: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 6348: */
 6349: 
 6350:   nberr=0; /* Number of errors and warnings */
 6351:   nbwarn=0;
 6352: #ifdef WIN32
 6353:   _getcwd(pathcd, size);
 6354: #else
 6355:   getcwd(pathcd, size);
 6356: #endif
 6357:   syscompilerinfo(0);
 6358:   printf("\n%s\n%s",version,fullversion);
 6359:   if(argc <=1){
 6360:     printf("\nEnter the parameter file name: ");
 6361:     fgets(pathr,FILENAMELENGTH,stdin);
 6362:     i=strlen(pathr);
 6363:     if(pathr[i-1]=='\n')
 6364:       pathr[i-1]='\0';
 6365:     i=strlen(pathr);
 6366:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 6367:       pathr[i-1]='\0';
 6368:    for (tok = pathr; tok != NULL; ){
 6369:       printf("Pathr |%s|\n",pathr);
 6370:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 6371:       printf("val= |%s| pathr=%s\n",val,pathr);
 6372:       strcpy (pathtot, val);
 6373:       if(pathr[0] == '\0') break; /* Dirty */
 6374:     }
 6375:   }
 6376:   else{
 6377:     strcpy(pathtot,argv[1]);
 6378:   }
 6379:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 6380:   /*cygwin_split_path(pathtot,path,optionfile);
 6381:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 6382:   /* cutv(path,optionfile,pathtot,'\\');*/
 6383: 
 6384:   /* Split argv[0], imach program to get pathimach */
 6385:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 6386:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6387:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6388:  /*   strcpy(pathimach,argv[0]); */
 6389:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 6390:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 6391:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 6392: #ifdef WIN32
 6393:   _chdir(path); /* Can be a relative path */
 6394:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 6395: #else
 6396:   chdir(path); /* Can be a relative path */
 6397:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 6398: #endif
 6399:   printf("Current directory %s!\n",pathcd);
 6400:   strcpy(command,"mkdir ");
 6401:   strcat(command,optionfilefiname);
 6402:   if((outcmd=system(command)) != 0){
 6403:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 6404:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 6405:     /* fclose(ficlog); */
 6406: /*     exit(1); */
 6407:   }
 6408: /*   if((imk=mkdir(optionfilefiname))<0){ */
 6409: /*     perror("mkdir"); */
 6410: /*   } */
 6411: 
 6412:   /*-------- arguments in the command line --------*/
 6413: 
 6414:   /* Main Log file */
 6415:   strcat(filelog, optionfilefiname);
 6416:   strcat(filelog,".log");    /* */
 6417:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 6418:     printf("Problem with logfile %s\n",filelog);
 6419:     goto end;
 6420:   }
 6421:   fprintf(ficlog,"Log filename:%s\n",filelog);
 6422:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 6423:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 6424:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 6425:  path=%s \n\
 6426:  optionfile=%s\n\
 6427:  optionfilext=%s\n\
 6428:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 6429: 
 6430:   syscompilerinfo(0);
 6431: 
 6432:   printf("Local time (at start):%s",strstart);
 6433:   fprintf(ficlog,"Local time (at start): %s",strstart);
 6434:   fflush(ficlog);
 6435: /*   (void) gettimeofday(&curr_time,&tzp); */
 6436: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 6437: 
 6438:   /* */
 6439:   strcpy(fileres,"r");
 6440:   strcat(fileres, optionfilefiname);
 6441:   strcat(fileres,".txt");    /* Other files have txt extension */
 6442: 
 6443:   /* Main ---------arguments file --------*/
 6444: 
 6445:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 6446:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6447:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6448:     fflush(ficlog);
 6449:     /* goto end; */
 6450:     exit(70); 
 6451:   }
 6452: 
 6453: 
 6454: 
 6455:   strcpy(filereso,"o");
 6456:   strcat(filereso,fileres);
 6457:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 6458:     printf("Problem with Output resultfile: %s\n", filereso);
 6459:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 6460:     fflush(ficlog);
 6461:     goto end;
 6462:   }
 6463: 
 6464:   /* Reads comments: lines beginning with '#' */
 6465:   numlinepar=0;
 6466:   while((c=getc(ficpar))=='#' && c!= EOF){
 6467:     ungetc(c,ficpar);
 6468:     fgets(line, MAXLINE, ficpar);
 6469:     numlinepar++;
 6470:     fputs(line,stdout);
 6471:     fputs(line,ficparo);
 6472:     fputs(line,ficlog);
 6473:   }
 6474:   ungetc(c,ficpar);
 6475: 
 6476:   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);
 6477:   numlinepar++;
 6478:   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);
 6479:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
 6480:     model[strlen(model)-1]='\0';
 6481:   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);
 6482:   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);
 6483:   fflush(ficlog);
 6484:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 6485:   if(model[0]=='#'){
 6486:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 6487:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 6488:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 6489:     if(mle != -1){
 6490:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 6491:       exit(1);
 6492:     }
 6493:   }
 6494:   while((c=getc(ficpar))=='#' && c!= EOF){
 6495:     ungetc(c,ficpar);
 6496:     fgets(line, MAXLINE, ficpar);
 6497:     numlinepar++;
 6498:     fputs(line, stdout);
 6499:     //puts(line);
 6500:     fputs(line,ficparo);
 6501:     fputs(line,ficlog);
 6502:   }
 6503:   ungetc(c,ficpar);
 6504: 
 6505:    
 6506:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 6507:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 6508:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 6509:      v1+v2*age+v2*v3 makes cptcovn = 3
 6510:   */
 6511:   if (strlen(model)>1) 
 6512:     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*/
 6513:   else
 6514:     ncovmodel=2; /* Constant and age */
 6515:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 6516:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 6517:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 6518:     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);
 6519:     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);
 6520:     fflush(stdout);
 6521:     fclose (ficlog);
 6522:     goto end;
 6523:   }
 6524:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6525:   delti=delti3[1][1];
 6526:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 6527:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 6528:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6529:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6530:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6531:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6532:     fclose (ficparo);
 6533:     fclose (ficlog);
 6534:     goto end;
 6535:     exit(0);
 6536:   }
 6537:   else if(mle==-3) { /* Main Wizard */
 6538:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6539:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6540:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6541:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6542:     matcov=matrix(1,npar,1,npar);
 6543:   }
 6544:   else{
 6545:     /* Read guessed parameters */
 6546:     /* Reads comments: lines beginning with '#' */
 6547:     while((c=getc(ficpar))=='#' && c!= EOF){
 6548:       ungetc(c,ficpar);
 6549:       fgets(line, MAXLINE, ficpar);
 6550:       numlinepar++;
 6551:       fputs(line,stdout);
 6552:       fputs(line,ficparo);
 6553:       fputs(line,ficlog);
 6554:     }
 6555:     ungetc(c,ficpar);
 6556:     
 6557:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6558:     for(i=1; i <=nlstate; i++){
 6559:       j=0;
 6560:       for(jj=1; jj <=nlstate+ndeath; jj++){
 6561: 	if(jj==i) continue;
 6562: 	j++;
 6563: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6564: 	if ((i1 != i) && (j1 != j)){
 6565: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 6566: It might be a problem of design; if ncovcol and the model are correct\n \
 6567: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 6568: 	  exit(1);
 6569: 	}
 6570: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6571: 	if(mle==1)
 6572: 	  printf("%1d%1d",i,j);
 6573: 	fprintf(ficlog,"%1d%1d",i,j);
 6574: 	for(k=1; k<=ncovmodel;k++){
 6575: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 6576: 	  if(mle==1){
 6577: 	    printf(" %lf",param[i][j][k]);
 6578: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6579: 	  }
 6580: 	  else
 6581: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6582: 	  fprintf(ficparo," %lf",param[i][j][k]);
 6583: 	}
 6584: 	fscanf(ficpar,"\n");
 6585: 	numlinepar++;
 6586: 	if(mle==1)
 6587: 	  printf("\n");
 6588: 	fprintf(ficlog,"\n");
 6589: 	fprintf(ficparo,"\n");
 6590:       }
 6591:     }  
 6592:     fflush(ficlog);
 6593: 
 6594:     /* Reads scales values */
 6595:     p=param[1][1];
 6596:     
 6597:     /* Reads comments: lines beginning with '#' */
 6598:     while((c=getc(ficpar))=='#' && c!= EOF){
 6599:       ungetc(c,ficpar);
 6600:       fgets(line, MAXLINE, ficpar);
 6601:       numlinepar++;
 6602:       fputs(line,stdout);
 6603:       fputs(line,ficparo);
 6604:       fputs(line,ficlog);
 6605:     }
 6606:     ungetc(c,ficpar);
 6607: 
 6608:     for(i=1; i <=nlstate; i++){
 6609:       for(j=1; j <=nlstate+ndeath-1; j++){
 6610: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6611: 	if ( (i1-i) * (j1-j) != 0){
 6612: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 6613: 	  exit(1);
 6614: 	}
 6615: 	printf("%1d%1d",i,j);
 6616: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6617: 	fprintf(ficlog,"%1d%1d",i1,j1);
 6618: 	for(k=1; k<=ncovmodel;k++){
 6619: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 6620: 	  printf(" %le",delti3[i][j][k]);
 6621: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 6622: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 6623: 	}
 6624: 	fscanf(ficpar,"\n");
 6625: 	numlinepar++;
 6626: 	printf("\n");
 6627: 	fprintf(ficparo,"\n");
 6628: 	fprintf(ficlog,"\n");
 6629:       }
 6630:     }
 6631:     fflush(ficlog);
 6632: 
 6633:     /* Reads covariance matrix */
 6634:     delti=delti3[1][1];
 6635: 
 6636: 
 6637:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 6638:   
 6639:     /* Reads comments: lines beginning with '#' */
 6640:     while((c=getc(ficpar))=='#' && c!= EOF){
 6641:       ungetc(c,ficpar);
 6642:       fgets(line, MAXLINE, ficpar);
 6643:       numlinepar++;
 6644:       fputs(line,stdout);
 6645:       fputs(line,ficparo);
 6646:       fputs(line,ficlog);
 6647:     }
 6648:     ungetc(c,ficpar);
 6649:   
 6650:     matcov=matrix(1,npar,1,npar);
 6651:     for(i=1; i <=npar; i++)
 6652:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6653:       
 6654:     for(i=1; i <=npar; i++){
 6655:       fscanf(ficpar,"%s",str);
 6656:       if(mle==1)
 6657: 	printf("%s",str);
 6658:       fprintf(ficlog,"%s",str);
 6659:       fprintf(ficparo,"%s",str);
 6660:       for(j=1; j <=i; j++){
 6661: 	fscanf(ficpar," %le",&matcov[i][j]);
 6662: 	if(mle==1){
 6663: 	  printf(" %.5le",matcov[i][j]);
 6664: 	}
 6665: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6666: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6667:       }
 6668:       fscanf(ficpar,"\n");
 6669:       numlinepar++;
 6670:       if(mle==1)
 6671: 	printf("\n");
 6672:       fprintf(ficlog,"\n");
 6673:       fprintf(ficparo,"\n");
 6674:     }
 6675:     for(i=1; i <=npar; i++)
 6676:       for(j=i+1;j<=npar;j++)
 6677: 	matcov[i][j]=matcov[j][i];
 6678:     
 6679:     if(mle==1)
 6680:       printf("\n");
 6681:     fprintf(ficlog,"\n");
 6682:     
 6683:     fflush(ficlog);
 6684:     
 6685:     /*-------- Rewriting parameter file ----------*/
 6686:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6687:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6688:     strcat(rfileres,".");    /* */
 6689:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6690:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6691:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6692:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6693:     }
 6694:     fprintf(ficres,"#%s\n",version);
 6695:   }    /* End of mle != -3 */
 6696: 
 6697:   /*  Main data
 6698:    */
 6699:   n= lastobs;
 6700:   num=lvector(1,n);
 6701:   moisnais=vector(1,n);
 6702:   annais=vector(1,n);
 6703:   moisdc=vector(1,n);
 6704:   andc=vector(1,n);
 6705:   agedc=vector(1,n);
 6706:   cod=ivector(1,n);
 6707:   weight=vector(1,n);
 6708:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6709:   mint=matrix(1,maxwav,1,n);
 6710:   anint=matrix(1,maxwav,1,n);
 6711:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6712:   tab=ivector(1,NCOVMAX);
 6713:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6714:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6715: 
 6716:   /* Reads data from file datafile */
 6717:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6718:     goto end;
 6719: 
 6720:   /* Calculation of the number of parameters from char model */
 6721:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6722: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6723: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6724: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6725: 	k=1 Tvar[1]=2 (from V2)
 6726:     */
 6727:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6728:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6729:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6730:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6731:   */
 6732:   /* For model-covariate k tells which data-covariate to use but
 6733:     because this model-covariate is a construction we invent a new column
 6734:     ncovcol + k1
 6735:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6736:     Tvar[3=V1*V4]=4+1 etc */
 6737:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6738:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6739:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6740:   */
 6741:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6742:   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
 6743: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6744: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6745:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6746: 			 4 covariates (3 plus signs)
 6747: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6748: 		      */  
 6749: 
 6750: /* Main decodemodel */
 6751: 
 6752: 
 6753:   if(decodemodel(model, lastobs) == 1)
 6754:     goto end;
 6755: 
 6756:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6757:     nbwarn++;
 6758:     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); 
 6759:     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); 
 6760:   }
 6761:     /*  if(mle==1){*/
 6762:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6763:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6764:   }
 6765: 
 6766:     /*-calculation of age at interview from date of interview and age at death -*/
 6767:   agev=matrix(1,maxwav,1,imx);
 6768: 
 6769:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6770:     goto end;
 6771: 
 6772: 
 6773:   agegomp=(int)agemin;
 6774:   free_vector(moisnais,1,n);
 6775:   free_vector(annais,1,n);
 6776:   /* free_matrix(mint,1,maxwav,1,n);
 6777:      free_matrix(anint,1,maxwav,1,n);*/
 6778:   free_vector(moisdc,1,n);
 6779:   free_vector(andc,1,n);
 6780:   /* */
 6781:   
 6782:   wav=ivector(1,imx);
 6783:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6784:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6785:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6786:    
 6787:   /* Concatenates waves */
 6788:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6789:   /* */
 6790:  
 6791:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6792: 
 6793:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6794:   ncodemax[1]=1;
 6795:   Ndum =ivector(-1,NCOVMAX);  
 6796:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 6797:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6798:   /* Nbcode gives the value of the lth modality of jth covariate, in
 6799:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 6800:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
 6801: 
 6802:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6803:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6804:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 6805:   h=0;
 6806: 
 6807: 
 6808:   /*if (cptcovn > 0) */
 6809:       
 6810:  
 6811:   m=pow(2,cptcoveff);
 6812:  
 6813:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6814:     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 */ 
 6815:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6816: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6817: 	  h++;
 6818: 	  if (h>m) 
 6819: 	    h=1;
 6820: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6821: 	   * For k=4 covariates, h goes from 1 to 2**k
 6822: 	   * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
 6823: 	   *     h\k   1     2     3     4
 6824: 	   *______________________________  
 6825: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6826: 	   *     2     2     1     1     1
 6827: 	   *     3 i=2 1     2     1     1
 6828: 	   *     4     2     2     1     1
 6829: 	   *     5 i=3 1 i=2 1     2     1
 6830: 	   *     6     2     1     2     1
 6831: 	   *     7 i=4 1     2     2     1
 6832: 	   *     8     2     2     2     1
 6833: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6834: 	   *    10     2     1     1     1
 6835: 	   *    11 i=6 1     2     1     1
 6836: 	   *    12     2     2     1     1
 6837: 	   *    13 i=7 1 i=4 1     2     1    
 6838: 	   *    14     2     1     2     1
 6839: 	   *    15 i=8 1     2     2     1
 6840: 	   *    16     2     2     2     1
 6841: 	   */
 6842: 	  codtab[h][k]=j;
 6843: 	  /* codtab[12][3]=1; */
 6844: 	  /*codtab[h][Tvar[k]]=j;*/
 6845: 	  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]]);
 6846: 	} 
 6847:       }
 6848:     }
 6849:   } 
 6850:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6851:      codtab[1][2]=1;codtab[2][2]=2; */
 6852:   /* for(i=1; i <=m ;i++){ 
 6853:      for(k=1; k <=cptcovn; k++){
 6854:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6855:      }
 6856:      printf("\n");
 6857:      }
 6858:      scanf("%d",i);*/
 6859: 
 6860:  free_ivector(Ndum,-1,NCOVMAX);
 6861: 
 6862: 
 6863:     
 6864:   /* Initialisation of ----------- gnuplot -------------*/
 6865:   strcpy(optionfilegnuplot,optionfilefiname);
 6866:   if(mle==-3)
 6867:     strcat(optionfilegnuplot,"-mort");
 6868:   strcat(optionfilegnuplot,".gp");
 6869: 
 6870:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6871:     printf("Problem with file %s",optionfilegnuplot);
 6872:   }
 6873:   else{
 6874:     fprintf(ficgp,"\n# %s\n", version); 
 6875:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6876:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6877:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6878:   }
 6879:   /*  fclose(ficgp);*/
 6880: 
 6881: 
 6882:   /* Initialisation of --------- index.htm --------*/
 6883: 
 6884:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6885:   if(mle==-3)
 6886:     strcat(optionfilehtm,"-mort");
 6887:   strcat(optionfilehtm,".htm");
 6888:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6889:     printf("Problem with %s \n",optionfilehtm);
 6890:     exit(0);
 6891:   }
 6892: 
 6893:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6894:   strcat(optionfilehtmcov,"-cov.htm");
 6895:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6896:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6897:   }
 6898:   else{
 6899:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6900: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6901: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6902: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6903:   }
 6904: 
 6905:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6906: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6907: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6908: \n\
 6909: <hr  size=\"2\" color=\"#EC5E5E\">\
 6910:  <ul><li><h4>Parameter files</h4>\n\
 6911:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6912:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6913:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6914:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6915:  - Date and time at start: %s</ul>\n",\
 6916: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6917: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6918: 	  fileres,fileres,\
 6919: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6920:   fflush(fichtm);
 6921: 
 6922:   strcpy(pathr,path);
 6923:   strcat(pathr,optionfilefiname);
 6924: #ifdef WIN32
 6925:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 6926: #else
 6927:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6928: #endif
 6929: 	  
 6930:   
 6931:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6932:      and prints on file fileres'p'. */
 6933:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6934: 
 6935:   fprintf(fichtm,"\n");
 6936:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6937: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6938: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6939: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6940:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6941:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6942:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6943:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6944:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6945:     
 6946:    
 6947:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6948:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6949:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6950: 
 6951:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6952:   /* For mortality only */
 6953:   if (mle==-3){
 6954:     ximort=matrix(1,NDIM,1,NDIM); 
 6955:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6956:     cens=ivector(1,n);
 6957:     ageexmed=vector(1,n);
 6958:     agecens=vector(1,n);
 6959:     dcwave=ivector(1,n);
 6960:  
 6961:     for (i=1; i<=imx; i++){
 6962:       dcwave[i]=-1;
 6963:       for (m=firstpass; m<=lastpass; m++)
 6964: 	if (s[m][i]>nlstate) {
 6965: 	  dcwave[i]=m;
 6966: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6967: 	  break;
 6968: 	}
 6969:     }
 6970: 
 6971:     for (i=1; i<=imx; i++) {
 6972:       if (wav[i]>0){
 6973: 	ageexmed[i]=agev[mw[1][i]][i];
 6974: 	j=wav[i];
 6975: 	agecens[i]=1.; 
 6976: 
 6977: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6978: 	  agecens[i]=agev[mw[j][i]][i];
 6979: 	  cens[i]= 1;
 6980: 	}else if (ageexmed[i]< 1) 
 6981: 	  cens[i]= -1;
 6982: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6983: 	  cens[i]=0 ;
 6984:       }
 6985:       else cens[i]=-1;
 6986:     }
 6987:     
 6988:     for (i=1;i<=NDIM;i++) {
 6989:       for (j=1;j<=NDIM;j++)
 6990: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6991:     }
 6992:     
 6993:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6994:     /*printf("%lf %lf", p[1], p[2]);*/
 6995:     
 6996:     
 6997: #ifdef GSL
 6998:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6999: #else
 7000:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 7001: #endif
 7002:     strcpy(filerespow,"pow-mort"); 
 7003:     strcat(filerespow,fileres);
 7004:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 7005:       printf("Problem with resultfile: %s\n", filerespow);
 7006:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 7007:     }
 7008: #ifdef GSL
 7009:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 7010: #else
 7011:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 7012: #endif
 7013:     /*  for (i=1;i<=nlstate;i++)
 7014: 	for(j=1;j<=nlstate+ndeath;j++)
 7015: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 7016:     */
 7017:     fprintf(ficrespow,"\n");
 7018: #ifdef GSL
 7019:     /* gsl starts here */ 
 7020:     T = gsl_multimin_fminimizer_nmsimplex;
 7021:     gsl_multimin_fminimizer *sfm = NULL;
 7022:     gsl_vector *ss, *x;
 7023:     gsl_multimin_function minex_func;
 7024: 
 7025:     /* Initial vertex size vector */
 7026:     ss = gsl_vector_alloc (NDIM);
 7027:     
 7028:     if (ss == NULL){
 7029:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 7030:     }
 7031:     /* Set all step sizes to 1 */
 7032:     gsl_vector_set_all (ss, 0.001);
 7033: 
 7034:     /* Starting point */
 7035:     
 7036:     x = gsl_vector_alloc (NDIM);
 7037:     
 7038:     if (x == NULL){
 7039:       gsl_vector_free(ss);
 7040:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 7041:     }
 7042:   
 7043:     /* Initialize method and iterate */
 7044:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 7045:     /*     gsl_vector_set(x, 0, 0.0268); */
 7046:     /*     gsl_vector_set(x, 1, 0.083); */
 7047:     gsl_vector_set(x, 0, p[1]);
 7048:     gsl_vector_set(x, 1, p[2]);
 7049: 
 7050:     minex_func.f = &gompertz_f;
 7051:     minex_func.n = NDIM;
 7052:     minex_func.params = (void *)&p; /* ??? */
 7053:     
 7054:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 7055:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 7056:     
 7057:     printf("Iterations beginning .....\n\n");
 7058:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 7059: 
 7060:     iteri=0;
 7061:     while (rval == GSL_CONTINUE){
 7062:       iteri++;
 7063:       status = gsl_multimin_fminimizer_iterate(sfm);
 7064:       
 7065:       if (status) printf("error: %s\n", gsl_strerror (status));
 7066:       fflush(0);
 7067:       
 7068:       if (status) 
 7069:         break;
 7070:       
 7071:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 7072:       ssval = gsl_multimin_fminimizer_size (sfm);
 7073:       
 7074:       if (rval == GSL_SUCCESS)
 7075:         printf ("converged to a local maximum at\n");
 7076:       
 7077:       printf("%5d ", iteri);
 7078:       for (it = 0; it < NDIM; it++){
 7079: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 7080:       }
 7081:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 7082:     }
 7083:     
 7084:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 7085:     
 7086:     gsl_vector_free(x); /* initial values */
 7087:     gsl_vector_free(ss); /* inital step size */
 7088:     for (it=0; it<NDIM; it++){
 7089:       p[it+1]=gsl_vector_get(sfm->x,it);
 7090:       fprintf(ficrespow," %.12lf", p[it]);
 7091:     }
 7092:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 7093: #endif
 7094: #ifdef POWELL
 7095:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 7096: #endif  
 7097:     fclose(ficrespow);
 7098:     
 7099:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 7100: 
 7101:     for(i=1; i <=NDIM; i++)
 7102:       for(j=i+1;j<=NDIM;j++)
 7103: 	matcov[i][j]=matcov[j][i];
 7104:     
 7105:     printf("\nCovariance matrix\n ");
 7106:     for(i=1; i <=NDIM; i++) {
 7107:       for(j=1;j<=NDIM;j++){ 
 7108: 	printf("%f ",matcov[i][j]);
 7109:       }
 7110:       printf("\n ");
 7111:     }
 7112:     
 7113:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 7114:     for (i=1;i<=NDIM;i++) 
 7115:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 7116: 
 7117:     lsurv=vector(1,AGESUP);
 7118:     lpop=vector(1,AGESUP);
 7119:     tpop=vector(1,AGESUP);
 7120:     lsurv[agegomp]=100000;
 7121:     
 7122:     for (k=agegomp;k<=AGESUP;k++) {
 7123:       agemortsup=k;
 7124:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 7125:     }
 7126:     
 7127:     for (k=agegomp;k<agemortsup;k++)
 7128:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 7129:     
 7130:     for (k=agegomp;k<agemortsup;k++){
 7131:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 7132:       sumlpop=sumlpop+lpop[k];
 7133:     }
 7134:     
 7135:     tpop[agegomp]=sumlpop;
 7136:     for (k=agegomp;k<(agemortsup-3);k++){
 7137:       /*  tpop[k+1]=2;*/
 7138:       tpop[k+1]=tpop[k]-lpop[k];
 7139:     }
 7140:     
 7141:     
 7142:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 7143:     for (k=agegomp;k<(agemortsup-2);k++) 
 7144:       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]);
 7145:     
 7146:     
 7147:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7148:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7149:     
 7150:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 7151: 		     stepm, weightopt,\
 7152: 		     model,imx,p,matcov,agemortsup);
 7153:     
 7154:     free_vector(lsurv,1,AGESUP);
 7155:     free_vector(lpop,1,AGESUP);
 7156:     free_vector(tpop,1,AGESUP);
 7157: #ifdef GSL
 7158:     free_ivector(cens,1,n);
 7159:     free_vector(agecens,1,n);
 7160:     free_ivector(dcwave,1,n);
 7161:     free_matrix(ximort,1,NDIM,1,NDIM);
 7162: #endif
 7163:   } /* Endof if mle==-3 mortality only */
 7164:   /* Standard maximisation */
 7165:   else{ /* For mle >=1 */
 7166:     globpr=0;/* debug */
 7167:     /* Computes likelihood for initial parameters */
 7168:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7169:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7170:     for (k=1; k<=npar;k++)
 7171:       printf(" %d %8.5f",k,p[k]);
 7172:     printf("\n");
 7173:     globpr=1; /* again, to print the contributions */
 7174:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7175:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7176:     for (k=1; k<=npar;k++)
 7177:       printf(" %d %8.5f",k,p[k]);
 7178:     printf("\n");
 7179:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
 7180:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 7181:     }
 7182:     
 7183:     /*--------- results files --------------*/
 7184:     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);
 7185:     
 7186:     
 7187:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7188:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7189:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7190:     for(i=1,jk=1; i <=nlstate; i++){
 7191:       for(k=1; k <=(nlstate+ndeath); k++){
 7192: 	if (k != i) {
 7193: 	  printf("%d%d ",i,k);
 7194: 	  fprintf(ficlog,"%d%d ",i,k);
 7195: 	  fprintf(ficres,"%1d%1d ",i,k);
 7196: 	  for(j=1; j <=ncovmodel; j++){
 7197: 	    printf("%12.7f ",p[jk]);
 7198: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 7199: 	    fprintf(ficres,"%12.7f ",p[jk]);
 7200: 	    jk++; 
 7201: 	  }
 7202: 	  printf("\n");
 7203: 	  fprintf(ficlog,"\n");
 7204: 	  fprintf(ficres,"\n");
 7205: 	}
 7206:       }
 7207:     }
 7208:     if(mle!=0){
 7209:       /* Computing hessian and covariance matrix */
 7210:       ftolhess=ftol; /* Usually correct */
 7211:       hesscov(matcov, p, npar, delti, ftolhess, func);
 7212:     }
 7213:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 7214:     printf("# Scales (for hessian or gradient estimation)\n");
 7215:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 7216:     for(i=1,jk=1; i <=nlstate; i++){
 7217:       for(j=1; j <=nlstate+ndeath; j++){
 7218: 	if (j!=i) {
 7219: 	  fprintf(ficres,"%1d%1d",i,j);
 7220: 	  printf("%1d%1d",i,j);
 7221: 	  fprintf(ficlog,"%1d%1d",i,j);
 7222: 	  for(k=1; k<=ncovmodel;k++){
 7223: 	    printf(" %.5e",delti[jk]);
 7224: 	    fprintf(ficlog," %.5e",delti[jk]);
 7225: 	    fprintf(ficres," %.5e",delti[jk]);
 7226: 	    jk++;
 7227: 	  }
 7228: 	  printf("\n");
 7229: 	  fprintf(ficlog,"\n");
 7230: 	  fprintf(ficres,"\n");
 7231: 	}
 7232:       }
 7233:     }
 7234:     
 7235:     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");
 7236:     if(mle>=1)
 7237:       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");
 7238:     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");
 7239:     /* # 121 Var(a12)\n\ */
 7240:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7241:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7242:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7243:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7244:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7245:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7246:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7247:     
 7248:     
 7249:     /* Just to have a covariance matrix which will be more understandable
 7250:        even is we still don't want to manage dictionary of variables
 7251:     */
 7252:     for(itimes=1;itimes<=2;itimes++){
 7253:       jj=0;
 7254:       for(i=1; i <=nlstate; i++){
 7255: 	for(j=1; j <=nlstate+ndeath; j++){
 7256: 	  if(j==i) continue;
 7257: 	  for(k=1; k<=ncovmodel;k++){
 7258: 	    jj++;
 7259: 	    ca[0]= k+'a'-1;ca[1]='\0';
 7260: 	    if(itimes==1){
 7261: 	      if(mle>=1)
 7262: 		printf("#%1d%1d%d",i,j,k);
 7263: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 7264: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 7265: 	    }else{
 7266: 	      if(mle>=1)
 7267: 		printf("%1d%1d%d",i,j,k);
 7268: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 7269: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 7270: 	    }
 7271: 	    ll=0;
 7272: 	    for(li=1;li <=nlstate; li++){
 7273: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 7274: 		if(lj==li) continue;
 7275: 		for(lk=1;lk<=ncovmodel;lk++){
 7276: 		  ll++;
 7277: 		  if(ll<=jj){
 7278: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 7279: 		    if(ll<jj){
 7280: 		      if(itimes==1){
 7281: 			if(mle>=1)
 7282: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7283: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7284: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7285: 		      }else{
 7286: 			if(mle>=1)
 7287: 			  printf(" %.5e",matcov[jj][ll]); 
 7288: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7289: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7290: 		      }
 7291: 		    }else{
 7292: 		      if(itimes==1){
 7293: 			if(mle>=1)
 7294: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 7295: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 7296: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 7297: 		      }else{
 7298: 			if(mle>=1)
 7299: 			  printf(" %.5e",matcov[jj][ll]); 
 7300: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7301: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7302: 		      }
 7303: 		    }
 7304: 		  }
 7305: 		} /* end lk */
 7306: 	      } /* end lj */
 7307: 	    } /* end li */
 7308: 	    if(mle>=1)
 7309: 	      printf("\n");
 7310: 	    fprintf(ficlog,"\n");
 7311: 	    fprintf(ficres,"\n");
 7312: 	    numlinepar++;
 7313: 	  } /* end k*/
 7314: 	} /*end j */
 7315:       } /* end i */
 7316:     } /* end itimes */
 7317:     
 7318:     fflush(ficlog);
 7319:     fflush(ficres);
 7320:     
 7321:     while((c=getc(ficpar))=='#' && c!= EOF){
 7322:       ungetc(c,ficpar);
 7323:       fgets(line, MAXLINE, ficpar);
 7324:       fputs(line,stdout);
 7325:       fputs(line,ficparo);
 7326:     }
 7327:     ungetc(c,ficpar);
 7328:     
 7329:     estepm=0;
 7330:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 7331:     if (estepm==0 || estepm < stepm) estepm=stepm;
 7332:     if (fage <= 2) {
 7333:       bage = ageminpar;
 7334:       fage = agemaxpar;
 7335:     }
 7336:     
 7337:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 7338:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7339:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7340: 
 7341:     /* Other stuffs, more or less useful */    
 7342:     while((c=getc(ficpar))=='#' && c!= EOF){
 7343:       ungetc(c,ficpar);
 7344:       fgets(line, MAXLINE, ficpar);
 7345:       fputs(line,stdout);
 7346:       fputs(line,ficparo);
 7347:     }
 7348:     ungetc(c,ficpar);
 7349:     
 7350:     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);
 7351:     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);
 7352:     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);
 7353:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 7354:     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);
 7355:     
 7356:     while((c=getc(ficpar))=='#' && c!= EOF){
 7357:       ungetc(c,ficpar);
 7358:       fgets(line, MAXLINE, ficpar);
 7359:       fputs(line,stdout);
 7360:       fputs(line,ficparo);
 7361:     }
 7362:     ungetc(c,ficpar);
 7363:     
 7364:     
 7365:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 7366:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 7367:     
 7368:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 7369:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 7370:     fprintf(ficres,"pop_based=%d\n",popbased);   
 7371:     
 7372:     while((c=getc(ficpar))=='#' && c!= EOF){
 7373:       ungetc(c,ficpar);
 7374:       fgets(line, MAXLINE, ficpar);
 7375:       fputs(line,stdout);
 7376:       fputs(line,ficparo);
 7377:     }
 7378:     ungetc(c,ficpar);
 7379:     
 7380:     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);
 7381:     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);
 7382:     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);
 7383:     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);
 7384:     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);
 7385:     /* day and month of proj2 are not used but only year anproj2.*/
 7386:     
 7387:     
 7388:     
 7389:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 7390:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 7391:     
 7392:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7393:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7394:     
 7395:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 7396: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 7397: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 7398:       
 7399:    /*------------ free_vector  -------------*/
 7400:    /*  chdir(path); */
 7401:  
 7402:     free_ivector(wav,1,imx);
 7403:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 7404:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 7405:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 7406:     free_lvector(num,1,n);
 7407:     free_vector(agedc,1,n);
 7408:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 7409:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 7410:     fclose(ficparo);
 7411:     fclose(ficres);
 7412: 
 7413: 
 7414:     /* Other results (useful)*/
 7415: 
 7416: 
 7417:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7418:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 7419:     prlim=matrix(1,nlstate,1,nlstate);
 7420:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
 7421:     fclose(ficrespl);
 7422: 
 7423: #ifdef FREEEXIT2
 7424: #include "freeexit2.h"
 7425: #endif
 7426: 
 7427:     /*------------- h Pij x at various ages ------------*/
 7428:     /*#include "hpijx.h"*/
 7429:     hPijx(p, bage, fage);
 7430:     fclose(ficrespij);
 7431: 
 7432:   /*-------------- Variance of one-step probabilities---*/
 7433:     k=1;
 7434:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 7435: 
 7436: 
 7437:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7438:     for(i=1;i<=AGESUP;i++)
 7439:       for(j=1;j<=NCOVMAX;j++)
 7440: 	for(k=1;k<=NCOVMAX;k++)
 7441: 	  probs[i][j][k]=0.;
 7442: 
 7443:     /*---------- Forecasting ------------------*/
 7444:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 7445:     if(prevfcast==1){
 7446:       /*    if(stepm ==1){*/
 7447:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 7448:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 7449:       /*      }  */
 7450:       /*      else{ */
 7451:       /*        erreur=108; */
 7452:       /*        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); */
 7453:       /*        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); */
 7454:       /*      } */
 7455:     }
 7456:  
 7457:     /* ------ Other prevalence ratios------------ */
 7458: 
 7459:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 7460: 
 7461:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 7462:     /*  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",\
 7463: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 7464:     */
 7465: 
 7466:     if (mobilav!=0) {
 7467:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7468:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 7469: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 7470: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 7471:       }
 7472:     }
 7473: 
 7474: 
 7475:     /*---------- Health expectancies, no variances ------------*/
 7476: 
 7477:     strcpy(filerese,"e");
 7478:     strcat(filerese,fileres);
 7479:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 7480:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7481:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7482:     }
 7483:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 7484:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 7485:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7486:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7487:           
 7488:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7489: 	fprintf(ficreseij,"\n#****** ");
 7490: 	for(j=1;j<=cptcoveff;j++) {
 7491: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7492: 	}
 7493: 	fprintf(ficreseij,"******\n");
 7494: 
 7495: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7496: 	oldm=oldms;savm=savms;
 7497: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 7498:       
 7499: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7500:       /*}*/
 7501:     }
 7502:     fclose(ficreseij);
 7503: 
 7504: 
 7505:     /*---------- Health expectancies and variances ------------*/
 7506: 
 7507: 
 7508:     strcpy(filerest,"t");
 7509:     strcat(filerest,fileres);
 7510:     if((ficrest=fopen(filerest,"w"))==NULL) {
 7511:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 7512:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 7513:     }
 7514:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7515:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7516: 
 7517: 
 7518:     strcpy(fileresstde,"stde");
 7519:     strcat(fileresstde,fileres);
 7520:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 7521:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7522:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7523:     }
 7524:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7525:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7526: 
 7527:     strcpy(filerescve,"cve");
 7528:     strcat(filerescve,fileres);
 7529:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 7530:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7531:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7532:     }
 7533:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7534:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7535: 
 7536:     strcpy(fileresv,"v");
 7537:     strcat(fileresv,fileres);
 7538:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 7539:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 7540:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 7541:     }
 7542:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7543:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7544: 
 7545:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7546:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7547:           
 7548:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7549:     	fprintf(ficrest,"\n#****** ");
 7550: 	for(j=1;j<=cptcoveff;j++) 
 7551: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7552: 	fprintf(ficrest,"******\n");
 7553: 
 7554: 	fprintf(ficresstdeij,"\n#****** ");
 7555: 	fprintf(ficrescveij,"\n#****** ");
 7556: 	for(j=1;j<=cptcoveff;j++) {
 7557: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7558: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7559: 	}
 7560: 	fprintf(ficresstdeij,"******\n");
 7561: 	fprintf(ficrescveij,"******\n");
 7562: 
 7563: 	fprintf(ficresvij,"\n#****** ");
 7564: 	for(j=1;j<=cptcoveff;j++) 
 7565: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7566: 	fprintf(ficresvij,"******\n");
 7567: 
 7568: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7569: 	oldm=oldms;savm=savms;
 7570: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 7571: 	/*
 7572: 	 */
 7573: 	/* goto endfree; */
 7574:  
 7575: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7576: 	pstamp(ficrest);
 7577: 
 7578: 
 7579: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 7580: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 7581: 	  cptcod= 0; /* To be deleted */
 7582: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
 7583: 	  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 ");
 7584: 	  if(vpopbased==1)
 7585: 	    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);
 7586: 	  else
 7587: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 7588: 	  fprintf(ficrest,"# Age e.. (std) ");
 7589: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 7590: 	  fprintf(ficrest,"\n");
 7591: 
 7592: 	  epj=vector(1,nlstate+1);
 7593: 	  for(age=bage; age <=fage ;age++){
 7594: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 7595: 	    if (vpopbased==1) {
 7596: 	      if(mobilav ==0){
 7597: 		for(i=1; i<=nlstate;i++)
 7598: 		  prlim[i][i]=probs[(int)age][i][k];
 7599: 	      }else{ /* mobilav */ 
 7600: 		for(i=1; i<=nlstate;i++)
 7601: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 7602: 	      }
 7603: 	    }
 7604: 	
 7605: 	    fprintf(ficrest," %4.0f",age);
 7606: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 7607: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 7608: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 7609: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 7610: 	      }
 7611: 	      epj[nlstate+1] +=epj[j];
 7612: 	    }
 7613: 
 7614: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 7615: 	      for(j=1;j <=nlstate;j++)
 7616: 		vepp += vareij[i][j][(int)age];
 7617: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 7618: 	    for(j=1;j <=nlstate;j++){
 7619: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 7620: 	    }
 7621: 	    fprintf(ficrest,"\n");
 7622: 	  }
 7623: 	}
 7624: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7625: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7626: 	free_vector(epj,1,nlstate+1);
 7627:       /*}*/
 7628:     }
 7629:     free_vector(weight,1,n);
 7630:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 7631:     free_imatrix(s,1,maxwav+1,1,n);
 7632:     free_matrix(anint,1,maxwav,1,n); 
 7633:     free_matrix(mint,1,maxwav,1,n);
 7634:     free_ivector(cod,1,n);
 7635:     free_ivector(tab,1,NCOVMAX);
 7636:     fclose(ficresstdeij);
 7637:     fclose(ficrescveij);
 7638:     fclose(ficresvij);
 7639:     fclose(ficrest);
 7640:     fclose(ficpar);
 7641:   
 7642:     /*------- Variance of period (stable) prevalence------*/   
 7643: 
 7644:     strcpy(fileresvpl,"vpl");
 7645:     strcat(fileresvpl,fileres);
 7646:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 7647:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 7648:       exit(0);
 7649:     }
 7650:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 7651: 
 7652:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7653:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7654:           
 7655:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7656:     	fprintf(ficresvpl,"\n#****** ");
 7657: 	for(j=1;j<=cptcoveff;j++) 
 7658: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7659: 	fprintf(ficresvpl,"******\n");
 7660:       
 7661: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 7662: 	oldm=oldms;savm=savms;
 7663: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 7664: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 7665:       /*}*/
 7666:     }
 7667: 
 7668:     fclose(ficresvpl);
 7669: 
 7670:     /*---------- End : free ----------------*/
 7671:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7672:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7673:   }  /* mle==-3 arrives here for freeing */
 7674:  /* endfree:*/
 7675:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 7676:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 7677:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7678:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7679:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7680:     free_matrix(covar,0,NCOVMAX,1,n);
 7681:     free_matrix(matcov,1,npar,1,npar);
 7682:     /*free_vector(delti,1,npar);*/
 7683:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7684:     free_matrix(agev,1,maxwav,1,imx);
 7685:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7686: 
 7687:     free_ivector(ncodemax,1,NCOVMAX);
 7688:     free_ivector(ncodemaxwundef,1,NCOVMAX);
 7689:     free_ivector(Tvar,1,NCOVMAX);
 7690:     free_ivector(Tprod,1,NCOVMAX);
 7691:     free_ivector(Tvaraff,1,NCOVMAX);
 7692:     free_ivector(Tage,1,NCOVMAX);
 7693: 
 7694:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7695:     free_imatrix(codtab,1,100,1,10);
 7696:   fflush(fichtm);
 7697:   fflush(ficgp);
 7698:   
 7699: 
 7700:   if((nberr >0) || (nbwarn>0)){
 7701:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7702:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7703:   }else{
 7704:     printf("End of Imach\n");
 7705:     fprintf(ficlog,"End of Imach\n");
 7706:   }
 7707:   printf("See log file on %s\n",filelog);
 7708:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7709:   /*(void) gettimeofday(&end_time,&tzp);*/
 7710:   rend_time = time(NULL);  
 7711:   end_time = *localtime(&rend_time);
 7712:   /* tml = *localtime(&end_time.tm_sec); */
 7713:   strcpy(strtend,asctime(&end_time));
 7714:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7715:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7716:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7717: 
 7718:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7719:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7720:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7721:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7722: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7723:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7724:   fclose(fichtm);
 7725:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7726:   fclose(fichtmcov);
 7727:   fclose(ficgp);
 7728:   fclose(ficlog);
 7729:   /*------ End -----------*/
 7730: 
 7731: 
 7732:    printf("Before Current directory %s!\n",pathcd);
 7733: #ifdef WIN32
 7734:    if (_chdir(pathcd) != 0)
 7735: 	   printf("Can't move to directory %s!\n",path);
 7736:    if(_getcwd(pathcd,MAXLINE) > 0)
 7737: #else
 7738:    if(chdir(pathcd) != 0)
 7739: 	   printf("Can't move to directory %s!\n", path);
 7740:    if (getcwd(pathcd, MAXLINE) > 0)
 7741: #endif 
 7742:     printf("Current directory %s!\n",pathcd);
 7743:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7744:   sprintf(plotcmd,"gnuplot");
 7745: #ifdef _WIN32
 7746:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7747: #endif
 7748:   if(!stat(plotcmd,&info)){
 7749:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7750:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7751:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7752:     }else
 7753:       strcpy(pplotcmd,plotcmd);
 7754: #ifdef __unix
 7755:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7756:     if(!stat(plotcmd,&info)){
 7757:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7758:     }else
 7759:       strcpy(pplotcmd,plotcmd);
 7760: #endif
 7761:   }else
 7762:     strcpy(pplotcmd,plotcmd);
 7763:   
 7764:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7765:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7766: 
 7767:   if((outcmd=system(plotcmd)) != 0){
 7768:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7769:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7770:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7771:     if((outcmd=system(plotcmd)) != 0)
 7772:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7773:   }
 7774:   printf(" Successful, please wait...");
 7775:   while (z[0] != 'q') {
 7776:     /* chdir(path); */
 7777:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7778:     scanf("%s",z);
 7779: /*     if (z[0] == 'c') system("./imach"); */
 7780:     if (z[0] == 'e') {
 7781: #ifdef __APPLE__
 7782:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7783: #elif __linux
 7784:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7785: #else
 7786:       sprintf(pplotcmd, "%s", optionfilehtm);
 7787: #endif
 7788:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7789:       system(pplotcmd);
 7790:     }
 7791:     else if (z[0] == 'g') system(plotcmd);
 7792:     else if (z[0] == 'q') exit(0);
 7793:   }
 7794:   end:
 7795:   while (z[0] != 'q') {
 7796:     printf("\nType  q for exiting: ");
 7797:     scanf("%s",z);
 7798:   }
 7799: }

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