File:  [Local Repository] / imach / src / imach.c
Revision 1.174: download - view: text, annotated - select for diffs
Sat Jan 3 16:15:49 2015 UTC (9 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Still in cross-compilation

    1: /* $Id: imach.c,v 1.174 2015/01/03 16:15:49 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.174  2015/01/03 16:15:49  brouard
    5:   Summary: Still in cross-compilation
    6: 
    7:   Revision 1.173  2015/01/03 12:06:26  brouard
    8:   Summary: trying to detect cross-compilation
    9: 
   10:   Revision 1.172  2014/12/27 12:07:47  brouard
   11:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   12: 
   13:   Revision 1.171  2014/12/23 13:26:59  brouard
   14:   Summary: Back from Visual C
   15: 
   16:   Still problem with utsname.h on Windows
   17: 
   18:   Revision 1.170  2014/12/23 11:17:12  brouard
   19:   Summary: Cleaning some \%% back to %%
   20: 
   21:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   22: 
   23:   Revision 1.169  2014/12/22 23:08:31  brouard
   24:   Summary: 0.98p
   25: 
   26:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   27: 
   28:   Revision 1.168  2014/12/22 15:17:42  brouard
   29:   Summary: update
   30: 
   31:   Revision 1.167  2014/12/22 13:50:56  brouard
   32:   Summary: Testing uname and compiler version and if compiled 32 or 64
   33: 
   34:   Testing on Linux 64
   35: 
   36:   Revision 1.166  2014/12/22 11:40:47  brouard
   37:   *** empty log message ***
   38: 
   39:   Revision 1.165  2014/12/16 11:20:36  brouard
   40:   Summary: After compiling on Visual C
   41: 
   42:   * imach.c (Module): Merging 1.61 to 1.162
   43: 
   44:   Revision 1.164  2014/12/16 10:52:11  brouard
   45:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
   46: 
   47:   * imach.c (Module): Merging 1.61 to 1.162
   48: 
   49:   Revision 1.163  2014/12/16 10:30:11  brouard
   50:   * imach.c (Module): Merging 1.61 to 1.162
   51: 
   52:   Revision 1.162  2014/09/25 11:43:39  brouard
   53:   Summary: temporary backup 0.99!
   54: 
   55:   Revision 1.1  2014/09/16 11:06:58  brouard
   56:   Summary: With some code (wrong) for nlopt
   57: 
   58:   Author:
   59: 
   60:   Revision 1.161  2014/09/15 20:41:41  brouard
   61:   Summary: Problem with macro SQR on Intel compiler
   62: 
   63:   Revision 1.160  2014/09/02 09:24:05  brouard
   64:   *** empty log message ***
   65: 
   66:   Revision 1.159  2014/09/01 10:34:10  brouard
   67:   Summary: WIN32
   68:   Author: Brouard
   69: 
   70:   Revision 1.158  2014/08/27 17:11:51  brouard
   71:   *** empty log message ***
   72: 
   73:   Revision 1.157  2014/08/27 16:26:55  brouard
   74:   Summary: Preparing windows Visual studio version
   75:   Author: Brouard
   76: 
   77:   In order to compile on Visual studio, time.h is now correct and time_t
   78:   and tm struct should be used. difftime should be used but sometimes I
   79:   just make the differences in raw time format (time(&now).
   80:   Trying to suppress #ifdef LINUX
   81:   Add xdg-open for __linux in order to open default browser.
   82: 
   83:   Revision 1.156  2014/08/25 20:10:10  brouard
   84:   *** empty log message ***
   85: 
   86:   Revision 1.155  2014/08/25 18:32:34  brouard
   87:   Summary: New compile, minor changes
   88:   Author: Brouard
   89: 
   90:   Revision 1.154  2014/06/20 17:32:08  brouard
   91:   Summary: Outputs now all graphs of convergence to period prevalence
   92: 
   93:   Revision 1.153  2014/06/20 16:45:46  brouard
   94:   Summary: If 3 live state, convergence to period prevalence on same graph
   95:   Author: Brouard
   96: 
   97:   Revision 1.152  2014/06/18 17:54:09  brouard
   98:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
   99: 
  100:   Revision 1.151  2014/06/18 16:43:30  brouard
  101:   *** empty log message ***
  102: 
  103:   Revision 1.150  2014/06/18 16:42:35  brouard
  104:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  105:   Author: brouard
  106: 
  107:   Revision 1.149  2014/06/18 15:51:14  brouard
  108:   Summary: Some fixes in parameter files errors
  109:   Author: Nicolas Brouard
  110: 
  111:   Revision 1.148  2014/06/17 17:38:48  brouard
  112:   Summary: Nothing new
  113:   Author: Brouard
  114: 
  115:   Just a new packaging for OS/X version 0.98nS
  116: 
  117:   Revision 1.147  2014/06/16 10:33:11  brouard
  118:   *** empty log message ***
  119: 
  120:   Revision 1.146  2014/06/16 10:20:28  brouard
  121:   Summary: Merge
  122:   Author: Brouard
  123: 
  124:   Merge, before building revised version.
  125: 
  126:   Revision 1.145  2014/06/10 21:23:15  brouard
  127:   Summary: Debugging with valgrind
  128:   Author: Nicolas Brouard
  129: 
  130:   Lot of changes in order to output the results with some covariates
  131:   After the Edimburgh REVES conference 2014, it seems mandatory to
  132:   improve the code.
  133:   No more memory valgrind error but a lot has to be done in order to
  134:   continue the work of splitting the code into subroutines.
  135:   Also, decodemodel has been improved. Tricode is still not
  136:   optimal. nbcode should be improved. Documentation has been added in
  137:   the source code.
  138: 
  139:   Revision 1.143  2014/01/26 09:45:38  brouard
  140:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  141: 
  142:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  143:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  144: 
  145:   Revision 1.142  2014/01/26 03:57:36  brouard
  146:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  147: 
  148:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  149: 
  150:   Revision 1.141  2014/01/26 02:42:01  brouard
  151:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  152: 
  153:   Revision 1.140  2011/09/02 10:37:54  brouard
  154:   Summary: times.h is ok with mingw32 now.
  155: 
  156:   Revision 1.139  2010/06/14 07:50:17  brouard
  157:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  158:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  159: 
  160:   Revision 1.138  2010/04/30 18:19:40  brouard
  161:   *** empty log message ***
  162: 
  163:   Revision 1.137  2010/04/29 18:11:38  brouard
  164:   (Module): Checking covariates for more complex models
  165:   than V1+V2. A lot of change to be done. Unstable.
  166: 
  167:   Revision 1.136  2010/04/26 20:30:53  brouard
  168:   (Module): merging some libgsl code. Fixing computation
  169:   of likelione (using inter/intrapolation if mle = 0) in order to
  170:   get same likelihood as if mle=1.
  171:   Some cleaning of code and comments added.
  172: 
  173:   Revision 1.135  2009/10/29 15:33:14  brouard
  174:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  175: 
  176:   Revision 1.134  2009/10/29 13:18:53  brouard
  177:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  178: 
  179:   Revision 1.133  2009/07/06 10:21:25  brouard
  180:   just nforces
  181: 
  182:   Revision 1.132  2009/07/06 08:22:05  brouard
  183:   Many tings
  184: 
  185:   Revision 1.131  2009/06/20 16:22:47  brouard
  186:   Some dimensions resccaled
  187: 
  188:   Revision 1.130  2009/05/26 06:44:34  brouard
  189:   (Module): Max Covariate is now set to 20 instead of 8. A
  190:   lot of cleaning with variables initialized to 0. Trying to make
  191:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  192: 
  193:   Revision 1.129  2007/08/31 13:49:27  lievre
  194:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  195: 
  196:   Revision 1.128  2006/06/30 13:02:05  brouard
  197:   (Module): Clarifications on computing e.j
  198: 
  199:   Revision 1.127  2006/04/28 18:11:50  brouard
  200:   (Module): Yes the sum of survivors was wrong since
  201:   imach-114 because nhstepm was no more computed in the age
  202:   loop. Now we define nhstepma in the age loop.
  203:   (Module): In order to speed up (in case of numerous covariates) we
  204:   compute health expectancies (without variances) in a first step
  205:   and then all the health expectancies with variances or standard
  206:   deviation (needs data from the Hessian matrices) which slows the
  207:   computation.
  208:   In the future we should be able to stop the program is only health
  209:   expectancies and graph are needed without standard deviations.
  210: 
  211:   Revision 1.126  2006/04/28 17:23:28  brouard
  212:   (Module): Yes the sum of survivors was wrong since
  213:   imach-114 because nhstepm was no more computed in the age
  214:   loop. Now we define nhstepma in the age loop.
  215:   Version 0.98h
  216: 
  217:   Revision 1.125  2006/04/04 15:20:31  lievre
  218:   Errors in calculation of health expectancies. Age was not initialized.
  219:   Forecasting file added.
  220: 
  221:   Revision 1.124  2006/03/22 17:13:53  lievre
  222:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  223:   The log-likelihood is printed in the log file
  224: 
  225:   Revision 1.123  2006/03/20 10:52:43  brouard
  226:   * imach.c (Module): <title> changed, corresponds to .htm file
  227:   name. <head> headers where missing.
  228: 
  229:   * imach.c (Module): Weights can have a decimal point as for
  230:   English (a comma might work with a correct LC_NUMERIC environment,
  231:   otherwise the weight is truncated).
  232:   Modification of warning when the covariates values are not 0 or
  233:   1.
  234:   Version 0.98g
  235: 
  236:   Revision 1.122  2006/03/20 09:45:41  brouard
  237:   (Module): Weights can have a decimal point as for
  238:   English (a comma might work with a correct LC_NUMERIC environment,
  239:   otherwise the weight is truncated).
  240:   Modification of warning when the covariates values are not 0 or
  241:   1.
  242:   Version 0.98g
  243: 
  244:   Revision 1.121  2006/03/16 17:45:01  lievre
  245:   * imach.c (Module): Comments concerning covariates added
  246: 
  247:   * imach.c (Module): refinements in the computation of lli if
  248:   status=-2 in order to have more reliable computation if stepm is
  249:   not 1 month. Version 0.98f
  250: 
  251:   Revision 1.120  2006/03/16 15:10:38  lievre
  252:   (Module): refinements in the computation of lli if
  253:   status=-2 in order to have more reliable computation if stepm is
  254:   not 1 month. Version 0.98f
  255: 
  256:   Revision 1.119  2006/03/15 17:42:26  brouard
  257:   (Module): Bug if status = -2, the loglikelihood was
  258:   computed as likelihood omitting the logarithm. Version O.98e
  259: 
  260:   Revision 1.118  2006/03/14 18:20:07  brouard
  261:   (Module): varevsij Comments added explaining the second
  262:   table of variances if popbased=1 .
  263:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  264:   (Module): Function pstamp added
  265:   (Module): Version 0.98d
  266: 
  267:   Revision 1.117  2006/03/14 17:16:22  brouard
  268:   (Module): varevsij Comments added explaining the second
  269:   table of variances if popbased=1 .
  270:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  271:   (Module): Function pstamp added
  272:   (Module): Version 0.98d
  273: 
  274:   Revision 1.116  2006/03/06 10:29:27  brouard
  275:   (Module): Variance-covariance wrong links and
  276:   varian-covariance of ej. is needed (Saito).
  277: 
  278:   Revision 1.115  2006/02/27 12:17:45  brouard
  279:   (Module): One freematrix added in mlikeli! 0.98c
  280: 
  281:   Revision 1.114  2006/02/26 12:57:58  brouard
  282:   (Module): Some improvements in processing parameter
  283:   filename with strsep.
  284: 
  285:   Revision 1.113  2006/02/24 14:20:24  brouard
  286:   (Module): Memory leaks checks with valgrind and:
  287:   datafile was not closed, some imatrix were not freed and on matrix
  288:   allocation too.
  289: 
  290:   Revision 1.112  2006/01/30 09:55:26  brouard
  291:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  292: 
  293:   Revision 1.111  2006/01/25 20:38:18  brouard
  294:   (Module): Lots of cleaning and bugs added (Gompertz)
  295:   (Module): Comments can be added in data file. Missing date values
  296:   can be a simple dot '.'.
  297: 
  298:   Revision 1.110  2006/01/25 00:51:50  brouard
  299:   (Module): Lots of cleaning and bugs added (Gompertz)
  300: 
  301:   Revision 1.109  2006/01/24 19:37:15  brouard
  302:   (Module): Comments (lines starting with a #) are allowed in data.
  303: 
  304:   Revision 1.108  2006/01/19 18:05:42  lievre
  305:   Gnuplot problem appeared...
  306:   To be fixed
  307: 
  308:   Revision 1.107  2006/01/19 16:20:37  brouard
  309:   Test existence of gnuplot in imach path
  310: 
  311:   Revision 1.106  2006/01/19 13:24:36  brouard
  312:   Some cleaning and links added in html output
  313: 
  314:   Revision 1.105  2006/01/05 20:23:19  lievre
  315:   *** empty log message ***
  316: 
  317:   Revision 1.104  2005/09/30 16:11:43  lievre
  318:   (Module): sump fixed, loop imx fixed, and simplifications.
  319:   (Module): If the status is missing at the last wave but we know
  320:   that the person is alive, then we can code his/her status as -2
  321:   (instead of missing=-1 in earlier versions) and his/her
  322:   contributions to the likelihood is 1 - Prob of dying from last
  323:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  324:   the healthy state at last known wave). Version is 0.98
  325: 
  326:   Revision 1.103  2005/09/30 15:54:49  lievre
  327:   (Module): sump fixed, loop imx fixed, and simplifications.
  328: 
  329:   Revision 1.102  2004/09/15 17:31:30  brouard
  330:   Add the possibility to read data file including tab characters.
  331: 
  332:   Revision 1.101  2004/09/15 10:38:38  brouard
  333:   Fix on curr_time
  334: 
  335:   Revision 1.100  2004/07/12 18:29:06  brouard
  336:   Add version for Mac OS X. Just define UNIX in Makefile
  337: 
  338:   Revision 1.99  2004/06/05 08:57:40  brouard
  339:   *** empty log message ***
  340: 
  341:   Revision 1.98  2004/05/16 15:05:56  brouard
  342:   New version 0.97 . First attempt to estimate force of mortality
  343:   directly from the data i.e. without the need of knowing the health
  344:   state at each age, but using a Gompertz model: log u =a + b*age .
  345:   This is the basic analysis of mortality and should be done before any
  346:   other analysis, in order to test if the mortality estimated from the
  347:   cross-longitudinal survey is different from the mortality estimated
  348:   from other sources like vital statistic data.
  349: 
  350:   The same imach parameter file can be used but the option for mle should be -3.
  351: 
  352:   Agnès, who wrote this part of the code, tried to keep most of the
  353:   former routines in order to include the new code within the former code.
  354: 
  355:   The output is very simple: only an estimate of the intercept and of
  356:   the slope with 95% confident intervals.
  357: 
  358:   Current limitations:
  359:   A) Even if you enter covariates, i.e. with the
  360:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  361:   B) There is no computation of Life Expectancy nor Life Table.
  362: 
  363:   Revision 1.97  2004/02/20 13:25:42  lievre
  364:   Version 0.96d. Population forecasting command line is (temporarily)
  365:   suppressed.
  366: 
  367:   Revision 1.96  2003/07/15 15:38:55  brouard
  368:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  369:   rewritten within the same printf. Workaround: many printfs.
  370: 
  371:   Revision 1.95  2003/07/08 07:54:34  brouard
  372:   * imach.c (Repository):
  373:   (Repository): Using imachwizard code to output a more meaningful covariance
  374:   matrix (cov(a12,c31) instead of numbers.
  375: 
  376:   Revision 1.94  2003/06/27 13:00:02  brouard
  377:   Just cleaning
  378: 
  379:   Revision 1.93  2003/06/25 16:33:55  brouard
  380:   (Module): On windows (cygwin) function asctime_r doesn't
  381:   exist so I changed back to asctime which exists.
  382:   (Module): Version 0.96b
  383: 
  384:   Revision 1.92  2003/06/25 16:30:45  brouard
  385:   (Module): On windows (cygwin) function asctime_r doesn't
  386:   exist so I changed back to asctime which exists.
  387: 
  388:   Revision 1.91  2003/06/25 15:30:29  brouard
  389:   * imach.c (Repository): Duplicated warning errors corrected.
  390:   (Repository): Elapsed time after each iteration is now output. It
  391:   helps to forecast when convergence will be reached. Elapsed time
  392:   is stamped in powell.  We created a new html file for the graphs
  393:   concerning matrix of covariance. It has extension -cov.htm.
  394: 
  395:   Revision 1.90  2003/06/24 12:34:15  brouard
  396:   (Module): Some bugs corrected for windows. Also, when
  397:   mle=-1 a template is output in file "or"mypar.txt with the design
  398:   of the covariance matrix to be input.
  399: 
  400:   Revision 1.89  2003/06/24 12:30:52  brouard
  401:   (Module): Some bugs corrected for windows. Also, when
  402:   mle=-1 a template is output in file "or"mypar.txt with the design
  403:   of the covariance matrix to be input.
  404: 
  405:   Revision 1.88  2003/06/23 17:54:56  brouard
  406:   * 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.
  407: 
  408:   Revision 1.87  2003/06/18 12:26:01  brouard
  409:   Version 0.96
  410: 
  411:   Revision 1.86  2003/06/17 20:04:08  brouard
  412:   (Module): Change position of html and gnuplot routines and added
  413:   routine fileappend.
  414: 
  415:   Revision 1.85  2003/06/17 13:12:43  brouard
  416:   * imach.c (Repository): Check when date of death was earlier that
  417:   current date of interview. It may happen when the death was just
  418:   prior to the death. In this case, dh was negative and likelihood
  419:   was wrong (infinity). We still send an "Error" but patch by
  420:   assuming that the date of death was just one stepm after the
  421:   interview.
  422:   (Repository): Because some people have very long ID (first column)
  423:   we changed int to long in num[] and we added a new lvector for
  424:   memory allocation. But we also truncated to 8 characters (left
  425:   truncation)
  426:   (Repository): No more line truncation errors.
  427: 
  428:   Revision 1.84  2003/06/13 21:44:43  brouard
  429:   * imach.c (Repository): Replace "freqsummary" at a correct
  430:   place. It differs from routine "prevalence" which may be called
  431:   many times. Probs is memory consuming and must be used with
  432:   parcimony.
  433:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  434: 
  435:   Revision 1.83  2003/06/10 13:39:11  lievre
  436:   *** empty log message ***
  437: 
  438:   Revision 1.82  2003/06/05 15:57:20  brouard
  439:   Add log in  imach.c and  fullversion number is now printed.
  440: 
  441: */
  442: /*
  443:    Interpolated Markov Chain
  444: 
  445:   Short summary of the programme:
  446:   
  447:   This program computes Healthy Life Expectancies from
  448:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  449:   first survey ("cross") where individuals from different ages are
  450:   interviewed on their health status or degree of disability (in the
  451:   case of a health survey which is our main interest) -2- at least a
  452:   second wave of interviews ("longitudinal") which measure each change
  453:   (if any) in individual health status.  Health expectancies are
  454:   computed from the time spent in each health state according to a
  455:   model. More health states you consider, more time is necessary to reach the
  456:   Maximum Likelihood of the parameters involved in the model.  The
  457:   simplest model is the multinomial logistic model where pij is the
  458:   probability to be observed in state j at the second wave
  459:   conditional to be observed in state i at the first wave. Therefore
  460:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  461:   'age' is age and 'sex' is a covariate. If you want to have a more
  462:   complex model than "constant and age", you should modify the program
  463:   where the markup *Covariates have to be included here again* invites
  464:   you to do it.  More covariates you add, slower the
  465:   convergence.
  466: 
  467:   The advantage of this computer programme, compared to a simple
  468:   multinomial logistic model, is clear when the delay between waves is not
  469:   identical for each individual. Also, if a individual missed an
  470:   intermediate interview, the information is lost, but taken into
  471:   account using an interpolation or extrapolation.  
  472: 
  473:   hPijx is the probability to be observed in state i at age x+h
  474:   conditional to the observed state i at age x. The delay 'h' can be
  475:   split into an exact number (nh*stepm) of unobserved intermediate
  476:   states. This elementary transition (by month, quarter,
  477:   semester or year) is modelled as a multinomial logistic.  The hPx
  478:   matrix is simply the matrix product of nh*stepm elementary matrices
  479:   and the contribution of each individual to the likelihood is simply
  480:   hPijx.
  481: 
  482:   Also this programme outputs the covariance matrix of the parameters but also
  483:   of the life expectancies. It also computes the period (stable) prevalence. 
  484:   
  485:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  486:            Institut national d'études démographiques, Paris.
  487:   This software have been partly granted by Euro-REVES, a concerted action
  488:   from the European Union.
  489:   It is copyrighted identically to a GNU software product, ie programme and
  490:   software can be distributed freely for non commercial use. Latest version
  491:   can be accessed at http://euroreves.ined.fr/imach .
  492: 
  493:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  494:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  495:   
  496:   **********************************************************************/
  497: /*
  498:   main
  499:   read parameterfile
  500:   read datafile
  501:   concatwav
  502:   freqsummary
  503:   if (mle >= 1)
  504:     mlikeli
  505:   print results files
  506:   if mle==1 
  507:      computes hessian
  508:   read end of parameter file: agemin, agemax, bage, fage, estepm
  509:       begin-prev-date,...
  510:   open gnuplot file
  511:   open html file
  512:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  513:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  514:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  515:     freexexit2 possible for memory heap.
  516: 
  517:   h Pij x                         | pij_nom  ficrestpij
  518:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  519:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  520:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  521: 
  522:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  523:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  524:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  525:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  526:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  527: 
  528:   forecasting if prevfcast==1 prevforecast call prevalence()
  529:   health expectancies
  530:   Variance-covariance of DFLE
  531:   prevalence()
  532:    movingaverage()
  533:   varevsij() 
  534:   if popbased==1 varevsij(,popbased)
  535:   total life expectancies
  536:   Variance of period (stable) prevalence
  537:  end
  538: */
  539: 
  540: #define POWELL /* Instead of NLOPT */
  541: 
  542: #include <math.h>
  543: #include <stdio.h>
  544: #include <stdlib.h>
  545: #include <string.h>
  546: 
  547: #ifdef _WIN32
  548: #include <io.h>
  549: #include <windows.h>
  550: #include <tchar.h>
  551: #else
  552: #include <unistd.h>
  553: #endif
  554: 
  555: #include <limits.h>
  556: #include <sys/types.h>
  557: 
  558: #if defined(__GNUC__)
  559: #include <sys/utsname.h> /* Doesn't work on Windows */
  560: #endif
  561: 
  562: #include <sys/stat.h>
  563: #include <errno.h>
  564: /* extern int errno; */
  565: 
  566: /* #ifdef LINUX */
  567: /* #include <time.h> */
  568: /* #include "timeval.h" */
  569: /* #else */
  570: /* #include <sys/time.h> */
  571: /* #endif */
  572: 
  573: #include <time.h>
  574: 
  575: #ifdef GSL
  576: #include <gsl/gsl_errno.h>
  577: #include <gsl/gsl_multimin.h>
  578: #endif
  579: 
  580: 
  581: #ifdef NLOPT
  582: #include <nlopt.h>
  583: typedef struct {
  584:   double (* function)(double [] );
  585: } myfunc_data ;
  586: #endif
  587: 
  588: /* #include <libintl.h> */
  589: /* #define _(String) gettext (String) */
  590: 
  591: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  592: 
  593: #define GNUPLOTPROGRAM "gnuplot"
  594: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  595: #define FILENAMELENGTH 132
  596: 
  597: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  598: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  599: 
  600: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  601: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  602: 
  603: #define NINTERVMAX 8
  604: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  605: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  606: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  607: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  608: #define MAXN 20000
  609: #define YEARM 12. /**< Number of months per year */
  610: #define AGESUP 130
  611: #define AGEBASE 40
  612: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  613: #ifdef _WIN32
  614: #define DIRSEPARATOR '\\'
  615: #define CHARSEPARATOR "\\"
  616: #define ODIRSEPARATOR '/'
  617: #else
  618: #define DIRSEPARATOR '/'
  619: #define CHARSEPARATOR "/"
  620: #define ODIRSEPARATOR '\\'
  621: #endif
  622: 
  623: /* $Id: imach.c,v 1.174 2015/01/03 16:15:49 brouard Exp $ */
  624: /* $State: Exp $ */
  625: 
  626: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  627: char fullversion[]="$Revision: 1.174 $ $Date: 2015/01/03 16:15:49 $"; 
  628: char strstart[80];
  629: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  630: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  631: int nvar=0, nforce=0; /* Number of variables, number of forces */
  632: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  633: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  634: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  635: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  636: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  637: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  638: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  639: int cptcov=0; /* Working variable */
  640: int npar=NPARMAX;
  641: int nlstate=2; /* Number of live states */
  642: int ndeath=1; /* Number of dead states */
  643: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  644: int popbased=0;
  645: 
  646: int *wav; /* Number of waves for this individuual 0 is possible */
  647: int maxwav=0; /* Maxim number of waves */
  648: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  649: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  650: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  651: 		   to the likelihood and the sum of weights (done by funcone)*/
  652: int mle=1, weightopt=0;
  653: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  654: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  655: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  656: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  657: int countcallfunc=0;  /* Count the number of calls to func */
  658: double jmean=1; /* Mean space between 2 waves */
  659: double **matprod2(); /* test */
  660: double **oldm, **newm, **savm; /* Working pointers to matrices */
  661: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  662: /*FILE *fic ; */ /* Used in readdata only */
  663: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  664: FILE *ficlog, *ficrespow;
  665: int globpr=0; /* Global variable for printing or not */
  666: double fretone; /* Only one call to likelihood */
  667: long ipmx=0; /* Number of contributions */
  668: double sw; /* Sum of weights */
  669: char filerespow[FILENAMELENGTH];
  670: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  671: FILE *ficresilk;
  672: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  673: FILE *ficresprobmorprev;
  674: FILE *fichtm, *fichtmcov; /* Html File */
  675: FILE *ficreseij;
  676: char filerese[FILENAMELENGTH];
  677: FILE *ficresstdeij;
  678: char fileresstde[FILENAMELENGTH];
  679: FILE *ficrescveij;
  680: char filerescve[FILENAMELENGTH];
  681: FILE  *ficresvij;
  682: char fileresv[FILENAMELENGTH];
  683: FILE  *ficresvpl;
  684: char fileresvpl[FILENAMELENGTH];
  685: char title[MAXLINE];
  686: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  687: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  688: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  689: char command[FILENAMELENGTH];
  690: int  outcmd=0;
  691: 
  692: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  693: 
  694: char filelog[FILENAMELENGTH]; /* Log file */
  695: char filerest[FILENAMELENGTH];
  696: char fileregp[FILENAMELENGTH];
  697: char popfile[FILENAMELENGTH];
  698: 
  699: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  700: 
  701: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  702: /* struct timezone tzp; */
  703: /* extern int gettimeofday(); */
  704: struct tm tml, *gmtime(), *localtime();
  705: 
  706: extern time_t time();
  707: 
  708: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  709: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  710: struct tm tm;
  711: 
  712: char strcurr[80], strfor[80];
  713: 
  714: char *endptr;
  715: long lval;
  716: double dval;
  717: 
  718: #define NR_END 1
  719: #define FREE_ARG char*
  720: #define FTOL 1.0e-10
  721: 
  722: #define NRANSI 
  723: #define ITMAX 200 
  724: 
  725: #define TOL 2.0e-4 
  726: 
  727: #define CGOLD 0.3819660 
  728: #define ZEPS 1.0e-10 
  729: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  730: 
  731: #define GOLD 1.618034 
  732: #define GLIMIT 100.0 
  733: #define TINY 1.0e-20 
  734: 
  735: static double maxarg1,maxarg2;
  736: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  737: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  738:   
  739: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  740: #define rint(a) floor(a+0.5)
  741: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  742: /* #define mytinydouble 1.0e-16 */
  743: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  744: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  745: /* static double dsqrarg; */
  746: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  747: static double sqrarg;
  748: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  749: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  750: int agegomp= AGEGOMP;
  751: 
  752: int imx; 
  753: int stepm=1;
  754: /* Stepm, step in month: minimum step interpolation*/
  755: 
  756: int estepm;
  757: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  758: 
  759: int m,nb;
  760: long *num;
  761: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  762: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  763: double **pmmij, ***probs;
  764: double *ageexmed,*agecens;
  765: double dateintmean=0;
  766: 
  767: double *weight;
  768: int **s; /* Status */
  769: double *agedc;
  770: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  771: 		  * covar=matrix(0,NCOVMAX,1,n); 
  772: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  773: double  idx; 
  774: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  775: int *Ndum; /** Freq of modality (tricode */
  776: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  777: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  778: double *lsurv, *lpop, *tpop;
  779: 
  780: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  781: double ftolhess; /**< Tolerance for computing hessian */
  782: 
  783: /**************** split *************************/
  784: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  785: {
  786:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  787:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  788:   */ 
  789:   char	*ss;				/* pointer */
  790:   int	l1, l2;				/* length counters */
  791: 
  792:   l1 = strlen(path );			/* length of path */
  793:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  794:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  795:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  796:     strcpy( name, path );		/* we got the fullname name because no directory */
  797:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  798:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  799:     /* get current working directory */
  800:     /*    extern  char* getcwd ( char *buf , int len);*/
  801:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  802:       return( GLOCK_ERROR_GETCWD );
  803:     }
  804:     /* got dirc from getcwd*/
  805:     printf(" DIRC = %s \n",dirc);
  806:   } else {				/* strip direcotry from path */
  807:     ss++;				/* after this, the filename */
  808:     l2 = strlen( ss );			/* length of filename */
  809:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  810:     strcpy( name, ss );		/* save file name */
  811:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  812:     dirc[l1-l2] = 0;			/* add zero */
  813:     printf(" DIRC2 = %s \n",dirc);
  814:   }
  815:   /* We add a separator at the end of dirc if not exists */
  816:   l1 = strlen( dirc );			/* length of directory */
  817:   if( dirc[l1-1] != DIRSEPARATOR ){
  818:     dirc[l1] =  DIRSEPARATOR;
  819:     dirc[l1+1] = 0; 
  820:     printf(" DIRC3 = %s \n",dirc);
  821:   }
  822:   ss = strrchr( name, '.' );		/* find last / */
  823:   if (ss >0){
  824:     ss++;
  825:     strcpy(ext,ss);			/* save extension */
  826:     l1= strlen( name);
  827:     l2= strlen(ss)+1;
  828:     strncpy( finame, name, l1-l2);
  829:     finame[l1-l2]= 0;
  830:   }
  831: 
  832:   return( 0 );				/* we're done */
  833: }
  834: 
  835: 
  836: /******************************************/
  837: 
  838: void replace_back_to_slash(char *s, char*t)
  839: {
  840:   int i;
  841:   int lg=0;
  842:   i=0;
  843:   lg=strlen(t);
  844:   for(i=0; i<= lg; i++) {
  845:     (s[i] = t[i]);
  846:     if (t[i]== '\\') s[i]='/';
  847:   }
  848: }
  849: 
  850: char *trimbb(char *out, char *in)
  851: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  852:   char *s;
  853:   s=out;
  854:   while (*in != '\0'){
  855:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  856:       in++;
  857:     }
  858:     *out++ = *in++;
  859:   }
  860:   *out='\0';
  861:   return s;
  862: }
  863: 
  864: char *cutl(char *blocc, char *alocc, char *in, char occ)
  865: {
  866:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  867:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  868:      gives blocc="abcdef2ghi" and alocc="j".
  869:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  870:   */
  871:   char *s, *t;
  872:   t=in;s=in;
  873:   while ((*in != occ) && (*in != '\0')){
  874:     *alocc++ = *in++;
  875:   }
  876:   if( *in == occ){
  877:     *(alocc)='\0';
  878:     s=++in;
  879:   }
  880:  
  881:   if (s == t) {/* occ not found */
  882:     *(alocc-(in-s))='\0';
  883:     in=s;
  884:   }
  885:   while ( *in != '\0'){
  886:     *blocc++ = *in++;
  887:   }
  888: 
  889:   *blocc='\0';
  890:   return t;
  891: }
  892: char *cutv(char *blocc, char *alocc, char *in, char occ)
  893: {
  894:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  895:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  896:      gives blocc="abcdef2ghi" and alocc="j".
  897:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  898:   */
  899:   char *s, *t;
  900:   t=in;s=in;
  901:   while (*in != '\0'){
  902:     while( *in == occ){
  903:       *blocc++ = *in++;
  904:       s=in;
  905:     }
  906:     *blocc++ = *in++;
  907:   }
  908:   if (s == t) /* occ not found */
  909:     *(blocc-(in-s))='\0';
  910:   else
  911:     *(blocc-(in-s)-1)='\0';
  912:   in=s;
  913:   while ( *in != '\0'){
  914:     *alocc++ = *in++;
  915:   }
  916: 
  917:   *alocc='\0';
  918:   return s;
  919: }
  920: 
  921: int nbocc(char *s, char occ)
  922: {
  923:   int i,j=0;
  924:   int lg=20;
  925:   i=0;
  926:   lg=strlen(s);
  927:   for(i=0; i<= lg; i++) {
  928:   if  (s[i] == occ ) j++;
  929:   }
  930:   return j;
  931: }
  932: 
  933: /* void cutv(char *u,char *v, char*t, char occ) */
  934: /* { */
  935: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  936: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  937: /*      gives u="abcdef2ghi" and v="j" *\/ */
  938: /*   int i,lg,j,p=0; */
  939: /*   i=0; */
  940: /*   lg=strlen(t); */
  941: /*   for(j=0; j<=lg-1; j++) { */
  942: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  943: /*   } */
  944: 
  945: /*   for(j=0; j<p; j++) { */
  946: /*     (u[j] = t[j]); */
  947: /*   } */
  948: /*      u[p]='\0'; */
  949: 
  950: /*    for(j=0; j<= lg; j++) { */
  951: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  952: /*   } */
  953: /* } */
  954: 
  955: #ifdef _WIN32
  956: char * strsep(char **pp, const char *delim)
  957: {
  958:   char *p, *q;
  959:          
  960:   if ((p = *pp) == NULL)
  961:     return 0;
  962:   if ((q = strpbrk (p, delim)) != NULL)
  963:   {
  964:     *pp = q + 1;
  965:     *q = '\0';
  966:   }
  967:   else
  968:     *pp = 0;
  969:   return p;
  970: }
  971: #endif
  972: 
  973: /********************** nrerror ********************/
  974: 
  975: void nrerror(char error_text[])
  976: {
  977:   fprintf(stderr,"ERREUR ...\n");
  978:   fprintf(stderr,"%s\n",error_text);
  979:   exit(EXIT_FAILURE);
  980: }
  981: /*********************** vector *******************/
  982: double *vector(int nl, int nh)
  983: {
  984:   double *v;
  985:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  986:   if (!v) nrerror("allocation failure in vector");
  987:   return v-nl+NR_END;
  988: }
  989: 
  990: /************************ free vector ******************/
  991: void free_vector(double*v, int nl, int nh)
  992: {
  993:   free((FREE_ARG)(v+nl-NR_END));
  994: }
  995: 
  996: /************************ivector *******************************/
  997: int *ivector(long nl,long nh)
  998: {
  999:   int *v;
 1000:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1001:   if (!v) nrerror("allocation failure in ivector");
 1002:   return v-nl+NR_END;
 1003: }
 1004: 
 1005: /******************free ivector **************************/
 1006: void free_ivector(int *v, long nl, long nh)
 1007: {
 1008:   free((FREE_ARG)(v+nl-NR_END));
 1009: }
 1010: 
 1011: /************************lvector *******************************/
 1012: long *lvector(long nl,long nh)
 1013: {
 1014:   long *v;
 1015:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1016:   if (!v) nrerror("allocation failure in ivector");
 1017:   return v-nl+NR_END;
 1018: }
 1019: 
 1020: /******************free lvector **************************/
 1021: void free_lvector(long *v, long nl, long nh)
 1022: {
 1023:   free((FREE_ARG)(v+nl-NR_END));
 1024: }
 1025: 
 1026: /******************* imatrix *******************************/
 1027: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1028:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1029: { 
 1030:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1031:   int **m; 
 1032:   
 1033:   /* allocate pointers to rows */ 
 1034:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1035:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1036:   m += NR_END; 
 1037:   m -= nrl; 
 1038:   
 1039:   
 1040:   /* allocate rows and set pointers to them */ 
 1041:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1042:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1043:   m[nrl] += NR_END; 
 1044:   m[nrl] -= ncl; 
 1045:   
 1046:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1047:   
 1048:   /* return pointer to array of pointers to rows */ 
 1049:   return m; 
 1050: } 
 1051: 
 1052: /****************** free_imatrix *************************/
 1053: void free_imatrix(m,nrl,nrh,ncl,nch)
 1054:       int **m;
 1055:       long nch,ncl,nrh,nrl; 
 1056:      /* free an int matrix allocated by imatrix() */ 
 1057: { 
 1058:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1059:   free((FREE_ARG) (m+nrl-NR_END)); 
 1060: } 
 1061: 
 1062: /******************* matrix *******************************/
 1063: double **matrix(long nrl, long nrh, long ncl, long nch)
 1064: {
 1065:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1066:   double **m;
 1067: 
 1068:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1069:   if (!m) nrerror("allocation failure 1 in matrix()");
 1070:   m += NR_END;
 1071:   m -= nrl;
 1072: 
 1073:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1074:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1075:   m[nrl] += NR_END;
 1076:   m[nrl] -= ncl;
 1077: 
 1078:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1079:   return m;
 1080:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1081: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1082: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1083:    */
 1084: }
 1085: 
 1086: /*************************free matrix ************************/
 1087: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1088: {
 1089:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1090:   free((FREE_ARG)(m+nrl-NR_END));
 1091: }
 1092: 
 1093: /******************* ma3x *******************************/
 1094: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1095: {
 1096:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1097:   double ***m;
 1098: 
 1099:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1100:   if (!m) nrerror("allocation failure 1 in matrix()");
 1101:   m += NR_END;
 1102:   m -= nrl;
 1103: 
 1104:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1105:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1106:   m[nrl] += NR_END;
 1107:   m[nrl] -= ncl;
 1108: 
 1109:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1110: 
 1111:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1112:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1113:   m[nrl][ncl] += NR_END;
 1114:   m[nrl][ncl] -= nll;
 1115:   for (j=ncl+1; j<=nch; j++) 
 1116:     m[nrl][j]=m[nrl][j-1]+nlay;
 1117:   
 1118:   for (i=nrl+1; i<=nrh; i++) {
 1119:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1120:     for (j=ncl+1; j<=nch; j++) 
 1121:       m[i][j]=m[i][j-1]+nlay;
 1122:   }
 1123:   return m; 
 1124:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1125:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1126:   */
 1127: }
 1128: 
 1129: /*************************free ma3x ************************/
 1130: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1131: {
 1132:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1133:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1134:   free((FREE_ARG)(m+nrl-NR_END));
 1135: }
 1136: 
 1137: /*************** function subdirf ***********/
 1138: char *subdirf(char fileres[])
 1139: {
 1140:   /* Caution optionfilefiname is hidden */
 1141:   strcpy(tmpout,optionfilefiname);
 1142:   strcat(tmpout,"/"); /* Add to the right */
 1143:   strcat(tmpout,fileres);
 1144:   return tmpout;
 1145: }
 1146: 
 1147: /*************** function subdirf2 ***********/
 1148: char *subdirf2(char fileres[], char *preop)
 1149: {
 1150:   
 1151:   /* Caution optionfilefiname is hidden */
 1152:   strcpy(tmpout,optionfilefiname);
 1153:   strcat(tmpout,"/");
 1154:   strcat(tmpout,preop);
 1155:   strcat(tmpout,fileres);
 1156:   return tmpout;
 1157: }
 1158: 
 1159: /*************** function subdirf3 ***********/
 1160: char *subdirf3(char fileres[], char *preop, char *preop2)
 1161: {
 1162:   
 1163:   /* Caution optionfilefiname is hidden */
 1164:   strcpy(tmpout,optionfilefiname);
 1165:   strcat(tmpout,"/");
 1166:   strcat(tmpout,preop);
 1167:   strcat(tmpout,preop2);
 1168:   strcat(tmpout,fileres);
 1169:   return tmpout;
 1170: }
 1171: 
 1172: char *asc_diff_time(long time_sec, char ascdiff[])
 1173: {
 1174:   long sec_left, days, hours, minutes;
 1175:   days = (time_sec) / (60*60*24);
 1176:   sec_left = (time_sec) % (60*60*24);
 1177:   hours = (sec_left) / (60*60) ;
 1178:   sec_left = (sec_left) %(60*60);
 1179:   minutes = (sec_left) /60;
 1180:   sec_left = (sec_left) % (60);
 1181:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1182:   return ascdiff;
 1183: }
 1184: 
 1185: /***************** f1dim *************************/
 1186: extern int ncom; 
 1187: extern double *pcom,*xicom;
 1188: extern double (*nrfunc)(double []); 
 1189:  
 1190: double f1dim(double x) 
 1191: { 
 1192:   int j; 
 1193:   double f;
 1194:   double *xt; 
 1195:  
 1196:   xt=vector(1,ncom); 
 1197:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1198:   f=(*nrfunc)(xt); 
 1199:   free_vector(xt,1,ncom); 
 1200:   return f; 
 1201: } 
 1202: 
 1203: /*****************brent *************************/
 1204: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1205: { 
 1206:   int iter; 
 1207:   double a,b,d,etemp;
 1208:   double fu=0,fv,fw,fx;
 1209:   double ftemp=0.;
 1210:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1211:   double e=0.0; 
 1212:  
 1213:   a=(ax < cx ? ax : cx); 
 1214:   b=(ax > cx ? ax : cx); 
 1215:   x=w=v=bx; 
 1216:   fw=fv=fx=(*f)(x); 
 1217:   for (iter=1;iter<=ITMAX;iter++) { 
 1218:     xm=0.5*(a+b); 
 1219:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1220:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1221:     printf(".");fflush(stdout);
 1222:     fprintf(ficlog,".");fflush(ficlog);
 1223: #ifdef DEBUGBRENT
 1224:     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);
 1225:     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);
 1226:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1227: #endif
 1228:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1229:       *xmin=x; 
 1230:       return fx; 
 1231:     } 
 1232:     ftemp=fu;
 1233:     if (fabs(e) > tol1) { 
 1234:       r=(x-w)*(fx-fv); 
 1235:       q=(x-v)*(fx-fw); 
 1236:       p=(x-v)*q-(x-w)*r; 
 1237:       q=2.0*(q-r); 
 1238:       if (q > 0.0) p = -p; 
 1239:       q=fabs(q); 
 1240:       etemp=e; 
 1241:       e=d; 
 1242:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1243: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1244:       else { 
 1245: 	d=p/q; 
 1246: 	u=x+d; 
 1247: 	if (u-a < tol2 || b-u < tol2) 
 1248: 	  d=SIGN(tol1,xm-x); 
 1249:       } 
 1250:     } else { 
 1251:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1252:     } 
 1253:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1254:     fu=(*f)(u); 
 1255:     if (fu <= fx) { 
 1256:       if (u >= x) a=x; else b=x; 
 1257:       SHFT(v,w,x,u) 
 1258: 	SHFT(fv,fw,fx,fu) 
 1259: 	} else { 
 1260: 	  if (u < x) a=u; else b=u; 
 1261: 	  if (fu <= fw || w == x) { 
 1262: 	    v=w; 
 1263: 	    w=u; 
 1264: 	    fv=fw; 
 1265: 	    fw=fu; 
 1266: 	  } else if (fu <= fv || v == x || v == w) { 
 1267: 	    v=u; 
 1268: 	    fv=fu; 
 1269: 	  } 
 1270: 	} 
 1271:   } 
 1272:   nrerror("Too many iterations in brent"); 
 1273:   *xmin=x; 
 1274:   return fx; 
 1275: } 
 1276: 
 1277: /****************** mnbrak ***********************/
 1278: 
 1279: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1280: 	    double (*func)(double)) 
 1281: { 
 1282:   double ulim,u,r,q, dum;
 1283:   double fu; 
 1284:  
 1285:   *fa=(*func)(*ax); 
 1286:   *fb=(*func)(*bx); 
 1287:   if (*fb > *fa) { 
 1288:     SHFT(dum,*ax,*bx,dum) 
 1289:       SHFT(dum,*fb,*fa,dum) 
 1290:       } 
 1291:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1292:   *fc=(*func)(*cx); 
 1293:   while (*fb > *fc) { /* Declining fa, fb, fc */
 1294:     r=(*bx-*ax)*(*fb-*fc); 
 1295:     q=(*bx-*cx)*(*fb-*fa); 
 1296:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1297:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1298:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
 1299:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
 1300:       fu=(*func)(u); 
 1301: #ifdef DEBUG
 1302:       /* f(x)=A(x-u)**2+f(u) */
 1303:       double A, fparabu; 
 1304:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1305:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1306:       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);
 1307:       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);
 1308: #endif 
 1309:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1310:       fu=(*func)(u); 
 1311:       if (fu < *fc) { 
 1312: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1313: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1314: 	  } 
 1315:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1316:       u=ulim; 
 1317:       fu=(*func)(u); 
 1318:     } else { 
 1319:       u=(*cx)+GOLD*(*cx-*bx); 
 1320:       fu=(*func)(u); 
 1321:     } 
 1322:     SHFT(*ax,*bx,*cx,u) 
 1323:       SHFT(*fa,*fb,*fc,fu) 
 1324:       } 
 1325: } 
 1326: 
 1327: /*************** linmin ************************/
 1328: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1329: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1330: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1331: the value of func at the returned location p . This is actually all accomplished by calling the
 1332: routines mnbrak and brent .*/
 1333: int ncom; 
 1334: double *pcom,*xicom;
 1335: double (*nrfunc)(double []); 
 1336:  
 1337: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1338: { 
 1339:   double brent(double ax, double bx, double cx, 
 1340: 	       double (*f)(double), double tol, double *xmin); 
 1341:   double f1dim(double x); 
 1342:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1343: 	      double *fc, double (*func)(double)); 
 1344:   int j; 
 1345:   double xx,xmin,bx,ax; 
 1346:   double fx,fb,fa;
 1347:  
 1348:   ncom=n; 
 1349:   pcom=vector(1,n); 
 1350:   xicom=vector(1,n); 
 1351:   nrfunc=func; 
 1352:   for (j=1;j<=n;j++) { 
 1353:     pcom[j]=p[j]; 
 1354:     xicom[j]=xi[j]; 
 1355:   } 
 1356:   ax=0.0; 
 1357:   xx=1.0; 
 1358:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1359:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1360: #ifdef DEBUG
 1361:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1362:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1363: #endif
 1364:   for (j=1;j<=n;j++) { 
 1365:     xi[j] *= xmin; 
 1366:     p[j] += xi[j]; 
 1367:   } 
 1368:   free_vector(xicom,1,n); 
 1369:   free_vector(pcom,1,n); 
 1370: } 
 1371: 
 1372: 
 1373: /*************** powell ************************/
 1374: /*
 1375: Minimization of a function func of n variables. Input consists of an initial starting point
 1376: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1377: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1378: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1379: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1380: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1381:  */
 1382: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1383: 	    double (*func)(double [])) 
 1384: { 
 1385:   void linmin(double p[], double xi[], int n, double *fret, 
 1386: 	      double (*func)(double [])); 
 1387:   int i,ibig,j; 
 1388:   double del,t,*pt,*ptt,*xit;
 1389:   double fp,fptt;
 1390:   double *xits;
 1391:   int niterf, itmp;
 1392: 
 1393:   pt=vector(1,n); 
 1394:   ptt=vector(1,n); 
 1395:   xit=vector(1,n); 
 1396:   xits=vector(1,n); 
 1397:   *fret=(*func)(p); 
 1398:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1399:     rcurr_time = time(NULL);  
 1400:   for (*iter=1;;++(*iter)) { 
 1401:     fp=(*fret); 
 1402:     ibig=0; 
 1403:     del=0.0; 
 1404:     rlast_time=rcurr_time;
 1405:     /* (void) gettimeofday(&curr_time,&tzp); */
 1406:     rcurr_time = time(NULL);  
 1407:     curr_time = *localtime(&rcurr_time);
 1408:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1409:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1410: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1411:    for (i=1;i<=n;i++) {
 1412:       printf(" %d %.12f",i, p[i]);
 1413:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1414:       fprintf(ficrespow," %.12lf", p[i]);
 1415:     }
 1416:     printf("\n");
 1417:     fprintf(ficlog,"\n");
 1418:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1419:     if(*iter <=3){
 1420:       tml = *localtime(&rcurr_time);
 1421:       strcpy(strcurr,asctime(&tml));
 1422:       rforecast_time=rcurr_time; 
 1423:       itmp = strlen(strcurr);
 1424:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1425: 	strcurr[itmp-1]='\0';
 1426:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1427:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1428:       for(niterf=10;niterf<=30;niterf+=10){
 1429: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1430: 	forecast_time = *localtime(&rforecast_time);
 1431: 	strcpy(strfor,asctime(&forecast_time));
 1432: 	itmp = strlen(strfor);
 1433: 	if(strfor[itmp-1]=='\n')
 1434: 	strfor[itmp-1]='\0';
 1435: 	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);
 1436: 	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);
 1437:       }
 1438:     }
 1439:     for (i=1;i<=n;i++) { 
 1440:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1441:       fptt=(*fret); 
 1442: #ifdef DEBUG
 1443: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1444: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1445: #endif
 1446:       printf("%d",i);fflush(stdout);
 1447:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1448:       linmin(p,xit,n,fret,func); 
 1449:       if (fabs(fptt-(*fret)) > del) { 
 1450: 	del=fabs(fptt-(*fret)); 
 1451: 	ibig=i; 
 1452:       } 
 1453: #ifdef DEBUG
 1454:       printf("%d %.12e",i,(*fret));
 1455:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1456:       for (j=1;j<=n;j++) {
 1457: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1458: 	printf(" x(%d)=%.12e",j,xit[j]);
 1459: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1460:       }
 1461:       for(j=1;j<=n;j++) {
 1462: 	printf(" p(%d)=%.12e",j,p[j]);
 1463: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1464:       }
 1465:       printf("\n");
 1466:       fprintf(ficlog,"\n");
 1467: #endif
 1468:     } /* end i */
 1469:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1470: #ifdef DEBUG
 1471:       int k[2],l;
 1472:       k[0]=1;
 1473:       k[1]=-1;
 1474:       printf("Max: %.12e",(*func)(p));
 1475:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1476:       for (j=1;j<=n;j++) {
 1477: 	printf(" %.12e",p[j]);
 1478: 	fprintf(ficlog," %.12e",p[j]);
 1479:       }
 1480:       printf("\n");
 1481:       fprintf(ficlog,"\n");
 1482:       for(l=0;l<=1;l++) {
 1483: 	for (j=1;j<=n;j++) {
 1484: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1485: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1486: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1487: 	}
 1488: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1489: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1490:       }
 1491: #endif
 1492: 
 1493: 
 1494:       free_vector(xit,1,n); 
 1495:       free_vector(xits,1,n); 
 1496:       free_vector(ptt,1,n); 
 1497:       free_vector(pt,1,n); 
 1498:       return; 
 1499:     } 
 1500:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1501:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
 1502:       ptt[j]=2.0*p[j]-pt[j]; 
 1503:       xit[j]=p[j]-pt[j]; 
 1504:       pt[j]=p[j]; 
 1505:     } 
 1506:     fptt=(*func)(ptt); 
 1507:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1508:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1509:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1510:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1511:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1512:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1513:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
 1514:       /* Thus we compare delta(2h) with observed f1-f3 */
 1515:       /* or best gain on one ancient line 'del' with total  */
 1516:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
 1517:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1518: 
 1519:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
 1520:       t= t- del*SQR(fp-fptt);
 1521:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1522:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1523: #ifdef DEBUG
 1524:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1525: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1526:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1527: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1528:       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);
 1529:       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);
 1530: #endif
 1531:       if (t < 0.0) { /* Then we use it for last direction */
 1532: 	linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
 1533: 	for (j=1;j<=n;j++) { 
 1534: 	  xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
 1535: 	  xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
 1536: 	}
 1537: 	printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1538: 	fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1539: 
 1540: #ifdef DEBUG
 1541: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1542: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1543: 	for(j=1;j<=n;j++){
 1544: 	  printf(" %.12e",xit[j]);
 1545: 	  fprintf(ficlog," %.12e",xit[j]);
 1546: 	}
 1547: 	printf("\n");
 1548: 	fprintf(ficlog,"\n");
 1549: #endif
 1550:       } /* end of t negative */
 1551:     } /* end if (fptt < fp)  */
 1552:   } 
 1553: } 
 1554: 
 1555: /**** Prevalence limit (stable or period prevalence)  ****************/
 1556: 
 1557: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1558: {
 1559:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1560:      matrix by transitions matrix until convergence is reached */
 1561:   
 1562:   int i, ii,j,k;
 1563:   double min, max, maxmin, maxmax,sumnew=0.;
 1564:   /* double **matprod2(); */ /* test */
 1565:   double **out, cov[NCOVMAX+1], **pmij();
 1566:   double **newm;
 1567:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1568:   
 1569:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1570:     for (j=1;j<=nlstate+ndeath;j++){
 1571:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1572:     }
 1573:   
 1574:   cov[1]=1.;
 1575:   
 1576:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1577:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1578:     newm=savm;
 1579:     /* Covariates have to be included here again */
 1580:     cov[2]=agefin;
 1581:     
 1582:     for (k=1; k<=cptcovn;k++) {
 1583:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1584:       /*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]]);*/
 1585:     }
 1586:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1587:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1588:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1589:     
 1590:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1591:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1592:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1593:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1594:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1595:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1596:     
 1597:     savm=oldm;
 1598:     oldm=newm;
 1599:     maxmax=0.;
 1600:     for(j=1;j<=nlstate;j++){
 1601:       min=1.;
 1602:       max=0.;
 1603:       for(i=1; i<=nlstate; i++) {
 1604: 	sumnew=0;
 1605: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1606: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1607:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1608: 	max=FMAX(max,prlim[i][j]);
 1609: 	min=FMIN(min,prlim[i][j]);
 1610:       }
 1611:       maxmin=max-min;
 1612:       maxmax=FMAX(maxmax,maxmin);
 1613:     } /* j loop */
 1614:     if(maxmax < ftolpl){
 1615:       return prlim;
 1616:     }
 1617:   } /* age loop */
 1618:   return prlim; /* should not reach here */
 1619: }
 1620: 
 1621: /*************** transition probabilities ***************/ 
 1622: 
 1623: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1624: {
 1625:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1626:      computes the probability to be observed in state j being in state i by appying the
 1627:      model to the ncovmodel covariates (including constant and age).
 1628:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1629:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1630:      ncth covariate in the global vector x is given by the formula:
 1631:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1632:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1633:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1634:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1635:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1636:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1637:   */
 1638:   double s1, lnpijopii;
 1639:   /*double t34;*/
 1640:   int i,j, nc, ii, jj;
 1641: 
 1642:     for(i=1; i<= nlstate; i++){
 1643:       for(j=1; j<i;j++){
 1644: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1645: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1646: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1647: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1648: 	}
 1649: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1650: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1651:       }
 1652:       for(j=i+1; j<=nlstate+ndeath;j++){
 1653: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1654: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1655: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1656: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1657: 	}
 1658: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1659:       }
 1660:     }
 1661:     
 1662:     for(i=1; i<= nlstate; i++){
 1663:       s1=0;
 1664:       for(j=1; j<i; j++){
 1665: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1666: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1667:       }
 1668:       for(j=i+1; j<=nlstate+ndeath; j++){
 1669: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1670: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1671:       }
 1672:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1673:       ps[i][i]=1./(s1+1.);
 1674:       /* Computing other pijs */
 1675:       for(j=1; j<i; j++)
 1676: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1677:       for(j=i+1; j<=nlstate+ndeath; j++)
 1678: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1679:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1680:     } /* end i */
 1681:     
 1682:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1683:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1684: 	ps[ii][jj]=0;
 1685: 	ps[ii][ii]=1;
 1686:       }
 1687:     }
 1688:     
 1689:     
 1690:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1691:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1692:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1693:     /*   } */
 1694:     /*   printf("\n "); */
 1695:     /* } */
 1696:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1697:     /*
 1698:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1699:       goto end;*/
 1700:     return ps;
 1701: }
 1702: 
 1703: /**************** Product of 2 matrices ******************/
 1704: 
 1705: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1706: {
 1707:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1708:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1709:   /* in, b, out are matrice of pointers which should have been initialized 
 1710:      before: only the contents of out is modified. The function returns
 1711:      a pointer to pointers identical to out */
 1712:   int i, j, k;
 1713:   for(i=nrl; i<= nrh; i++)
 1714:     for(k=ncolol; k<=ncoloh; k++){
 1715:       out[i][k]=0.;
 1716:       for(j=ncl; j<=nch; j++)
 1717:   	out[i][k] +=in[i][j]*b[j][k];
 1718:     }
 1719:   return out;
 1720: }
 1721: 
 1722: 
 1723: /************* Higher Matrix Product ***************/
 1724: 
 1725: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1726: {
 1727:   /* Computes the transition matrix starting at age 'age' over 
 1728:      'nhstepm*hstepm*stepm' months (i.e. until
 1729:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1730:      nhstepm*hstepm matrices. 
 1731:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1732:      (typically every 2 years instead of every month which is too big 
 1733:      for the memory).
 1734:      Model is determined by parameters x and covariates have to be 
 1735:      included manually here. 
 1736: 
 1737:      */
 1738: 
 1739:   int i, j, d, h, k;
 1740:   double **out, cov[NCOVMAX+1];
 1741:   double **newm;
 1742: 
 1743:   /* Hstepm could be zero and should return the unit matrix */
 1744:   for (i=1;i<=nlstate+ndeath;i++)
 1745:     for (j=1;j<=nlstate+ndeath;j++){
 1746:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1747:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1748:     }
 1749:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1750:   for(h=1; h <=nhstepm; h++){
 1751:     for(d=1; d <=hstepm; d++){
 1752:       newm=savm;
 1753:       /* Covariates have to be included here again */
 1754:       cov[1]=1.;
 1755:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1756:       for (k=1; k<=cptcovn;k++) 
 1757: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1758:       for (k=1; k<=cptcovage;k++)
 1759: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1760:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1761: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1762: 
 1763: 
 1764:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1765:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1766:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1767: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1768:       savm=oldm;
 1769:       oldm=newm;
 1770:     }
 1771:     for(i=1; i<=nlstate+ndeath; i++)
 1772:       for(j=1;j<=nlstate+ndeath;j++) {
 1773: 	po[i][j][h]=newm[i][j];
 1774: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1775:       }
 1776:     /*printf("h=%d ",h);*/
 1777:   } /* end h */
 1778: /*     printf("\n H=%d \n",h); */
 1779:   return po;
 1780: }
 1781: 
 1782: #ifdef NLOPT
 1783:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1784:   double fret;
 1785:   double *xt;
 1786:   int j;
 1787:   myfunc_data *d2 = (myfunc_data *) pd;
 1788: /* xt = (p1-1); */
 1789:   xt=vector(1,n); 
 1790:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1791: 
 1792:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1793:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1794:   printf("Function = %.12lf ",fret);
 1795:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1796:   printf("\n");
 1797:  free_vector(xt,1,n);
 1798:   return fret;
 1799: }
 1800: #endif
 1801: 
 1802: /*************** log-likelihood *************/
 1803: double func( double *x)
 1804: {
 1805:   int i, ii, j, k, mi, d, kk;
 1806:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1807:   double **out;
 1808:   double sw; /* Sum of weights */
 1809:   double lli; /* Individual log likelihood */
 1810:   int s1, s2;
 1811:   double bbh, survp;
 1812:   long ipmx;
 1813:   /*extern weight */
 1814:   /* We are differentiating ll according to initial status */
 1815:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1816:   /*for(i=1;i<imx;i++) 
 1817:     printf(" %d\n",s[4][i]);
 1818:   */
 1819: 
 1820:   ++countcallfunc;
 1821: 
 1822:   cov[1]=1.;
 1823: 
 1824:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1825: 
 1826:   if(mle==1){
 1827:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1828:       /* Computes the values of the ncovmodel covariates of the model
 1829: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1830: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1831: 	 to be observed in j being in i according to the model.
 1832:        */
 1833:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1834: 	cov[2+k]=covar[Tvar[k]][i];
 1835:       }
 1836:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1837: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1838: 	 has been calculated etc */
 1839:       for(mi=1; mi<= wav[i]-1; mi++){
 1840: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1841: 	  for (j=1;j<=nlstate+ndeath;j++){
 1842: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1843: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1844: 	  }
 1845: 	for(d=0; d<dh[mi][i]; d++){
 1846: 	  newm=savm;
 1847: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1848: 	  for (kk=1; kk<=cptcovage;kk++) {
 1849: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1850: 	  }
 1851: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1852: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1853: 	  savm=oldm;
 1854: 	  oldm=newm;
 1855: 	} /* end mult */
 1856:       
 1857: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1858: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1859: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1860: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1861: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1862: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1863: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1864: 	 * probability in order to take into account the bias as a fraction of the way
 1865: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1866: 	 * -stepm/2 to stepm/2 .
 1867: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1868: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1869: 	 */
 1870: 	s1=s[mw[mi][i]][i];
 1871: 	s2=s[mw[mi+1][i]][i];
 1872: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1873: 	/* bias bh is positive if real duration
 1874: 	 * is higher than the multiple of stepm and negative otherwise.
 1875: 	 */
 1876: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1877: 	if( s2 > nlstate){ 
 1878: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1879: 	     then the contribution to the likelihood is the probability to 
 1880: 	     die between last step unit time and current  step unit time, 
 1881: 	     which is also equal to probability to die before dh 
 1882: 	     minus probability to die before dh-stepm . 
 1883: 	     In version up to 0.92 likelihood was computed
 1884: 	as if date of death was unknown. Death was treated as any other
 1885: 	health state: the date of the interview describes the actual state
 1886: 	and not the date of a change in health state. The former idea was
 1887: 	to consider that at each interview the state was recorded
 1888: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1889: 	introduced the exact date of death then we should have modified
 1890: 	the contribution of an exact death to the likelihood. This new
 1891: 	contribution is smaller and very dependent of the step unit
 1892: 	stepm. It is no more the probability to die between last interview
 1893: 	and month of death but the probability to survive from last
 1894: 	interview up to one month before death multiplied by the
 1895: 	probability to die within a month. Thanks to Chris
 1896: 	Jackson for correcting this bug.  Former versions increased
 1897: 	mortality artificially. The bad side is that we add another loop
 1898: 	which slows down the processing. The difference can be up to 10%
 1899: 	lower mortality.
 1900: 	  */
 1901: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1902: 
 1903: 
 1904: 	} else if  (s2==-2) {
 1905: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1906: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1907: 	  /*survp += out[s1][j]; */
 1908: 	  lli= log(survp);
 1909: 	}
 1910: 	
 1911:  	else if  (s2==-4) { 
 1912: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1913: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1914:  	  lli= log(survp); 
 1915:  	} 
 1916: 
 1917:  	else if  (s2==-5) { 
 1918:  	  for (j=1,survp=0. ; j<=2; j++)  
 1919: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1920:  	  lli= log(survp); 
 1921:  	} 
 1922: 	
 1923: 	else{
 1924: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1925: 	  /*  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 */
 1926: 	} 
 1927: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1928: 	/*if(lli ==000.0)*/
 1929: 	/*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); */
 1930:   	ipmx +=1;
 1931: 	sw += weight[i];
 1932: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1933:       } /* end of wave */
 1934:     } /* end of individual */
 1935:   }  else if(mle==2){
 1936:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1937:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1938:       for(mi=1; mi<= wav[i]-1; mi++){
 1939: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1940: 	  for (j=1;j<=nlstate+ndeath;j++){
 1941: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1942: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1943: 	  }
 1944: 	for(d=0; d<=dh[mi][i]; d++){
 1945: 	  newm=savm;
 1946: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1947: 	  for (kk=1; kk<=cptcovage;kk++) {
 1948: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1949: 	  }
 1950: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1951: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1952: 	  savm=oldm;
 1953: 	  oldm=newm;
 1954: 	} /* end mult */
 1955:       
 1956: 	s1=s[mw[mi][i]][i];
 1957: 	s2=s[mw[mi+1][i]][i];
 1958: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1959: 	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 */
 1960: 	ipmx +=1;
 1961: 	sw += weight[i];
 1962: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1963:       } /* end of wave */
 1964:     } /* end of individual */
 1965:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1966:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1967:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1968:       for(mi=1; mi<= wav[i]-1; mi++){
 1969: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1970: 	  for (j=1;j<=nlstate+ndeath;j++){
 1971: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1972: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1973: 	  }
 1974: 	for(d=0; d<dh[mi][i]; d++){
 1975: 	  newm=savm;
 1976: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1977: 	  for (kk=1; kk<=cptcovage;kk++) {
 1978: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1979: 	  }
 1980: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1981: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1982: 	  savm=oldm;
 1983: 	  oldm=newm;
 1984: 	} /* end mult */
 1985:       
 1986: 	s1=s[mw[mi][i]][i];
 1987: 	s2=s[mw[mi+1][i]][i];
 1988: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1989: 	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 */
 1990: 	ipmx +=1;
 1991: 	sw += weight[i];
 1992: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1993:       } /* end of wave */
 1994:     } /* end of individual */
 1995:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1996:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1997:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1998:       for(mi=1; mi<= wav[i]-1; mi++){
 1999: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2000: 	  for (j=1;j<=nlstate+ndeath;j++){
 2001: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2002: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2003: 	  }
 2004: 	for(d=0; d<dh[mi][i]; d++){
 2005: 	  newm=savm;
 2006: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2007: 	  for (kk=1; kk<=cptcovage;kk++) {
 2008: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2009: 	  }
 2010: 	
 2011: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2012: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2013: 	  savm=oldm;
 2014: 	  oldm=newm;
 2015: 	} /* end mult */
 2016:       
 2017: 	s1=s[mw[mi][i]][i];
 2018: 	s2=s[mw[mi+1][i]][i];
 2019: 	if( s2 > nlstate){ 
 2020: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2021: 	}else{
 2022: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2023: 	}
 2024: 	ipmx +=1;
 2025: 	sw += weight[i];
 2026: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2027: /* 	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]); */
 2028:       } /* end of wave */
 2029:     } /* end of individual */
 2030:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2031:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2032:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2033:       for(mi=1; mi<= wav[i]-1; mi++){
 2034: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2035: 	  for (j=1;j<=nlstate+ndeath;j++){
 2036: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2037: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2038: 	  }
 2039: 	for(d=0; d<dh[mi][i]; d++){
 2040: 	  newm=savm;
 2041: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2042: 	  for (kk=1; kk<=cptcovage;kk++) {
 2043: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2044: 	  }
 2045: 	
 2046: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2047: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2048: 	  savm=oldm;
 2049: 	  oldm=newm;
 2050: 	} /* end mult */
 2051:       
 2052: 	s1=s[mw[mi][i]][i];
 2053: 	s2=s[mw[mi+1][i]][i];
 2054: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2055: 	ipmx +=1;
 2056: 	sw += weight[i];
 2057: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2058: 	/*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]);*/
 2059:       } /* end of wave */
 2060:     } /* end of individual */
 2061:   } /* End of if */
 2062:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2063:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2064:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2065:   return -l;
 2066: }
 2067: 
 2068: /*************** log-likelihood *************/
 2069: double funcone( double *x)
 2070: {
 2071:   /* Same as likeli but slower because of a lot of printf and if */
 2072:   int i, ii, j, k, mi, d, kk;
 2073:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2074:   double **out;
 2075:   double lli; /* Individual log likelihood */
 2076:   double llt;
 2077:   int s1, s2;
 2078:   double bbh, survp;
 2079:   /*extern weight */
 2080:   /* We are differentiating ll according to initial status */
 2081:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2082:   /*for(i=1;i<imx;i++) 
 2083:     printf(" %d\n",s[4][i]);
 2084:   */
 2085:   cov[1]=1.;
 2086: 
 2087:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2088: 
 2089:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2090:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2091:     for(mi=1; mi<= wav[i]-1; mi++){
 2092:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2093: 	for (j=1;j<=nlstate+ndeath;j++){
 2094: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2095: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2096: 	}
 2097:       for(d=0; d<dh[mi][i]; d++){
 2098: 	newm=savm;
 2099: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2100: 	for (kk=1; kk<=cptcovage;kk++) {
 2101: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2102: 	}
 2103: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2104: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2105: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2106: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2107: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2108: 	savm=oldm;
 2109: 	oldm=newm;
 2110:       } /* end mult */
 2111:       
 2112:       s1=s[mw[mi][i]][i];
 2113:       s2=s[mw[mi+1][i]][i];
 2114:       bbh=(double)bh[mi][i]/(double)stepm; 
 2115:       /* bias is positive if real duration
 2116:        * is higher than the multiple of stepm and negative otherwise.
 2117:        */
 2118:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2119: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2120:       } else if  (s2==-2) {
 2121: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2122: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2123: 	lli= log(survp);
 2124:       }else if (mle==1){
 2125: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2126:       } else if(mle==2){
 2127: 	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 */
 2128:       } else if(mle==3){  /* exponential inter-extrapolation */
 2129: 	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 */
 2130:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2131: 	lli=log(out[s1][s2]); /* Original formula */
 2132:       } else{  /* mle=0 back to 1 */
 2133: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2134: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2135:       } /* End of if */
 2136:       ipmx +=1;
 2137:       sw += weight[i];
 2138:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2139:       /*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]); */
 2140:       if(globpr){
 2141: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2142:  %11.6f %11.6f %11.6f ", \
 2143: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2144: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2145: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2146: 	  llt +=ll[k]*gipmx/gsw;
 2147: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2148: 	}
 2149: 	fprintf(ficresilk," %10.6f\n", -llt);
 2150:       }
 2151:     } /* end of wave */
 2152:   } /* end of individual */
 2153:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2154:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2155:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2156:   if(globpr==0){ /* First time we count the contributions and weights */
 2157:     gipmx=ipmx;
 2158:     gsw=sw;
 2159:   }
 2160:   return -l;
 2161: }
 2162: 
 2163: 
 2164: /*************** function likelione ***********/
 2165: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2166: {
 2167:   /* This routine should help understanding what is done with 
 2168:      the selection of individuals/waves and
 2169:      to check the exact contribution to the likelihood.
 2170:      Plotting could be done.
 2171:    */
 2172:   int k;
 2173: 
 2174:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2175:     strcpy(fileresilk,"ilk"); 
 2176:     strcat(fileresilk,fileres);
 2177:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2178:       printf("Problem with resultfile: %s\n", fileresilk);
 2179:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2180:     }
 2181:     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");
 2182:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2183:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2184:     for(k=1; k<=nlstate; k++) 
 2185:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2186:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2187:   }
 2188: 
 2189:   *fretone=(*funcone)(p);
 2190:   if(*globpri !=0){
 2191:     fclose(ficresilk);
 2192:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2193:     fflush(fichtm); 
 2194:   } 
 2195:   return;
 2196: }
 2197: 
 2198: 
 2199: /*********** Maximum Likelihood Estimation ***************/
 2200: 
 2201: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2202: {
 2203:   int i,j, iter=0;
 2204:   double **xi;
 2205:   double fret;
 2206:   double fretone; /* Only one call to likelihood */
 2207:   /*  char filerespow[FILENAMELENGTH];*/
 2208: 
 2209: #ifdef NLOPT
 2210:   int creturn;
 2211:   nlopt_opt opt;
 2212:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2213:   double *lb;
 2214:   double minf; /* the minimum objective value, upon return */
 2215:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2216:   myfunc_data dinst, *d = &dinst;
 2217: #endif
 2218: 
 2219: 
 2220:   xi=matrix(1,npar,1,npar);
 2221:   for (i=1;i<=npar;i++)
 2222:     for (j=1;j<=npar;j++)
 2223:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2224:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2225:   strcpy(filerespow,"pow"); 
 2226:   strcat(filerespow,fileres);
 2227:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2228:     printf("Problem with resultfile: %s\n", filerespow);
 2229:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2230:   }
 2231:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2232:   for (i=1;i<=nlstate;i++)
 2233:     for(j=1;j<=nlstate+ndeath;j++)
 2234:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2235:   fprintf(ficrespow,"\n");
 2236: #ifdef POWELL
 2237:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2238: #endif
 2239: 
 2240: #ifdef NLOPT
 2241: #ifdef NEWUOA
 2242:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2243: #else
 2244:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2245: #endif
 2246:   lb=vector(0,npar-1);
 2247:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2248:   nlopt_set_lower_bounds(opt, lb);
 2249:   nlopt_set_initial_step1(opt, 0.1);
 2250:   
 2251:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2252:   d->function = func;
 2253:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2254:   nlopt_set_min_objective(opt, myfunc, d);
 2255:   nlopt_set_xtol_rel(opt, ftol);
 2256:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2257:     printf("nlopt failed! %d\n",creturn); 
 2258:   }
 2259:   else {
 2260:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2261:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2262:     iter=1; /* not equal */
 2263:   }
 2264:   nlopt_destroy(opt);
 2265: #endif
 2266:   free_matrix(xi,1,npar,1,npar);
 2267:   fclose(ficrespow);
 2268:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2269:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2270:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2271: 
 2272: }
 2273: 
 2274: /**** Computes Hessian and covariance matrix ***/
 2275: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2276: {
 2277:   double  **a,**y,*x,pd;
 2278:   double **hess;
 2279:   int i, j;
 2280:   int *indx;
 2281: 
 2282:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2283:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2284:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2285:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2286:   double gompertz(double p[]);
 2287:   hess=matrix(1,npar,1,npar);
 2288: 
 2289:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2290:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2291:   for (i=1;i<=npar;i++){
 2292:     printf("%d",i);fflush(stdout);
 2293:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2294:    
 2295:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2296:     
 2297:     /*  printf(" %f ",p[i]);
 2298: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2299:   }
 2300:   
 2301:   for (i=1;i<=npar;i++) {
 2302:     for (j=1;j<=npar;j++)  {
 2303:       if (j>i) { 
 2304: 	printf(".%d%d",i,j);fflush(stdout);
 2305: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2306: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2307: 	
 2308: 	hess[j][i]=hess[i][j];    
 2309: 	/*printf(" %lf ",hess[i][j]);*/
 2310:       }
 2311:     }
 2312:   }
 2313:   printf("\n");
 2314:   fprintf(ficlog,"\n");
 2315: 
 2316:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2317:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2318:   
 2319:   a=matrix(1,npar,1,npar);
 2320:   y=matrix(1,npar,1,npar);
 2321:   x=vector(1,npar);
 2322:   indx=ivector(1,npar);
 2323:   for (i=1;i<=npar;i++)
 2324:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2325:   ludcmp(a,npar,indx,&pd);
 2326: 
 2327:   for (j=1;j<=npar;j++) {
 2328:     for (i=1;i<=npar;i++) x[i]=0;
 2329:     x[j]=1;
 2330:     lubksb(a,npar,indx,x);
 2331:     for (i=1;i<=npar;i++){ 
 2332:       matcov[i][j]=x[i];
 2333:     }
 2334:   }
 2335: 
 2336:   printf("\n#Hessian matrix#\n");
 2337:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2338:   for (i=1;i<=npar;i++) { 
 2339:     for (j=1;j<=npar;j++) { 
 2340:       printf("%.3e ",hess[i][j]);
 2341:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2342:     }
 2343:     printf("\n");
 2344:     fprintf(ficlog,"\n");
 2345:   }
 2346: 
 2347:   /* Recompute Inverse */
 2348:   for (i=1;i<=npar;i++)
 2349:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2350:   ludcmp(a,npar,indx,&pd);
 2351: 
 2352:   /*  printf("\n#Hessian matrix recomputed#\n");
 2353: 
 2354:   for (j=1;j<=npar;j++) {
 2355:     for (i=1;i<=npar;i++) x[i]=0;
 2356:     x[j]=1;
 2357:     lubksb(a,npar,indx,x);
 2358:     for (i=1;i<=npar;i++){ 
 2359:       y[i][j]=x[i];
 2360:       printf("%.3e ",y[i][j]);
 2361:       fprintf(ficlog,"%.3e ",y[i][j]);
 2362:     }
 2363:     printf("\n");
 2364:     fprintf(ficlog,"\n");
 2365:   }
 2366:   */
 2367: 
 2368:   free_matrix(a,1,npar,1,npar);
 2369:   free_matrix(y,1,npar,1,npar);
 2370:   free_vector(x,1,npar);
 2371:   free_ivector(indx,1,npar);
 2372:   free_matrix(hess,1,npar,1,npar);
 2373: 
 2374: 
 2375: }
 2376: 
 2377: /*************** hessian matrix ****************/
 2378: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2379: {
 2380:   int i;
 2381:   int l=1, lmax=20;
 2382:   double k1,k2;
 2383:   double p2[MAXPARM+1]; /* identical to x */
 2384:   double res;
 2385:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2386:   double fx;
 2387:   int k=0,kmax=10;
 2388:   double l1;
 2389: 
 2390:   fx=func(x);
 2391:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2392:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2393:     l1=pow(10,l);
 2394:     delts=delt;
 2395:     for(k=1 ; k <kmax; k=k+1){
 2396:       delt = delta*(l1*k);
 2397:       p2[theta]=x[theta] +delt;
 2398:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2399:       p2[theta]=x[theta]-delt;
 2400:       k2=func(p2)-fx;
 2401:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2402:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2403:       
 2404: #ifdef DEBUGHESS
 2405:       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);
 2406:       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);
 2407: #endif
 2408:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2409:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2410: 	k=kmax;
 2411:       }
 2412:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2413: 	k=kmax; l=lmax*10;
 2414:       }
 2415:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2416: 	delts=delt;
 2417:       }
 2418:     }
 2419:   }
 2420:   delti[theta]=delts;
 2421:   return res; 
 2422:   
 2423: }
 2424: 
 2425: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2426: {
 2427:   int i;
 2428:   int l=1, lmax=20;
 2429:   double k1,k2,k3,k4,res,fx;
 2430:   double p2[MAXPARM+1];
 2431:   int k;
 2432: 
 2433:   fx=func(x);
 2434:   for (k=1; k<=2; k++) {
 2435:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2436:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2437:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2438:     k1=func(p2)-fx;
 2439:   
 2440:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2441:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2442:     k2=func(p2)-fx;
 2443:   
 2444:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2445:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2446:     k3=func(p2)-fx;
 2447:   
 2448:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2449:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2450:     k4=func(p2)-fx;
 2451:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2452: #ifdef DEBUG
 2453:     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);
 2454:     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);
 2455: #endif
 2456:   }
 2457:   return res;
 2458: }
 2459: 
 2460: /************** Inverse of matrix **************/
 2461: void ludcmp(double **a, int n, int *indx, double *d) 
 2462: { 
 2463:   int i,imax,j,k; 
 2464:   double big,dum,sum,temp; 
 2465:   double *vv; 
 2466:  
 2467:   vv=vector(1,n); 
 2468:   *d=1.0; 
 2469:   for (i=1;i<=n;i++) { 
 2470:     big=0.0; 
 2471:     for (j=1;j<=n;j++) 
 2472:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2473:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2474:     vv[i]=1.0/big; 
 2475:   } 
 2476:   for (j=1;j<=n;j++) { 
 2477:     for (i=1;i<j;i++) { 
 2478:       sum=a[i][j]; 
 2479:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2480:       a[i][j]=sum; 
 2481:     } 
 2482:     big=0.0; 
 2483:     for (i=j;i<=n;i++) { 
 2484:       sum=a[i][j]; 
 2485:       for (k=1;k<j;k++) 
 2486: 	sum -= a[i][k]*a[k][j]; 
 2487:       a[i][j]=sum; 
 2488:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2489: 	big=dum; 
 2490: 	imax=i; 
 2491:       } 
 2492:     } 
 2493:     if (j != imax) { 
 2494:       for (k=1;k<=n;k++) { 
 2495: 	dum=a[imax][k]; 
 2496: 	a[imax][k]=a[j][k]; 
 2497: 	a[j][k]=dum; 
 2498:       } 
 2499:       *d = -(*d); 
 2500:       vv[imax]=vv[j]; 
 2501:     } 
 2502:     indx[j]=imax; 
 2503:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2504:     if (j != n) { 
 2505:       dum=1.0/(a[j][j]); 
 2506:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2507:     } 
 2508:   } 
 2509:   free_vector(vv,1,n);  /* Doesn't work */
 2510: ;
 2511: } 
 2512: 
 2513: void lubksb(double **a, int n, int *indx, double b[]) 
 2514: { 
 2515:   int i,ii=0,ip,j; 
 2516:   double sum; 
 2517:  
 2518:   for (i=1;i<=n;i++) { 
 2519:     ip=indx[i]; 
 2520:     sum=b[ip]; 
 2521:     b[ip]=b[i]; 
 2522:     if (ii) 
 2523:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2524:     else if (sum) ii=i; 
 2525:     b[i]=sum; 
 2526:   } 
 2527:   for (i=n;i>=1;i--) { 
 2528:     sum=b[i]; 
 2529:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2530:     b[i]=sum/a[i][i]; 
 2531:   } 
 2532: } 
 2533: 
 2534: void pstamp(FILE *fichier)
 2535: {
 2536:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2537: }
 2538: 
 2539: /************ Frequencies ********************/
 2540: 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[])
 2541: {  /* Some frequencies */
 2542:   
 2543:   int i, m, jk, j1, bool, z1,j;
 2544:   int first;
 2545:   double ***freq; /* Frequencies */
 2546:   double *pp, **prop;
 2547:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2548:   char fileresp[FILENAMELENGTH];
 2549:   
 2550:   pp=vector(1,nlstate);
 2551:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2552:   strcpy(fileresp,"p");
 2553:   strcat(fileresp,fileres);
 2554:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2555:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2556:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2557:     exit(0);
 2558:   }
 2559:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2560:   j1=0;
 2561:   
 2562:   j=cptcoveff;
 2563:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2564: 
 2565:   first=1;
 2566: 
 2567:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2568:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2569:   /*    j1++; */
 2570:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2571:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2572: 	scanf("%d", i);*/
 2573:       for (i=-5; i<=nlstate+ndeath; i++)  
 2574: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2575: 	  for(m=iagemin; m <= iagemax+3; m++)
 2576: 	    freq[i][jk][m]=0;
 2577:       
 2578:       for (i=1; i<=nlstate; i++)  
 2579: 	for(m=iagemin; m <= iagemax+3; m++)
 2580: 	  prop[i][m]=0;
 2581:       
 2582:       dateintsum=0;
 2583:       k2cpt=0;
 2584:       for (i=1; i<=imx; i++) {
 2585: 	bool=1;
 2586: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2587: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2588:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2589:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2590:               bool=0;
 2591:               /* 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", 
 2592:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2593:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2594:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2595:             } 
 2596: 	}
 2597:  
 2598: 	if (bool==1){
 2599: 	  for(m=firstpass; m<=lastpass; m++){
 2600: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2601: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2602: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2603: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2604: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2605: 	      if (m<lastpass) {
 2606: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2607: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2608: 	      }
 2609: 	      
 2610: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2611: 		dateintsum=dateintsum+k2;
 2612: 		k2cpt++;
 2613: 	      }
 2614: 	      /*}*/
 2615: 	  }
 2616: 	}
 2617:       } /* end i */
 2618:        
 2619:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2620:       pstamp(ficresp);
 2621:       if  (cptcovn>0) {
 2622: 	fprintf(ficresp, "\n#********** Variable "); 
 2623: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2624: 	fprintf(ficresp, "**********\n#");
 2625: 	fprintf(ficlog, "\n#********** Variable "); 
 2626: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2627: 	fprintf(ficlog, "**********\n#");
 2628:       }
 2629:       for(i=1; i<=nlstate;i++) 
 2630: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2631:       fprintf(ficresp, "\n");
 2632:       
 2633:       for(i=iagemin; i <= iagemax+3; i++){
 2634: 	if(i==iagemax+3){
 2635: 	  fprintf(ficlog,"Total");
 2636: 	}else{
 2637: 	  if(first==1){
 2638: 	    first=0;
 2639: 	    printf("See log file for details...\n");
 2640: 	  }
 2641: 	  fprintf(ficlog,"Age %d", i);
 2642: 	}
 2643: 	for(jk=1; jk <=nlstate ; jk++){
 2644: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2645: 	    pp[jk] += freq[jk][m][i]; 
 2646: 	}
 2647: 	for(jk=1; jk <=nlstate ; jk++){
 2648: 	  for(m=-1, pos=0; m <=0 ; m++)
 2649: 	    pos += freq[jk][m][i];
 2650: 	  if(pp[jk]>=1.e-10){
 2651: 	    if(first==1){
 2652: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2653: 	    }
 2654: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2655: 	  }else{
 2656: 	    if(first==1)
 2657: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2658: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2659: 	  }
 2660: 	}
 2661: 
 2662: 	for(jk=1; jk <=nlstate ; jk++){
 2663: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2664: 	    pp[jk] += freq[jk][m][i];
 2665: 	}	
 2666: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2667: 	  pos += pp[jk];
 2668: 	  posprop += prop[jk][i];
 2669: 	}
 2670: 	for(jk=1; jk <=nlstate ; jk++){
 2671: 	  if(pos>=1.e-5){
 2672: 	    if(first==1)
 2673: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2674: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2675: 	  }else{
 2676: 	    if(first==1)
 2677: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2678: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2679: 	  }
 2680: 	  if( i <= iagemax){
 2681: 	    if(pos>=1.e-5){
 2682: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2683: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2684: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2685: 	    }
 2686: 	    else
 2687: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2688: 	  }
 2689: 	}
 2690: 	
 2691: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2692: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2693: 	    if(freq[jk][m][i] !=0 ) {
 2694: 	    if(first==1)
 2695: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2696: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2697: 	    }
 2698: 	if(i <= iagemax)
 2699: 	  fprintf(ficresp,"\n");
 2700: 	if(first==1)
 2701: 	  printf("Others in log...\n");
 2702: 	fprintf(ficlog,"\n");
 2703:       }
 2704:       /*}*/
 2705:   }
 2706:   dateintmean=dateintsum/k2cpt; 
 2707:  
 2708:   fclose(ficresp);
 2709:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2710:   free_vector(pp,1,nlstate);
 2711:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2712:   /* End of Freq */
 2713: }
 2714: 
 2715: /************ Prevalence ********************/
 2716: 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)
 2717: {  
 2718:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2719:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2720:      We still use firstpass and lastpass as another selection.
 2721:   */
 2722:  
 2723:   int i, m, jk, j1, bool, z1,j;
 2724: 
 2725:   double **prop;
 2726:   double posprop; 
 2727:   double  y2; /* in fractional years */
 2728:   int iagemin, iagemax;
 2729:   int first; /** to stop verbosity which is redirected to log file */
 2730: 
 2731:   iagemin= (int) agemin;
 2732:   iagemax= (int) agemax;
 2733:   /*pp=vector(1,nlstate);*/
 2734:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2735:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2736:   j1=0;
 2737:   
 2738:   /*j=cptcoveff;*/
 2739:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2740:   
 2741:   first=1;
 2742:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2743:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2744:       j1++;*/
 2745:       
 2746:       for (i=1; i<=nlstate; i++)  
 2747: 	for(m=iagemin; m <= iagemax+3; m++)
 2748: 	  prop[i][m]=0.0;
 2749:      
 2750:       for (i=1; i<=imx; i++) { /* Each individual */
 2751: 	bool=1;
 2752: 	if  (cptcovn>0) {
 2753: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2754: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2755: 	      bool=0;
 2756: 	} 
 2757: 	if (bool==1) { 
 2758: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2759: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2760: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2761: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2762: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2763: 	      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); 
 2764:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2765: 		/*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]]);*/
 2766:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2767:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2768:  	      } 
 2769: 	    }
 2770: 	  } /* end selection of waves */
 2771: 	}
 2772:       }
 2773:       for(i=iagemin; i <= iagemax+3; i++){  
 2774:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2775:  	  posprop += prop[jk][i]; 
 2776:  	} 
 2777: 	
 2778:  	for(jk=1; jk <=nlstate ; jk++){	    
 2779:  	  if( i <=  iagemax){ 
 2780:  	    if(posprop>=1.e-5){ 
 2781:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2782:  	    } else{
 2783: 	      if(first==1){
 2784: 		first=0;
 2785: 		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]);
 2786: 	      }
 2787: 	    }
 2788:  	  } 
 2789:  	}/* end jk */ 
 2790:       }/* end i */ 
 2791:     /*} *//* end i1 */
 2792:   } /* end j1 */
 2793:   
 2794:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2795:   /*free_vector(pp,1,nlstate);*/
 2796:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2797: }  /* End of prevalence */
 2798: 
 2799: /************* Waves Concatenation ***************/
 2800: 
 2801: 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)
 2802: {
 2803:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2804:      Death is a valid wave (if date is known).
 2805:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2806:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2807:      and mw[mi+1][i]. dh depends on stepm.
 2808:      */
 2809: 
 2810:   int i, mi, m;
 2811:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2812:      double sum=0., jmean=0.;*/
 2813:   int first;
 2814:   int j, k=0,jk, ju, jl;
 2815:   double sum=0.;
 2816:   first=0;
 2817:   jmin=100000;
 2818:   jmax=-1;
 2819:   jmean=0.;
 2820:   for(i=1; i<=imx; i++){
 2821:     mi=0;
 2822:     m=firstpass;
 2823:     while(s[m][i] <= nlstate){
 2824:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2825: 	mw[++mi][i]=m;
 2826:       if(m >=lastpass)
 2827: 	break;
 2828:       else
 2829: 	m++;
 2830:     }/* end while */
 2831:     if (s[m][i] > nlstate){
 2832:       mi++;	/* Death is another wave */
 2833:       /* if(mi==0)  never been interviewed correctly before death */
 2834: 	 /* Only death is a correct wave */
 2835:       mw[mi][i]=m;
 2836:     }
 2837: 
 2838:     wav[i]=mi;
 2839:     if(mi==0){
 2840:       nbwarn++;
 2841:       if(first==0){
 2842: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2843: 	first=1;
 2844:       }
 2845:       if(first==1){
 2846: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2847:       }
 2848:     } /* end mi==0 */
 2849:   } /* End individuals */
 2850: 
 2851:   for(i=1; i<=imx; i++){
 2852:     for(mi=1; mi<wav[i];mi++){
 2853:       if (stepm <=0)
 2854: 	dh[mi][i]=1;
 2855:       else{
 2856: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2857: 	  if (agedc[i] < 2*AGESUP) {
 2858: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2859: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2860: 	    else if(j<0){
 2861: 	      nberr++;
 2862: 	      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]);
 2863: 	      j=1; /* Temporary Dangerous patch */
 2864: 	      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);
 2865: 	      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]);
 2866: 	      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);
 2867: 	    }
 2868: 	    k=k+1;
 2869: 	    if (j >= jmax){
 2870: 	      jmax=j;
 2871: 	      ijmax=i;
 2872: 	    }
 2873: 	    if (j <= jmin){
 2874: 	      jmin=j;
 2875: 	      ijmin=i;
 2876: 	    }
 2877: 	    sum=sum+j;
 2878: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2879: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2880: 	  }
 2881: 	}
 2882: 	else{
 2883: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2884: /* 	  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]); */
 2885: 
 2886: 	  k=k+1;
 2887: 	  if (j >= jmax) {
 2888: 	    jmax=j;
 2889: 	    ijmax=i;
 2890: 	  }
 2891: 	  else if (j <= jmin){
 2892: 	    jmin=j;
 2893: 	    ijmin=i;
 2894: 	  }
 2895: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2896: 	  /*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]);*/
 2897: 	  if(j<0){
 2898: 	    nberr++;
 2899: 	    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]);
 2900: 	    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]);
 2901: 	  }
 2902: 	  sum=sum+j;
 2903: 	}
 2904: 	jk= j/stepm;
 2905: 	jl= j -jk*stepm;
 2906: 	ju= j -(jk+1)*stepm;
 2907: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2908: 	  if(jl==0){
 2909: 	    dh[mi][i]=jk;
 2910: 	    bh[mi][i]=0;
 2911: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2912: 		  * to avoid the price of an extra matrix product in likelihood */
 2913: 	    dh[mi][i]=jk+1;
 2914: 	    bh[mi][i]=ju;
 2915: 	  }
 2916: 	}else{
 2917: 	  if(jl <= -ju){
 2918: 	    dh[mi][i]=jk;
 2919: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2920: 				 * is higher than the multiple of stepm and negative otherwise.
 2921: 				 */
 2922: 	  }
 2923: 	  else{
 2924: 	    dh[mi][i]=jk+1;
 2925: 	    bh[mi][i]=ju;
 2926: 	  }
 2927: 	  if(dh[mi][i]==0){
 2928: 	    dh[mi][i]=1; /* At least one step */
 2929: 	    bh[mi][i]=ju; /* At least one step */
 2930: 	    /*  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);*/
 2931: 	  }
 2932: 	} /* end if mle */
 2933:       }
 2934:     } /* end wave */
 2935:   }
 2936:   jmean=sum/k;
 2937:   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);
 2938:   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);
 2939:  }
 2940: 
 2941: /*********** Tricode ****************************/
 2942: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 2943: {
 2944:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 2945:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 2946:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 2947:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 2948:    * nbcode[Tvar[j]][1]= 
 2949:   */
 2950: 
 2951:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2952:   int modmaxcovj=0; /* Modality max of covariates j */
 2953:   int cptcode=0; /* Modality max of covariates j */
 2954:   int modmincovj=0; /* Modality min of covariates j */
 2955: 
 2956: 
 2957:   cptcoveff=0; 
 2958:  
 2959:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 2960:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 2961: 
 2962:   /* Loop on covariates without age and products */
 2963:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 2964:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 2965: 			       modality of this covariate Vj*/ 
 2966:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 2967: 				    * If product of Vn*Vm, still boolean *:
 2968: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 2969: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 2970:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2971: 				      modality of the nth covariate of individual i. */
 2972:       if (ij > modmaxcovj)
 2973:         modmaxcovj=ij; 
 2974:       else if (ij < modmincovj) 
 2975: 	modmincovj=ij; 
 2976:       if ((ij < -1) && (ij > NCOVMAX)){
 2977: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 2978: 	exit(1);
 2979:       }else
 2980:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2981:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 2982:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2983:       /* getting the maximum value of the modality of the covariate
 2984: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2985: 	 female is 1, then modmaxcovj=1.*/
 2986:     }
 2987:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 2988:     cptcode=modmaxcovj;
 2989:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2990:    /*for (i=0; i<=cptcode; i++) {*/
 2991:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 2992:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 2993:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 2994: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 2995:       }
 2996:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2997: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 2998:     } /* Ndum[-1] number of undefined modalities */
 2999: 
 3000:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3001:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 3002:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 3003:        modmincovj=3; modmaxcovj = 7;
 3004:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 3005:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 3006:        variables V1_1 and V1_2.
 3007:        nbcode[Tvar[j]][ij]=k;
 3008:        nbcode[Tvar[j]][1]=0;
 3009:        nbcode[Tvar[j]][2]=1;
 3010:        nbcode[Tvar[j]][3]=2;
 3011:     */
 3012:     ij=1; /* ij is similar to i but can jumps over null modalities */
 3013:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 3014:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 3015: 	/*recode from 0 */
 3016: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 3017: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 3018: 				     k is a modality. If we have model=V1+V1*sex 
 3019: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3020: 	  ij++;
 3021: 	}
 3022: 	if (ij > ncodemax[j]) break; 
 3023:       }  /* end of loop on */
 3024:     } /* end of loop on modality */ 
 3025:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3026:   
 3027:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3028:   
 3029:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 3030:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3031:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3032:    Ndum[ij]++; 
 3033:  } 
 3034: 
 3035:  ij=1;
 3036:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3037:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3038:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3039:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3040:      Tvaraff[ij]=i; /*For printing (unclear) */
 3041:      ij++;
 3042:    }else
 3043:        Tvaraff[ij]=0;
 3044:  }
 3045:  ij--;
 3046:  cptcoveff=ij; /*Number of total covariates*/
 3047: 
 3048: }
 3049: 
 3050: 
 3051: /*********** Health Expectancies ****************/
 3052: 
 3053: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3054: 
 3055: {
 3056:   /* Health expectancies, no variances */
 3057:   int i, j, nhstepm, hstepm, h, nstepm;
 3058:   int nhstepma, nstepma; /* Decreasing with age */
 3059:   double age, agelim, hf;
 3060:   double ***p3mat;
 3061:   double eip;
 3062: 
 3063:   pstamp(ficreseij);
 3064:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3065:   fprintf(ficreseij,"# Age");
 3066:   for(i=1; i<=nlstate;i++){
 3067:     for(j=1; j<=nlstate;j++){
 3068:       fprintf(ficreseij," e%1d%1d ",i,j);
 3069:     }
 3070:     fprintf(ficreseij," e%1d. ",i);
 3071:   }
 3072:   fprintf(ficreseij,"\n");
 3073: 
 3074:   
 3075:   if(estepm < stepm){
 3076:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3077:   }
 3078:   else  hstepm=estepm;   
 3079:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3080:    * This is mainly to measure the difference between two models: for example
 3081:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3082:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3083:    * progression in between and thus overestimating or underestimating according
 3084:    * to the curvature of the survival function. If, for the same date, we 
 3085:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3086:    * to compare the new estimate of Life expectancy with the same linear 
 3087:    * hypothesis. A more precise result, taking into account a more precise
 3088:    * curvature will be obtained if estepm is as small as stepm. */
 3089: 
 3090:   /* For example we decided to compute the life expectancy with the smallest unit */
 3091:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3092:      nhstepm is the number of hstepm from age to agelim 
 3093:      nstepm is the number of stepm from age to agelin. 
 3094:      Look at hpijx to understand the reason of that which relies in memory size
 3095:      and note for a fixed period like estepm months */
 3096:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3097:      survival function given by stepm (the optimization length). Unfortunately it
 3098:      means that if the survival funtion is printed only each two years of age and if
 3099:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3100:      results. So we changed our mind and took the option of the best precision.
 3101:   */
 3102:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3103: 
 3104:   agelim=AGESUP;
 3105:   /* If stepm=6 months */
 3106:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3107:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3108:     
 3109: /* nhstepm age range expressed in number of stepm */
 3110:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3111:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3112:   /* if (stepm >= YEARM) hstepm=1;*/
 3113:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3114:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3115: 
 3116:   for (age=bage; age<=fage; age ++){ 
 3117:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3118:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3119:     /* if (stepm >= YEARM) hstepm=1;*/
 3120:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3121: 
 3122:     /* If stepm=6 months */
 3123:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3124:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3125:     
 3126:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3127:     
 3128:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3129:     
 3130:     printf("%d|",(int)age);fflush(stdout);
 3131:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3132:     
 3133:     /* Computing expectancies */
 3134:     for(i=1; i<=nlstate;i++)
 3135:       for(j=1; j<=nlstate;j++)
 3136: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3137: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3138: 	  
 3139: 	  /* 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]);*/
 3140: 
 3141: 	}
 3142: 
 3143:     fprintf(ficreseij,"%3.0f",age );
 3144:     for(i=1; i<=nlstate;i++){
 3145:       eip=0;
 3146:       for(j=1; j<=nlstate;j++){
 3147: 	eip +=eij[i][j][(int)age];
 3148: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3149:       }
 3150:       fprintf(ficreseij,"%9.4f", eip );
 3151:     }
 3152:     fprintf(ficreseij,"\n");
 3153:     
 3154:   }
 3155:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3156:   printf("\n");
 3157:   fprintf(ficlog,"\n");
 3158:   
 3159: }
 3160: 
 3161: 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[] )
 3162: 
 3163: {
 3164:   /* Covariances of health expectancies eij and of total life expectancies according
 3165:    to initial status i, ei. .
 3166:   */
 3167:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3168:   int nhstepma, nstepma; /* Decreasing with age */
 3169:   double age, agelim, hf;
 3170:   double ***p3matp, ***p3matm, ***varhe;
 3171:   double **dnewm,**doldm;
 3172:   double *xp, *xm;
 3173:   double **gp, **gm;
 3174:   double ***gradg, ***trgradg;
 3175:   int theta;
 3176: 
 3177:   double eip, vip;
 3178: 
 3179:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3180:   xp=vector(1,npar);
 3181:   xm=vector(1,npar);
 3182:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3183:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3184:   
 3185:   pstamp(ficresstdeij);
 3186:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3187:   fprintf(ficresstdeij,"# Age");
 3188:   for(i=1; i<=nlstate;i++){
 3189:     for(j=1; j<=nlstate;j++)
 3190:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3191:     fprintf(ficresstdeij," e%1d. ",i);
 3192:   }
 3193:   fprintf(ficresstdeij,"\n");
 3194: 
 3195:   pstamp(ficrescveij);
 3196:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3197:   fprintf(ficrescveij,"# Age");
 3198:   for(i=1; i<=nlstate;i++)
 3199:     for(j=1; j<=nlstate;j++){
 3200:       cptj= (j-1)*nlstate+i;
 3201:       for(i2=1; i2<=nlstate;i2++)
 3202: 	for(j2=1; j2<=nlstate;j2++){
 3203: 	  cptj2= (j2-1)*nlstate+i2;
 3204: 	  if(cptj2 <= cptj)
 3205: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3206: 	}
 3207:     }
 3208:   fprintf(ficrescveij,"\n");
 3209:   
 3210:   if(estepm < stepm){
 3211:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3212:   }
 3213:   else  hstepm=estepm;   
 3214:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3215:    * This is mainly to measure the difference between two models: for example
 3216:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3217:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3218:    * progression in between and thus overestimating or underestimating according
 3219:    * to the curvature of the survival function. If, for the same date, we 
 3220:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3221:    * to compare the new estimate of Life expectancy with the same linear 
 3222:    * hypothesis. A more precise result, taking into account a more precise
 3223:    * curvature will be obtained if estepm is as small as stepm. */
 3224: 
 3225:   /* For example we decided to compute the life expectancy with the smallest unit */
 3226:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3227:      nhstepm is the number of hstepm from age to agelim 
 3228:      nstepm is the number of stepm from age to agelin. 
 3229:      Look at hpijx to understand the reason of that which relies in memory size
 3230:      and note for a fixed period like estepm months */
 3231:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3232:      survival function given by stepm (the optimization length). Unfortunately it
 3233:      means that if the survival funtion is printed only each two years of age and if
 3234:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3235:      results. So we changed our mind and took the option of the best precision.
 3236:   */
 3237:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3238: 
 3239:   /* If stepm=6 months */
 3240:   /* nhstepm age range expressed in number of stepm */
 3241:   agelim=AGESUP;
 3242:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3243:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3244:   /* if (stepm >= YEARM) hstepm=1;*/
 3245:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3246:   
 3247:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3248:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3249:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3250:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3251:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3252:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3253: 
 3254:   for (age=bage; age<=fage; age ++){ 
 3255:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3256:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3257:     /* if (stepm >= YEARM) hstepm=1;*/
 3258:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3259: 
 3260:     /* If stepm=6 months */
 3261:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3262:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3263:     
 3264:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3265: 
 3266:     /* Computing  Variances of health expectancies */
 3267:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3268:        decrease memory allocation */
 3269:     for(theta=1; theta <=npar; theta++){
 3270:       for(i=1; i<=npar; i++){ 
 3271: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3272: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3273:       }
 3274:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3275:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3276:   
 3277:       for(j=1; j<= nlstate; j++){
 3278: 	for(i=1; i<=nlstate; i++){
 3279: 	  for(h=0; h<=nhstepm-1; h++){
 3280: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3281: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3282: 	  }
 3283: 	}
 3284:       }
 3285:      
 3286:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3287: 	for(h=0; h<=nhstepm-1; h++){
 3288: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3289: 	}
 3290:     }/* End theta */
 3291:     
 3292:     
 3293:     for(h=0; h<=nhstepm-1; h++)
 3294:       for(j=1; j<=nlstate*nlstate;j++)
 3295: 	for(theta=1; theta <=npar; theta++)
 3296: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3297:     
 3298: 
 3299:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3300:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3301: 	varhe[ij][ji][(int)age] =0.;
 3302: 
 3303:      printf("%d|",(int)age);fflush(stdout);
 3304:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3305:      for(h=0;h<=nhstepm-1;h++){
 3306:       for(k=0;k<=nhstepm-1;k++){
 3307: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3308: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3309: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3310: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3311: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3312:       }
 3313:     }
 3314: 
 3315:     /* Computing expectancies */
 3316:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3317:     for(i=1; i<=nlstate;i++)
 3318:       for(j=1; j<=nlstate;j++)
 3319: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3320: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3321: 	  
 3322: 	  /* 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]);*/
 3323: 
 3324: 	}
 3325: 
 3326:     fprintf(ficresstdeij,"%3.0f",age );
 3327:     for(i=1; i<=nlstate;i++){
 3328:       eip=0.;
 3329:       vip=0.;
 3330:       for(j=1; j<=nlstate;j++){
 3331: 	eip += eij[i][j][(int)age];
 3332: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3333: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3334: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3335:       }
 3336:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3337:     }
 3338:     fprintf(ficresstdeij,"\n");
 3339: 
 3340:     fprintf(ficrescveij,"%3.0f",age );
 3341:     for(i=1; i<=nlstate;i++)
 3342:       for(j=1; j<=nlstate;j++){
 3343: 	cptj= (j-1)*nlstate+i;
 3344: 	for(i2=1; i2<=nlstate;i2++)
 3345: 	  for(j2=1; j2<=nlstate;j2++){
 3346: 	    cptj2= (j2-1)*nlstate+i2;
 3347: 	    if(cptj2 <= cptj)
 3348: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3349: 	  }
 3350:       }
 3351:     fprintf(ficrescveij,"\n");
 3352:    
 3353:   }
 3354:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3355:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3356:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3357:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3358:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3359:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3360:   printf("\n");
 3361:   fprintf(ficlog,"\n");
 3362: 
 3363:   free_vector(xm,1,npar);
 3364:   free_vector(xp,1,npar);
 3365:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3366:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3367:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3368: }
 3369: 
 3370: /************ Variance ******************/
 3371: 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[])
 3372: {
 3373:   /* Variance of health expectancies */
 3374:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3375:   /* double **newm;*/
 3376:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3377:   
 3378:   int movingaverage();
 3379:   double **dnewm,**doldm;
 3380:   double **dnewmp,**doldmp;
 3381:   int i, j, nhstepm, hstepm, h, nstepm ;
 3382:   int k;
 3383:   double *xp;
 3384:   double **gp, **gm;  /* for var eij */
 3385:   double ***gradg, ***trgradg; /*for var eij */
 3386:   double **gradgp, **trgradgp; /* for var p point j */
 3387:   double *gpp, *gmp; /* for var p point j */
 3388:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3389:   double ***p3mat;
 3390:   double age,agelim, hf;
 3391:   double ***mobaverage;
 3392:   int theta;
 3393:   char digit[4];
 3394:   char digitp[25];
 3395: 
 3396:   char fileresprobmorprev[FILENAMELENGTH];
 3397: 
 3398:   if(popbased==1){
 3399:     if(mobilav!=0)
 3400:       strcpy(digitp,"-populbased-mobilav-");
 3401:     else strcpy(digitp,"-populbased-nomobil-");
 3402:   }
 3403:   else 
 3404:     strcpy(digitp,"-stablbased-");
 3405: 
 3406:   if (mobilav!=0) {
 3407:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3408:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3409:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3410:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3411:     }
 3412:   }
 3413: 
 3414:   strcpy(fileresprobmorprev,"prmorprev"); 
 3415:   sprintf(digit,"%-d",ij);
 3416:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3417:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3418:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3419:   strcat(fileresprobmorprev,fileres);
 3420:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3421:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3422:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3423:   }
 3424:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3425:  
 3426:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3427:   pstamp(ficresprobmorprev);
 3428:   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);
 3429:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3430:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3431:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3432:     for(i=1; i<=nlstate;i++)
 3433:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3434:   }  
 3435:   fprintf(ficresprobmorprev,"\n");
 3436:   fprintf(ficgp,"\n# Routine varevsij");
 3437:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3438:   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");
 3439:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3440: /*   } */
 3441:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3442:   pstamp(ficresvij);
 3443:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3444:   if(popbased==1)
 3445:     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);
 3446:   else
 3447:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3448:   fprintf(ficresvij,"# Age");
 3449:   for(i=1; i<=nlstate;i++)
 3450:     for(j=1; j<=nlstate;j++)
 3451:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3452:   fprintf(ficresvij,"\n");
 3453: 
 3454:   xp=vector(1,npar);
 3455:   dnewm=matrix(1,nlstate,1,npar);
 3456:   doldm=matrix(1,nlstate,1,nlstate);
 3457:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3458:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3459: 
 3460:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3461:   gpp=vector(nlstate+1,nlstate+ndeath);
 3462:   gmp=vector(nlstate+1,nlstate+ndeath);
 3463:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3464:   
 3465:   if(estepm < stepm){
 3466:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3467:   }
 3468:   else  hstepm=estepm;   
 3469:   /* For example we decided to compute the life expectancy with the smallest unit */
 3470:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3471:      nhstepm is the number of hstepm from age to agelim 
 3472:      nstepm is the number of stepm from age to agelin. 
 3473:      Look at function hpijx to understand why (it is linked to memory size questions) */
 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 every 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:   agelim = AGESUP;
 3482:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3483:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3484:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3485:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3486:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3487:     gp=matrix(0,nhstepm,1,nlstate);
 3488:     gm=matrix(0,nhstepm,1,nlstate);
 3489: 
 3490: 
 3491:     for(theta=1; theta <=npar; theta++){
 3492:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3493: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3494:       }
 3495:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3496:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3497: 
 3498:       if (popbased==1) {
 3499: 	if(mobilav ==0){
 3500: 	  for(i=1; i<=nlstate;i++)
 3501: 	    prlim[i][i]=probs[(int)age][i][ij];
 3502: 	}else{ /* mobilav */ 
 3503: 	  for(i=1; i<=nlstate;i++)
 3504: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3505: 	}
 3506:       }
 3507:   
 3508:       for(j=1; j<= nlstate; j++){
 3509: 	for(h=0; h<=nhstepm; h++){
 3510: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3511: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3512: 	}
 3513:       }
 3514:       /* This for computing probability of death (h=1 means
 3515:          computed over hstepm matrices product = hstepm*stepm months) 
 3516:          as a weighted average of prlim.
 3517:       */
 3518:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3519: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3520: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3521:       }    
 3522:       /* end probability of death */
 3523: 
 3524:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3525: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3526:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3527:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3528:  
 3529:       if (popbased==1) {
 3530: 	if(mobilav ==0){
 3531: 	  for(i=1; i<=nlstate;i++)
 3532: 	    prlim[i][i]=probs[(int)age][i][ij];
 3533: 	}else{ /* mobilav */ 
 3534: 	  for(i=1; i<=nlstate;i++)
 3535: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3536: 	}
 3537:       }
 3538: 
 3539:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3540: 	for(h=0; h<=nhstepm; h++){
 3541: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3542: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3543: 	}
 3544:       }
 3545:       /* This for computing probability of death (h=1 means
 3546:          computed over hstepm matrices product = hstepm*stepm months) 
 3547:          as a weighted average of prlim.
 3548:       */
 3549:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3550: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3551:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3552:       }    
 3553:       /* end probability of death */
 3554: 
 3555:       for(j=1; j<= nlstate; j++) /* vareij */
 3556: 	for(h=0; h<=nhstepm; h++){
 3557: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3558: 	}
 3559: 
 3560:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3561: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3562:       }
 3563: 
 3564:     } /* End theta */
 3565: 
 3566:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3567: 
 3568:     for(h=0; h<=nhstepm; h++) /* veij */
 3569:       for(j=1; j<=nlstate;j++)
 3570: 	for(theta=1; theta <=npar; theta++)
 3571: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3572: 
 3573:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3574:       for(theta=1; theta <=npar; theta++)
 3575: 	trgradgp[j][theta]=gradgp[theta][j];
 3576:   
 3577: 
 3578:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3579:     for(i=1;i<=nlstate;i++)
 3580:       for(j=1;j<=nlstate;j++)
 3581: 	vareij[i][j][(int)age] =0.;
 3582: 
 3583:     for(h=0;h<=nhstepm;h++){
 3584:       for(k=0;k<=nhstepm;k++){
 3585: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3586: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3587: 	for(i=1;i<=nlstate;i++)
 3588: 	  for(j=1;j<=nlstate;j++)
 3589: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3590:       }
 3591:     }
 3592:   
 3593:     /* pptj */
 3594:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3595:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3596:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3597:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3598: 	varppt[j][i]=doldmp[j][i];
 3599:     /* end ppptj */
 3600:     /*  x centered again */
 3601:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3602:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3603:  
 3604:     if (popbased==1) {
 3605:       if(mobilav ==0){
 3606: 	for(i=1; i<=nlstate;i++)
 3607: 	  prlim[i][i]=probs[(int)age][i][ij];
 3608:       }else{ /* mobilav */ 
 3609: 	for(i=1; i<=nlstate;i++)
 3610: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3611:       }
 3612:     }
 3613:              
 3614:     /* This for computing probability of death (h=1 means
 3615:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3616:        as a weighted average of prlim.
 3617:     */
 3618:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3619:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3620: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3621:     }    
 3622:     /* end probability of death */
 3623: 
 3624:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3625:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3626:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3627:       for(i=1; i<=nlstate;i++){
 3628: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3629:       }
 3630:     } 
 3631:     fprintf(ficresprobmorprev,"\n");
 3632: 
 3633:     fprintf(ficresvij,"%.0f ",age );
 3634:     for(i=1; i<=nlstate;i++)
 3635:       for(j=1; j<=nlstate;j++){
 3636: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3637:       }
 3638:     fprintf(ficresvij,"\n");
 3639:     free_matrix(gp,0,nhstepm,1,nlstate);
 3640:     free_matrix(gm,0,nhstepm,1,nlstate);
 3641:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3642:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3643:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3644:   } /* End age */
 3645:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3646:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3647:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3648:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3649:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3650:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3651:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3652: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3653: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3654: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3655:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3656:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3657:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3658:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3659:   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);
 3660:   /*  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);
 3661: */
 3662: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3663:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3664: 
 3665:   free_vector(xp,1,npar);
 3666:   free_matrix(doldm,1,nlstate,1,nlstate);
 3667:   free_matrix(dnewm,1,nlstate,1,npar);
 3668:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3669:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3670:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3671:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3672:   fclose(ficresprobmorprev);
 3673:   fflush(ficgp);
 3674:   fflush(fichtm); 
 3675: }  /* end varevsij */
 3676: 
 3677: /************ Variance of prevlim ******************/
 3678: 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[])
 3679: {
 3680:   /* Variance of prevalence limit */
 3681:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3682: 
 3683:   double **dnewm,**doldm;
 3684:   int i, j, nhstepm, hstepm;
 3685:   double *xp;
 3686:   double *gp, *gm;
 3687:   double **gradg, **trgradg;
 3688:   double age,agelim;
 3689:   int theta;
 3690:   
 3691:   pstamp(ficresvpl);
 3692:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3693:   fprintf(ficresvpl,"# Age");
 3694:   for(i=1; i<=nlstate;i++)
 3695:       fprintf(ficresvpl," %1d-%1d",i,i);
 3696:   fprintf(ficresvpl,"\n");
 3697: 
 3698:   xp=vector(1,npar);
 3699:   dnewm=matrix(1,nlstate,1,npar);
 3700:   doldm=matrix(1,nlstate,1,nlstate);
 3701:   
 3702:   hstepm=1*YEARM; /* Every year of age */
 3703:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3704:   agelim = AGESUP;
 3705:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3706:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3707:     if (stepm >= YEARM) hstepm=1;
 3708:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3709:     gradg=matrix(1,npar,1,nlstate);
 3710:     gp=vector(1,nlstate);
 3711:     gm=vector(1,nlstate);
 3712: 
 3713:     for(theta=1; theta <=npar; theta++){
 3714:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3715: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3716:       }
 3717:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3718:       for(i=1;i<=nlstate;i++)
 3719: 	gp[i] = prlim[i][i];
 3720:     
 3721:       for(i=1; i<=npar; i++) /* Computes gradient */
 3722: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3723:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3724:       for(i=1;i<=nlstate;i++)
 3725: 	gm[i] = prlim[i][i];
 3726: 
 3727:       for(i=1;i<=nlstate;i++)
 3728: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3729:     } /* End theta */
 3730: 
 3731:     trgradg =matrix(1,nlstate,1,npar);
 3732: 
 3733:     for(j=1; j<=nlstate;j++)
 3734:       for(theta=1; theta <=npar; theta++)
 3735: 	trgradg[j][theta]=gradg[theta][j];
 3736: 
 3737:     for(i=1;i<=nlstate;i++)
 3738:       varpl[i][(int)age] =0.;
 3739:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3740:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3741:     for(i=1;i<=nlstate;i++)
 3742:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3743: 
 3744:     fprintf(ficresvpl,"%.0f ",age );
 3745:     for(i=1; i<=nlstate;i++)
 3746:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3747:     fprintf(ficresvpl,"\n");
 3748:     free_vector(gp,1,nlstate);
 3749:     free_vector(gm,1,nlstate);
 3750:     free_matrix(gradg,1,npar,1,nlstate);
 3751:     free_matrix(trgradg,1,nlstate,1,npar);
 3752:   } /* End age */
 3753: 
 3754:   free_vector(xp,1,npar);
 3755:   free_matrix(doldm,1,nlstate,1,npar);
 3756:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3757: 
 3758: }
 3759: 
 3760: /************ Variance of one-step probabilities  ******************/
 3761: 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[])
 3762: {
 3763:   int i, j=0,  k1, l1, tj;
 3764:   int k2, l2, j1,  z1;
 3765:   int k=0, l;
 3766:   int first=1, first1, first2;
 3767:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3768:   double **dnewm,**doldm;
 3769:   double *xp;
 3770:   double *gp, *gm;
 3771:   double **gradg, **trgradg;
 3772:   double **mu;
 3773:   double age, cov[NCOVMAX+1];
 3774:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3775:   int theta;
 3776:   char fileresprob[FILENAMELENGTH];
 3777:   char fileresprobcov[FILENAMELENGTH];
 3778:   char fileresprobcor[FILENAMELENGTH];
 3779:   double ***varpij;
 3780: 
 3781:   strcpy(fileresprob,"prob"); 
 3782:   strcat(fileresprob,fileres);
 3783:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3784:     printf("Problem with resultfile: %s\n", fileresprob);
 3785:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3786:   }
 3787:   strcpy(fileresprobcov,"probcov"); 
 3788:   strcat(fileresprobcov,fileres);
 3789:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3790:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3791:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3792:   }
 3793:   strcpy(fileresprobcor,"probcor"); 
 3794:   strcat(fileresprobcor,fileres);
 3795:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3796:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3797:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3798:   }
 3799:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3800:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3801:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3802:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3803:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3804:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3805:   pstamp(ficresprob);
 3806:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3807:   fprintf(ficresprob,"# Age");
 3808:   pstamp(ficresprobcov);
 3809:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3810:   fprintf(ficresprobcov,"# Age");
 3811:   pstamp(ficresprobcor);
 3812:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3813:   fprintf(ficresprobcor,"# Age");
 3814: 
 3815: 
 3816:   for(i=1; i<=nlstate;i++)
 3817:     for(j=1; j<=(nlstate+ndeath);j++){
 3818:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3819:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3820:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3821:     }  
 3822:  /* fprintf(ficresprob,"\n");
 3823:   fprintf(ficresprobcov,"\n");
 3824:   fprintf(ficresprobcor,"\n");
 3825:  */
 3826:   xp=vector(1,npar);
 3827:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3828:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3829:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3830:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3831:   first=1;
 3832:   fprintf(ficgp,"\n# Routine varprob");
 3833:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3834:   fprintf(fichtm,"\n");
 3835: 
 3836:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3837:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3838:   file %s<br>\n",optionfilehtmcov);
 3839:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3840: and drawn. It helps understanding how is the covariance between two incidences.\
 3841:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3842:   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. \
 3843: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3844: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3845: standard deviations wide on each axis. <br>\
 3846:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3847:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3848: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3849: 
 3850:   cov[1]=1;
 3851:   /* tj=cptcoveff; */
 3852:   tj = (int) pow(2,cptcoveff);
 3853:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3854:   j1=0;
 3855:   for(j1=1; j1<=tj;j1++){
 3856:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 3857:     /*j1++;*/
 3858:       if  (cptcovn>0) {
 3859: 	fprintf(ficresprob, "\n#********** Variable "); 
 3860: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3861: 	fprintf(ficresprob, "**********\n#\n");
 3862: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3863: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3864: 	fprintf(ficresprobcov, "**********\n#\n");
 3865: 	
 3866: 	fprintf(ficgp, "\n#********** Variable "); 
 3867: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3868: 	fprintf(ficgp, "**********\n#\n");
 3869: 	
 3870: 	
 3871: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3872: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3873: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3874: 	
 3875: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3876: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3877: 	fprintf(ficresprobcor, "**********\n#");    
 3878:       }
 3879:       
 3880:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3881:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3882:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 3883:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 3884:       for (age=bage; age<=fage; age ++){ 
 3885: 	cov[2]=age;
 3886: 	for (k=1; k<=cptcovn;k++) {
 3887: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 3888: 							 * 1  1 1 1 1
 3889: 							 * 2  2 1 1 1
 3890: 							 * 3  1 2 1 1
 3891: 							 */
 3892: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 3893: 	}
 3894: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3895: 	for (k=1; k<=cptcovprod;k++)
 3896: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3897: 	
 3898:     
 3899: 	for(theta=1; theta <=npar; theta++){
 3900: 	  for(i=1; i<=npar; i++)
 3901: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3902: 	  
 3903: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3904: 	  
 3905: 	  k=0;
 3906: 	  for(i=1; i<= (nlstate); i++){
 3907: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3908: 	      k=k+1;
 3909: 	      gp[k]=pmmij[i][j];
 3910: 	    }
 3911: 	  }
 3912: 	  
 3913: 	  for(i=1; i<=npar; i++)
 3914: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3915:     
 3916: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3917: 	  k=0;
 3918: 	  for(i=1; i<=(nlstate); i++){
 3919: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3920: 	      k=k+1;
 3921: 	      gm[k]=pmmij[i][j];
 3922: 	    }
 3923: 	  }
 3924:      
 3925: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3926: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3927: 	}
 3928: 
 3929: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3930: 	  for(theta=1; theta <=npar; theta++)
 3931: 	    trgradg[j][theta]=gradg[theta][j];
 3932: 	
 3933: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3934: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3935: 
 3936: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3937: 	
 3938: 	k=0;
 3939: 	for(i=1; i<=(nlstate); i++){
 3940: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3941: 	    k=k+1;
 3942: 	    mu[k][(int) age]=pmmij[i][j];
 3943: 	  }
 3944: 	}
 3945:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3946: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3947: 	    varpij[i][j][(int)age] = doldm[i][j];
 3948: 
 3949: 	/*printf("\n%d ",(int)age);
 3950: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3951: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3952: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3953: 	  }*/
 3954: 
 3955: 	fprintf(ficresprob,"\n%d ",(int)age);
 3956: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3957: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3958: 
 3959: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3960: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3961: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3962: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3963: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3964: 	}
 3965: 	i=0;
 3966: 	for (k=1; k<=(nlstate);k++){
 3967:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3968:  	    i++;
 3969: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3970: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3971: 	    for (j=1; j<=i;j++){
 3972: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 3973: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3974: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3975: 	    }
 3976: 	  }
 3977: 	}/* end of loop for state */
 3978:       } /* end of loop for age */
 3979:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3980:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3981:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3982:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3983:       
 3984:       /* Confidence intervalle of pij  */
 3985:       /*
 3986: 	fprintf(ficgp,"\nunset parametric;unset label");
 3987: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3988: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3989: 	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);
 3990: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3991: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3992: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3993:       */
 3994: 
 3995:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3996:       first1=1;first2=2;
 3997:       for (k2=1; k2<=(nlstate);k2++){
 3998: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3999: 	  if(l2==k2) continue;
 4000: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4001: 	  for (k1=1; k1<=(nlstate);k1++){
 4002: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4003: 	      if(l1==k1) continue;
 4004: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4005: 	      if(i<=j) continue;
 4006: 	      for (age=bage; age<=fage; age ++){ 
 4007: 		if ((int)age %5==0){
 4008: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4009: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4010: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4011: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4012: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4013: 		  c12=cv12/sqrt(v1*v2);
 4014: 		  /* Computing eigen value of matrix of covariance */
 4015: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4016: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4017: 		  if ((lc2 <0) || (lc1 <0) ){
 4018: 		    if(first2==1){
 4019: 		      first1=0;
 4020: 		    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);
 4021: 		    }
 4022: 		    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);
 4023: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4024: 		    /* lc2=fabs(lc2); */
 4025: 		  }
 4026: 
 4027: 		  /* Eigen vectors */
 4028: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4029: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4030: 		  v21=(lc1-v1)/cv12*v11;
 4031: 		  v12=-v21;
 4032: 		  v22=v11;
 4033: 		  tnalp=v21/v11;
 4034: 		  if(first1==1){
 4035: 		    first1=0;
 4036: 		    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);
 4037: 		  }
 4038: 		  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);
 4039: 		  /*printf(fignu*/
 4040: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4041: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4042: 		  if(first==1){
 4043: 		    first=0;
 4044:  		    fprintf(ficgp,"\nset parametric;unset label");
 4045: 		    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);
 4046: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4047: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4048:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4049: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4050: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4051: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4052: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4053: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4054: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4055: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4056: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4057: 		    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",\
 4058: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4059: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4060: 		  }else{
 4061: 		    first=0;
 4062: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4063: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4064: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4065: 		    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",\
 4066: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4067: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4068: 		  }/* if first */
 4069: 		} /* age mod 5 */
 4070: 	      } /* end loop age */
 4071: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4072: 	      first=1;
 4073: 	    } /*l12 */
 4074: 	  } /* k12 */
 4075: 	} /*l1 */
 4076:       }/* k1 */
 4077:       /* } */ /* loop covariates */
 4078:   }
 4079:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4080:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4081:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4082:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4083:   free_vector(xp,1,npar);
 4084:   fclose(ficresprob);
 4085:   fclose(ficresprobcov);
 4086:   fclose(ficresprobcor);
 4087:   fflush(ficgp);
 4088:   fflush(fichtmcov);
 4089: }
 4090: 
 4091: 
 4092: /******************* Printing html file ***********/
 4093: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4094: 		  int lastpass, int stepm, int weightopt, char model[],\
 4095: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4096: 		  int popforecast, int estepm ,\
 4097: 		  double jprev1, double mprev1,double anprev1, \
 4098: 		  double jprev2, double mprev2,double anprev2){
 4099:   int jj1, k1, i1, cpt;
 4100: 
 4101:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4102:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4103: </ul>");
 4104:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4105:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4106: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4107:    fprintf(fichtm,"\
 4108:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4109: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4110:    fprintf(fichtm,"\
 4111:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4112: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4113:    fprintf(fichtm,"\
 4114:  - (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): \
 4115:    <a href=\"%s\">%s</a> <br>\n",
 4116: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4117:    fprintf(fichtm,"\
 4118:  - Population projections by age and states: \
 4119:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4120: 
 4121: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4122: 
 4123:  m=pow(2,cptcoveff);
 4124:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4125: 
 4126:  jj1=0;
 4127:  for(k1=1; k1<=m;k1++){
 4128:    for(i1=1; i1<=ncodemax[k1];i1++){
 4129:      jj1++;
 4130:      if (cptcovn > 0) {
 4131:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4132:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4133: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4134:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4135:      }
 4136:      /* Pij */
 4137:      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> \
 4138: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4139:      /* Quasi-incidences */
 4140:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4141:  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> \
 4142: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4143:        /* Period (stable) prevalence in each health state */
 4144:        for(cpt=1; cpt<=nlstate;cpt++){
 4145: 	 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> \
 4146: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4147:        }
 4148:      for(cpt=1; cpt<=nlstate;cpt++) {
 4149:         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> \
 4150: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4151:      }
 4152:    } /* end i1 */
 4153:  }/* End k1 */
 4154:  fprintf(fichtm,"</ul>");
 4155: 
 4156: 
 4157:  fprintf(fichtm,"\
 4158: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4159:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4160: 
 4161:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4162: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4163:  fprintf(fichtm,"\
 4164:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4165: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4166: 
 4167:  fprintf(fichtm,"\
 4168:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4169: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4170:  fprintf(fichtm,"\
 4171:  - 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): \
 4172:    <a href=\"%s\">%s</a> <br>\n</li>",
 4173: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4174:  fprintf(fichtm,"\
 4175:  - (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): \
 4176:    <a href=\"%s\">%s</a> <br>\n</li>",
 4177: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4178:  fprintf(fichtm,"\
 4179:  - 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",
 4180: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4181:  fprintf(fichtm,"\
 4182:  - 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",
 4183: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4184:  fprintf(fichtm,"\
 4185:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4186: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4187: 
 4188: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4189: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4190: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4191: /* 	<br>",fileres,fileres,fileres,fileres); */
 4192: /*  else  */
 4193: /*    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); */
 4194:  fflush(fichtm);
 4195:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4196: 
 4197:  m=pow(2,cptcoveff);
 4198:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4199: 
 4200:  jj1=0;
 4201:  for(k1=1; k1<=m;k1++){
 4202:    for(i1=1; i1<=ncodemax[k1];i1++){
 4203:      jj1++;
 4204:      if (cptcovn > 0) {
 4205:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4206:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4207: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4208:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4209:      }
 4210:      for(cpt=1; cpt<=nlstate;cpt++) {
 4211:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4212: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4213: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4214:      }
 4215:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4216: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4217: true period expectancies (those weighted with period prevalences are also\
 4218:  drawn in addition to the population based expectancies computed using\
 4219:  observed and cahotic prevalences: %s%d.png<br>\
 4220: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4221:    } /* end i1 */
 4222:  }/* End k1 */
 4223:  fprintf(fichtm,"</ul>");
 4224:  fflush(fichtm);
 4225: }
 4226: 
 4227: /******************* Gnuplot file **************/
 4228: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4229: 
 4230:   char dirfileres[132],optfileres[132];
 4231:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4232:   int ng=0;
 4233: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4234: /*     printf("Problem with file %s",optionfilegnuplot); */
 4235: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4236: /*   } */
 4237: 
 4238:   /*#ifdef windows */
 4239:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4240:     /*#endif */
 4241:   m=pow(2,cptcoveff);
 4242: 
 4243:   strcpy(dirfileres,optionfilefiname);
 4244:   strcpy(optfileres,"vpl");
 4245:  /* 1eme*/
 4246:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4247:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4248:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4249:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4250:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4251:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4252: set ylabel \"Probability\" \n\
 4253: set ter png small size 320, 240\n\
 4254: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4255: 
 4256:      for (i=1; i<= nlstate ; i ++) {
 4257:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4258:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4259:      }
 4260:      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);
 4261:      for (i=1; i<= nlstate ; i ++) {
 4262:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4263:        else fprintf(ficgp," %%*lf (%%*lf)");
 4264:      } 
 4265:      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); 
 4266:      for (i=1; i<= nlstate ; i ++) {
 4267:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4268:        else fprintf(ficgp," %%*lf (%%*lf)");
 4269:      }  
 4270:      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));
 4271:    }
 4272:   }
 4273:   /*2 eme*/
 4274:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4275:   for (k1=1; k1<= m ; k1 ++) { 
 4276:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4277:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4278:     
 4279:     for (i=1; i<= nlstate+1 ; i ++) {
 4280:       k=2*i;
 4281:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4282:       for (j=1; j<= nlstate+1 ; j ++) {
 4283: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4284: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4285:       }   
 4286:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4287:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4288:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4289:       for (j=1; j<= nlstate+1 ; j ++) {
 4290: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4291: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4292:       }   
 4293:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4294:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4295:       for (j=1; j<= nlstate+1 ; j ++) {
 4296: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4297: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4298:       }   
 4299:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4300:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4301:     }
 4302:   }
 4303:   
 4304:   /*3eme*/
 4305:   
 4306:   for (k1=1; k1<= m ; k1 ++) { 
 4307:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4308:       /*       k=2+nlstate*(2*cpt-2); */
 4309:       k=2+(nlstate+1)*(cpt-1);
 4310:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4311:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4312: 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);
 4313:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4314: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4315: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4316: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4317: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4318: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4319: 	
 4320:       */
 4321:       for (i=1; i< nlstate ; i ++) {
 4322: 	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);
 4323: 	/*	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);*/
 4324: 	
 4325:       } 
 4326:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4327:     }
 4328:   }
 4329:   
 4330:   /* CV preval stable (period) */
 4331:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4332:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4333:       k=3;
 4334:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4335:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4336:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4337: set ter png small size 320, 240\n\
 4338: unset log y\n\
 4339: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4340:       for (i=1; i<= nlstate ; i ++){
 4341: 	if(i==1)
 4342: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4343: 	else
 4344: 	  fprintf(ficgp,", '' ");
 4345: 	l=(nlstate+ndeath)*(i-1)+1;
 4346: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4347: 	for (j=1; j<= (nlstate-1) ; j ++)
 4348: 	  fprintf(ficgp,"+$%d",k+l+j);
 4349: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4350:       } /* nlstate */
 4351:       fprintf(ficgp,"\n");
 4352:     } /* end cpt state*/ 
 4353:   } /* end covariate */  
 4354:   
 4355:   /* proba elementaires */
 4356:   for(i=1,jk=1; i <=nlstate; i++){
 4357:     for(k=1; k <=(nlstate+ndeath); k++){
 4358:       if (k != i) {
 4359: 	for(j=1; j <=ncovmodel; j++){
 4360: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4361: 	  jk++; 
 4362: 	  fprintf(ficgp,"\n");
 4363: 	}
 4364:       }
 4365:     }
 4366:    }
 4367:   /*goto avoid;*/
 4368:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4369:      for(jk=1; jk <=m; jk++) {
 4370:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4371:        if (ng==2)
 4372: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4373:        else
 4374: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4375:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4376:        i=1;
 4377:        for(k2=1; k2<=nlstate; k2++) {
 4378: 	 k3=i;
 4379: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4380: 	   if (k != k2){
 4381: 	     if(ng==2)
 4382: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4383: 	     else
 4384: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4385: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4386: 	     for(j=3; j <=ncovmodel; j++) {
 4387: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4388: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4389: 	       /* 	 ij++; */
 4390: 	       /* } */
 4391: 	       /* else */
 4392: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4393: 	     }
 4394: 	     fprintf(ficgp,")/(1");
 4395: 	     
 4396: 	     for(k1=1; k1 <=nlstate; k1++){   
 4397: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4398: 	       ij=1;
 4399: 	       for(j=3; j <=ncovmodel; j++){
 4400: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4401: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4402: 		 /*   ij++; */
 4403: 		 /* } */
 4404: 		 /* else */
 4405: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4406: 	       }
 4407: 	       fprintf(ficgp,")");
 4408: 	     }
 4409: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4410: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4411: 	     i=i+ncovmodel;
 4412: 	   }
 4413: 	 } /* end k */
 4414:        } /* end k2 */
 4415:      } /* end jk */
 4416:    } /* end ng */
 4417:  /* avoid: */
 4418:    fflush(ficgp); 
 4419: }  /* end gnuplot */
 4420: 
 4421: 
 4422: /*************** Moving average **************/
 4423: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4424: 
 4425:   int i, cpt, cptcod;
 4426:   int modcovmax =1;
 4427:   int mobilavrange, mob;
 4428:   double age;
 4429: 
 4430:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4431: 			   a covariate has 2 modalities */
 4432:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4433: 
 4434:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4435:     if(mobilav==1) mobilavrange=5; /* default */
 4436:     else mobilavrange=mobilav;
 4437:     for (age=bage; age<=fage; age++)
 4438:       for (i=1; i<=nlstate;i++)
 4439: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4440: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4441:     /* We keep the original values on the extreme ages bage, fage and for 
 4442:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4443:        we use a 5 terms etc. until the borders are no more concerned. 
 4444:     */ 
 4445:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4446:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4447: 	for (i=1; i<=nlstate;i++){
 4448: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4449: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4450: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4451: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4452: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4453: 	      }
 4454: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4455: 	  }
 4456: 	}
 4457:       }/* end age */
 4458:     }/* end mob */
 4459:   }else return -1;
 4460:   return 0;
 4461: }/* End movingaverage */
 4462: 
 4463: 
 4464: /************** Forecasting ******************/
 4465: 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){
 4466:   /* proj1, year, month, day of starting projection 
 4467:      agemin, agemax range of age
 4468:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4469:      anproj2 year of en of projection (same day and month as proj1).
 4470:   */
 4471:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4472:   double agec; /* generic age */
 4473:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4474:   double *popeffectif,*popcount;
 4475:   double ***p3mat;
 4476:   double ***mobaverage;
 4477:   char fileresf[FILENAMELENGTH];
 4478: 
 4479:   agelim=AGESUP;
 4480:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4481:  
 4482:   strcpy(fileresf,"f"); 
 4483:   strcat(fileresf,fileres);
 4484:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4485:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4486:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4487:   }
 4488:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4489:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4490: 
 4491:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4492: 
 4493:   if (mobilav!=0) {
 4494:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4495:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4496:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4497:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4498:     }
 4499:   }
 4500: 
 4501:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4502:   if (stepm<=12) stepsize=1;
 4503:   if(estepm < stepm){
 4504:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4505:   }
 4506:   else  hstepm=estepm;   
 4507: 
 4508:   hstepm=hstepm/stepm; 
 4509:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4510:                                fractional in yp1 */
 4511:   anprojmean=yp;
 4512:   yp2=modf((yp1*12),&yp);
 4513:   mprojmean=yp;
 4514:   yp1=modf((yp2*30.5),&yp);
 4515:   jprojmean=yp;
 4516:   if(jprojmean==0) jprojmean=1;
 4517:   if(mprojmean==0) jprojmean=1;
 4518: 
 4519:   i1=cptcoveff;
 4520:   if (cptcovn < 1){i1=1;}
 4521:   
 4522:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4523:   
 4524:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4525: 
 4526: /* 	      if (h==(int)(YEARM*yearp)){ */
 4527:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4528:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4529:       k=k+1;
 4530:       fprintf(ficresf,"\n#******");
 4531:       for(j=1;j<=cptcoveff;j++) {
 4532: 	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]]);
 4533:       }
 4534:       fprintf(ficresf,"******\n");
 4535:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4536:       for(j=1; j<=nlstate+ndeath;j++){ 
 4537: 	for(i=1; i<=nlstate;i++) 	      
 4538:           fprintf(ficresf," p%d%d",i,j);
 4539: 	fprintf(ficresf," p.%d",j);
 4540:       }
 4541:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4542: 	fprintf(ficresf,"\n");
 4543: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4544: 
 4545:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4546: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4547: 	  nhstepm = nhstepm/hstepm; 
 4548: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4549: 	  oldm=oldms;savm=savms;
 4550: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4551: 	
 4552: 	  for (h=0; h<=nhstepm; h++){
 4553: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4554:               fprintf(ficresf,"\n");
 4555:               for(j=1;j<=cptcoveff;j++) 
 4556:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4557: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4558: 	    } 
 4559: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4560: 	      ppij=0.;
 4561: 	      for(i=1; i<=nlstate;i++) {
 4562: 		if (mobilav==1) 
 4563: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4564: 		else {
 4565: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4566: 		}
 4567: 		if (h*hstepm/YEARM*stepm== yearp) {
 4568: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4569: 		}
 4570: 	      } /* end i */
 4571: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4572: 		fprintf(ficresf," %.3f", ppij);
 4573: 	      }
 4574: 	    }/* end j */
 4575: 	  } /* end h */
 4576: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4577: 	} /* end agec */
 4578:       } /* end yearp */
 4579:     } /* end cptcod */
 4580:   } /* end  cptcov */
 4581:        
 4582:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4583: 
 4584:   fclose(ficresf);
 4585: }
 4586: 
 4587: /************** Forecasting *****not tested NB*************/
 4588: 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){
 4589:   
 4590:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4591:   int *popage;
 4592:   double calagedatem, agelim, kk1, kk2;
 4593:   double *popeffectif,*popcount;
 4594:   double ***p3mat,***tabpop,***tabpopprev;
 4595:   double ***mobaverage;
 4596:   char filerespop[FILENAMELENGTH];
 4597: 
 4598:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4599:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4600:   agelim=AGESUP;
 4601:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4602:   
 4603:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4604:   
 4605:   
 4606:   strcpy(filerespop,"pop"); 
 4607:   strcat(filerespop,fileres);
 4608:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4609:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4610:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4611:   }
 4612:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4613:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4614: 
 4615:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4616: 
 4617:   if (mobilav!=0) {
 4618:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4619:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4620:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4621:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4622:     }
 4623:   }
 4624: 
 4625:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4626:   if (stepm<=12) stepsize=1;
 4627:   
 4628:   agelim=AGESUP;
 4629:   
 4630:   hstepm=1;
 4631:   hstepm=hstepm/stepm; 
 4632:   
 4633:   if (popforecast==1) {
 4634:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4635:       printf("Problem with population file : %s\n",popfile);exit(0);
 4636:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4637:     } 
 4638:     popage=ivector(0,AGESUP);
 4639:     popeffectif=vector(0,AGESUP);
 4640:     popcount=vector(0,AGESUP);
 4641:     
 4642:     i=1;   
 4643:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4644:    
 4645:     imx=i;
 4646:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4647:   }
 4648: 
 4649:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4650:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4651:       k=k+1;
 4652:       fprintf(ficrespop,"\n#******");
 4653:       for(j=1;j<=cptcoveff;j++) {
 4654: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4655:       }
 4656:       fprintf(ficrespop,"******\n");
 4657:       fprintf(ficrespop,"# Age");
 4658:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4659:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4660:       
 4661:       for (cpt=0; cpt<=0;cpt++) { 
 4662: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4663: 	
 4664:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4665: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4666: 	  nhstepm = nhstepm/hstepm; 
 4667: 	  
 4668: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4669: 	  oldm=oldms;savm=savms;
 4670: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4671: 	
 4672: 	  for (h=0; h<=nhstepm; h++){
 4673: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4674: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4675: 	    } 
 4676: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4677: 	      kk1=0.;kk2=0;
 4678: 	      for(i=1; i<=nlstate;i++) {	      
 4679: 		if (mobilav==1) 
 4680: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4681: 		else {
 4682: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4683: 		}
 4684: 	      }
 4685: 	      if (h==(int)(calagedatem+12*cpt)){
 4686: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4687: 		  /*fprintf(ficrespop," %.3f", kk1);
 4688: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4689: 	      }
 4690: 	    }
 4691: 	    for(i=1; i<=nlstate;i++){
 4692: 	      kk1=0.;
 4693: 		for(j=1; j<=nlstate;j++){
 4694: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4695: 		}
 4696: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4697: 	    }
 4698: 
 4699: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4700: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4701: 	  }
 4702: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4703: 	}
 4704:       }
 4705:  
 4706:   /******/
 4707: 
 4708:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4709: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4710: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4711: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4712: 	  nhstepm = nhstepm/hstepm; 
 4713: 	  
 4714: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4715: 	  oldm=oldms;savm=savms;
 4716: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4717: 	  for (h=0; h<=nhstepm; h++){
 4718: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4719: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4720: 	    } 
 4721: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4722: 	      kk1=0.;kk2=0;
 4723: 	      for(i=1; i<=nlstate;i++) {	      
 4724: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4725: 	      }
 4726: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4727: 	    }
 4728: 	  }
 4729: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4730: 	}
 4731:       }
 4732:    } 
 4733:   }
 4734:  
 4735:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4736: 
 4737:   if (popforecast==1) {
 4738:     free_ivector(popage,0,AGESUP);
 4739:     free_vector(popeffectif,0,AGESUP);
 4740:     free_vector(popcount,0,AGESUP);
 4741:   }
 4742:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4743:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4744:   fclose(ficrespop);
 4745: } /* End of popforecast */
 4746: 
 4747: int fileappend(FILE *fichier, char *optionfich)
 4748: {
 4749:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4750:     printf("Problem with file: %s\n", optionfich);
 4751:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4752:     return (0);
 4753:   }
 4754:   fflush(fichier);
 4755:   return (1);
 4756: }
 4757: 
 4758: 
 4759: /**************** function prwizard **********************/
 4760: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4761: {
 4762: 
 4763:   /* Wizard to print covariance matrix template */
 4764: 
 4765:   char ca[32], cb[32];
 4766:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4767:   int numlinepar;
 4768: 
 4769:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4770:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4771:   for(i=1; i <=nlstate; i++){
 4772:     jj=0;
 4773:     for(j=1; j <=nlstate+ndeath; j++){
 4774:       if(j==i) continue;
 4775:       jj++;
 4776:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4777:       printf("%1d%1d",i,j);
 4778:       fprintf(ficparo,"%1d%1d",i,j);
 4779:       for(k=1; k<=ncovmodel;k++){
 4780: 	/* 	  printf(" %lf",param[i][j][k]); */
 4781: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4782: 	printf(" 0.");
 4783: 	fprintf(ficparo," 0.");
 4784:       }
 4785:       printf("\n");
 4786:       fprintf(ficparo,"\n");
 4787:     }
 4788:   }
 4789:   printf("# Scales (for hessian or gradient estimation)\n");
 4790:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4791:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4792:   for(i=1; i <=nlstate; i++){
 4793:     jj=0;
 4794:     for(j=1; j <=nlstate+ndeath; j++){
 4795:       if(j==i) continue;
 4796:       jj++;
 4797:       fprintf(ficparo,"%1d%1d",i,j);
 4798:       printf("%1d%1d",i,j);
 4799:       fflush(stdout);
 4800:       for(k=1; k<=ncovmodel;k++){
 4801: 	/* 	printf(" %le",delti3[i][j][k]); */
 4802: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4803: 	printf(" 0.");
 4804: 	fprintf(ficparo," 0.");
 4805:       }
 4806:       numlinepar++;
 4807:       printf("\n");
 4808:       fprintf(ficparo,"\n");
 4809:     }
 4810:   }
 4811:   printf("# Covariance matrix\n");
 4812: /* # 121 Var(a12)\n\ */
 4813: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4814: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4815: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4816: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4817: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4818: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4819: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4820:   fflush(stdout);
 4821:   fprintf(ficparo,"# Covariance matrix\n");
 4822:   /* # 121 Var(a12)\n\ */
 4823:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4824:   /* #   ...\n\ */
 4825:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4826:   
 4827:   for(itimes=1;itimes<=2;itimes++){
 4828:     jj=0;
 4829:     for(i=1; i <=nlstate; i++){
 4830:       for(j=1; j <=nlstate+ndeath; j++){
 4831: 	if(j==i) continue;
 4832: 	for(k=1; k<=ncovmodel;k++){
 4833: 	  jj++;
 4834: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4835: 	  if(itimes==1){
 4836: 	    printf("#%1d%1d%d",i,j,k);
 4837: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4838: 	  }else{
 4839: 	    printf("%1d%1d%d",i,j,k);
 4840: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4841: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4842: 	  }
 4843: 	  ll=0;
 4844: 	  for(li=1;li <=nlstate; li++){
 4845: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4846: 	      if(lj==li) continue;
 4847: 	      for(lk=1;lk<=ncovmodel;lk++){
 4848: 		ll++;
 4849: 		if(ll<=jj){
 4850: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4851: 		  if(ll<jj){
 4852: 		    if(itimes==1){
 4853: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4854: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4855: 		    }else{
 4856: 		      printf(" 0.");
 4857: 		      fprintf(ficparo," 0.");
 4858: 		    }
 4859: 		  }else{
 4860: 		    if(itimes==1){
 4861: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4862: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4863: 		    }else{
 4864: 		      printf(" 0.");
 4865: 		      fprintf(ficparo," 0.");
 4866: 		    }
 4867: 		  }
 4868: 		}
 4869: 	      } /* end lk */
 4870: 	    } /* end lj */
 4871: 	  } /* end li */
 4872: 	  printf("\n");
 4873: 	  fprintf(ficparo,"\n");
 4874: 	  numlinepar++;
 4875: 	} /* end k*/
 4876:       } /*end j */
 4877:     } /* end i */
 4878:   } /* end itimes */
 4879: 
 4880: } /* end of prwizard */
 4881: /******************* Gompertz Likelihood ******************************/
 4882: double gompertz(double x[])
 4883: { 
 4884:   double A,B,L=0.0,sump=0.,num=0.;
 4885:   int i,n=0; /* n is the size of the sample */
 4886: 
 4887:   for (i=0;i<=imx-1 ; i++) {
 4888:     sump=sump+weight[i];
 4889:     /*    sump=sump+1;*/
 4890:     num=num+1;
 4891:   }
 4892:  
 4893:  
 4894:   /* for (i=0; i<=imx; i++) 
 4895:      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]);*/
 4896: 
 4897:   for (i=1;i<=imx ; i++)
 4898:     {
 4899:       if (cens[i] == 1 && wav[i]>1)
 4900: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4901:       
 4902:       if (cens[i] == 0 && wav[i]>1)
 4903: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4904: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4905:       
 4906:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4907:       if (wav[i] > 1 ) { /* ??? */
 4908: 	L=L+A*weight[i];
 4909: 	/* 	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]);*/
 4910:       }
 4911:     }
 4912: 
 4913:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4914:  
 4915:   return -2*L*num/sump;
 4916: }
 4917: 
 4918: #ifdef GSL
 4919: /******************* Gompertz_f Likelihood ******************************/
 4920: double gompertz_f(const gsl_vector *v, void *params)
 4921: { 
 4922:   double A,B,LL=0.0,sump=0.,num=0.;
 4923:   double *x= (double *) v->data;
 4924:   int i,n=0; /* n is the size of the sample */
 4925: 
 4926:   for (i=0;i<=imx-1 ; i++) {
 4927:     sump=sump+weight[i];
 4928:     /*    sump=sump+1;*/
 4929:     num=num+1;
 4930:   }
 4931:  
 4932:  
 4933:   /* for (i=0; i<=imx; i++) 
 4934:      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]);*/
 4935:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4936:   for (i=1;i<=imx ; i++)
 4937:     {
 4938:       if (cens[i] == 1 && wav[i]>1)
 4939: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4940:       
 4941:       if (cens[i] == 0 && wav[i]>1)
 4942: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4943: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4944:       
 4945:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4946:       if (wav[i] > 1 ) { /* ??? */
 4947: 	LL=LL+A*weight[i];
 4948: 	/* 	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]);*/
 4949:       }
 4950:     }
 4951: 
 4952:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4953:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4954:  
 4955:   return -2*LL*num/sump;
 4956: }
 4957: #endif
 4958: 
 4959: /******************* Printing html file ***********/
 4960: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4961: 		  int lastpass, int stepm, int weightopt, char model[],\
 4962: 		  int imx,  double p[],double **matcov,double agemortsup){
 4963:   int i,k;
 4964: 
 4965:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4966:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4967:   for (i=1;i<=2;i++) 
 4968:     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]));
 4969:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4970:   fprintf(fichtm,"</ul>");
 4971: 
 4972: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4973: 
 4974:  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>");
 4975: 
 4976:  for (k=agegomp;k<(agemortsup-2);k++) 
 4977:    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]);
 4978: 
 4979:  
 4980:   fflush(fichtm);
 4981: }
 4982: 
 4983: /******************* Gnuplot file **************/
 4984: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4985: 
 4986:   char dirfileres[132],optfileres[132];
 4987: 
 4988:   int ng;
 4989: 
 4990: 
 4991:   /*#ifdef windows */
 4992:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4993:     /*#endif */
 4994: 
 4995: 
 4996:   strcpy(dirfileres,optionfilefiname);
 4997:   strcpy(optfileres,"vpl");
 4998:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4999:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5000:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5001:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5002:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5003: 
 5004: } 
 5005: 
 5006: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5007: {
 5008: 
 5009:   /*-------- data file ----------*/
 5010:   FILE *fic;
 5011:   char dummy[]="                         ";
 5012:   int i=0, j=0, n=0;
 5013:   int linei, month, year,iout;
 5014:   char line[MAXLINE], linetmp[MAXLINE];
 5015:   char stra[MAXLINE], strb[MAXLINE];
 5016:   char *stratrunc;
 5017:   int lstra;
 5018: 
 5019: 
 5020:   if((fic=fopen(datafile,"r"))==NULL)    {
 5021:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5022:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5023:   }
 5024: 
 5025:   i=1;
 5026:   linei=0;
 5027:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5028:     linei=linei+1;
 5029:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5030:       if(line[j] == '\t')
 5031: 	line[j] = ' ';
 5032:     }
 5033:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5034:       ;
 5035:     };
 5036:     line[j+1]=0;  /* Trims blanks at end of line */
 5037:     if(line[0]=='#'){
 5038:       fprintf(ficlog,"Comment line\n%s\n",line);
 5039:       printf("Comment line\n%s\n",line);
 5040:       continue;
 5041:     }
 5042:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5043:     strcpy(line, linetmp);
 5044:   
 5045: 
 5046:     for (j=maxwav;j>=1;j--){
 5047:       cutv(stra, strb, line, ' '); 
 5048:       if(strb[0]=='.') { /* Missing status */
 5049: 	lval=-1;
 5050:       }else{
 5051: 	errno=0;
 5052: 	lval=strtol(strb,&endptr,10); 
 5053:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5054: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5055: 	  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);
 5056: 	  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);
 5057: 	  return 1;
 5058: 	}
 5059:       }
 5060:       s[j][i]=lval;
 5061:       
 5062:       strcpy(line,stra);
 5063:       cutv(stra, strb,line,' ');
 5064:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5065:       }
 5066:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5067: 	month=99;
 5068: 	year=9999;
 5069:       }else{
 5070: 	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);
 5071: 	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);
 5072: 	return 1;
 5073:       }
 5074:       anint[j][i]= (double) year; 
 5075:       mint[j][i]= (double)month; 
 5076:       strcpy(line,stra);
 5077:     } /* ENd Waves */
 5078:     
 5079:     cutv(stra, strb,line,' '); 
 5080:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5081:     }
 5082:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5083:       month=99;
 5084:       year=9999;
 5085:     }else{
 5086:       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);
 5087: 	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);
 5088: 	return 1;
 5089:     }
 5090:     andc[i]=(double) year; 
 5091:     moisdc[i]=(double) month; 
 5092:     strcpy(line,stra);
 5093:     
 5094:     cutv(stra, strb,line,' '); 
 5095:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5096:     }
 5097:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5098:       month=99;
 5099:       year=9999;
 5100:     }else{
 5101:       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);
 5102:       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);
 5103: 	return 1;
 5104:     }
 5105:     if (year==9999) {
 5106:       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);
 5107:       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);
 5108: 	return 1;
 5109: 
 5110:     }
 5111:     annais[i]=(double)(year);
 5112:     moisnais[i]=(double)(month); 
 5113:     strcpy(line,stra);
 5114:     
 5115:     cutv(stra, strb,line,' '); 
 5116:     errno=0;
 5117:     dval=strtod(strb,&endptr); 
 5118:     if( strb[0]=='\0' || (*endptr != '\0')){
 5119:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5120:       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);
 5121:       fflush(ficlog);
 5122:       return 1;
 5123:     }
 5124:     weight[i]=dval; 
 5125:     strcpy(line,stra);
 5126:     
 5127:     for (j=ncovcol;j>=1;j--){
 5128:       cutv(stra, strb,line,' '); 
 5129:       if(strb[0]=='.') { /* Missing status */
 5130: 	lval=-1;
 5131:       }else{
 5132: 	errno=0;
 5133: 	lval=strtol(strb,&endptr,10); 
 5134: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5135: 	  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);
 5136: 	  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);
 5137: 	  return 1;
 5138: 	}
 5139:       }
 5140:       if(lval <-1 || lval >1){
 5141: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5142:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5143:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5144:  For example, for multinomial values like 1, 2 and 3,\n \
 5145:  build V1=0 V2=0 for the reference value (1),\n \
 5146:         V1=1 V2=0 for (2) \n \
 5147:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5148:  output of IMaCh is often meaningless.\n \
 5149:  Exiting.\n",lval,linei, i,line,j);
 5150: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5151:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5152:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5153:  For example, for multinomial values like 1, 2 and 3,\n \
 5154:  build V1=0 V2=0 for the reference value (1),\n \
 5155:         V1=1 V2=0 for (2) \n \
 5156:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5157:  output of IMaCh is often meaningless.\n \
 5158:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5159: 	return 1;
 5160:       }
 5161:       covar[j][i]=(double)(lval);
 5162:       strcpy(line,stra);
 5163:     }  
 5164:     lstra=strlen(stra);
 5165:      
 5166:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5167:       stratrunc = &(stra[lstra-9]);
 5168:       num[i]=atol(stratrunc);
 5169:     }
 5170:     else
 5171:       num[i]=atol(stra);
 5172:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5173:       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;}*/
 5174:     
 5175:     i=i+1;
 5176:   } /* End loop reading  data */
 5177: 
 5178:   *imax=i-1; /* Number of individuals */
 5179:   fclose(fic);
 5180:  
 5181:   return (0);
 5182:   /* endread: */
 5183:     printf("Exiting readdata: ");
 5184:     fclose(fic);
 5185:     return (1);
 5186: 
 5187: 
 5188: 
 5189: }
 5190: void removespace(char *str) {
 5191:   char *p1 = str, *p2 = str;
 5192:   do
 5193:     while (*p2 == ' ')
 5194:       p2++;
 5195:   while (*p1++ == *p2++);
 5196: }
 5197: 
 5198: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5199:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5200:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5201:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5202:    * - cptcovage number of covariates with age*products =2
 5203:    * - cptcovs number of simple covariates
 5204:    * - 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
 5205:    *     which is a new column after the 9 (ncovcol) variables. 
 5206:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5207:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5208:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5209:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5210:  */
 5211: {
 5212:   int i, j, k, ks;
 5213:   int  j1, k1, k2;
 5214:   char modelsav[80];
 5215:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5216: 
 5217:   /*removespace(model);*/
 5218:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5219:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5220:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5221:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5222:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5223:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5224:                   /* including age products which are counted in cptcovage.
 5225: 		  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5226:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5227:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5228:     strcpy(modelsav,model); 
 5229:     if (strstr(model,"AGE") !=0){
 5230:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5231:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5232:       return 1;
 5233:     }
 5234:     if (strstr(model,"v") !=0){
 5235:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5236:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5237:       return 1;
 5238:     }
 5239:     
 5240:     /*   Design
 5241:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5242:      *  <          ncovcol=8                >
 5243:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5244:      *   k=  1    2      3       4     5       6      7        8
 5245:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5246:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5247:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5248:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5249:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5250:      *  Tage[++cptcovage]=k
 5251:      *       if products, new covar are created after ncovcol with k1
 5252:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5253:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5254:      *  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
 5255:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5256:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5257:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5258:      *  <          ncovcol=8                >
 5259:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5260:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5261:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5262:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5263:      * p Tprod[1]@2={                         6, 5}
 5264:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5265:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5266:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5267:      *How to reorganize?
 5268:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5269:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5270:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5271:      * Struct []
 5272:      */
 5273: 
 5274:     /* This loop fills the array Tvar from the string 'model'.*/
 5275:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5276:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5277:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5278:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5279:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5280:     /* 	k=1 Tvar[1]=2 (from V2) */
 5281:     /* 	k=5 Tvar[5] */
 5282:     /* for (k=1; k<=cptcovn;k++) { */
 5283:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5284:     /* 	} */
 5285:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5286:     /*
 5287:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5288:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5289:         Tvar[k]=0;
 5290:     cptcovage=0;
 5291:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5292:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5293: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5294:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5295:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5296:       /*scanf("%d",i);*/
 5297:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5298: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5299: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5300: 	  /* covar is not filled and then is empty */
 5301: 	  cptcovprod--;
 5302: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5303: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5304: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5305: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5306: 	  /*printf("stre=%s ", stre);*/
 5307: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5308: 	  cptcovprod--;
 5309: 	  cutl(stre,strb,strc,'V');
 5310: 	  Tvar[k]=atoi(stre);
 5311: 	  cptcovage++;
 5312: 	  Tage[cptcovage]=k;
 5313: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5314: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5315: 	  cptcovn++;
 5316: 	  cptcovprodnoage++;k1++;
 5317: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5318: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5319: 				  because this model-covariate is a construction we invent a new column
 5320: 				  ncovcol + k1
 5321: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5322: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5323: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5324: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5325: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5326: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5327: 	  k2=k2+2;
 5328: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5329: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5330: 	  for (i=1; i<=lastobs;i++){
 5331: 	    /* Computes the new covariate which is a product of
 5332: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5333: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5334: 	  }
 5335: 	} /* End age is not in the model */
 5336:       } /* End if model includes a product */
 5337:       else { /* no more sum */
 5338: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5339:        /*  scanf("%d",i);*/
 5340: 	cutl(strd,strc,strb,'V');
 5341: 	ks++; /**< Number of simple covariates */
 5342: 	cptcovn++;
 5343: 	Tvar[k]=atoi(strd);
 5344:       }
 5345:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5346:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5347: 	scanf("%d",i);*/
 5348:     } /* end of loop + */
 5349:   } /* end model */
 5350:   
 5351:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5352:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5353: 
 5354:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5355:   printf("cptcovprod=%d ", cptcovprod);
 5356:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5357: 
 5358:   scanf("%d ",i);*/
 5359: 
 5360: 
 5361:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5362:   /*endread:*/
 5363:     printf("Exiting decodemodel: ");
 5364:     return (1);
 5365: }
 5366: 
 5367: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5368: {
 5369:   int i, m;
 5370: 
 5371:   for (i=1; i<=imx; i++) {
 5372:     for(m=2; (m<= maxwav); m++) {
 5373:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5374: 	anint[m][i]=9999;
 5375: 	s[m][i]=-1;
 5376:       }
 5377:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5378: 	*nberr = *nberr + 1;
 5379: 	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);
 5380: 	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);
 5381: 	s[m][i]=-1;
 5382:       }
 5383:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5384: 	(*nberr)++;
 5385: 	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]); 
 5386: 	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]); 
 5387: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5388:       }
 5389:     }
 5390:   }
 5391: 
 5392:   for (i=1; i<=imx; i++)  {
 5393:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5394:     for(m=firstpass; (m<= lastpass); m++){
 5395:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5396: 	if (s[m][i] >= nlstate+1) {
 5397: 	  if(agedc[i]>0){
 5398: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5399: 	      agev[m][i]=agedc[i];
 5400: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5401: 	    }else {
 5402: 	      if ((int)andc[i]!=9999){
 5403: 		nbwarn++;
 5404: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5405: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5406: 		agev[m][i]=-1;
 5407: 	      }
 5408: 	    }
 5409: 	  } /* agedc > 0 */
 5410: 	}
 5411: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5412: 				 years but with the precision of a month */
 5413: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5414: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5415: 	    agev[m][i]=1;
 5416: 	  else if(agev[m][i] < *agemin){ 
 5417: 	    *agemin=agev[m][i];
 5418: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5419: 	  }
 5420: 	  else if(agev[m][i] >*agemax){
 5421: 	    *agemax=agev[m][i];
 5422: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5423: 	  }
 5424: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5425: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5426: 	}
 5427: 	else { /* =9 */
 5428: 	  agev[m][i]=1;
 5429: 	  s[m][i]=-1;
 5430: 	}
 5431:       }
 5432:       else /*= 0 Unknown */
 5433: 	agev[m][i]=1;
 5434:     }
 5435:     
 5436:   }
 5437:   for (i=1; i<=imx; i++)  {
 5438:     for(m=firstpass; (m<=lastpass); m++){
 5439:       if (s[m][i] > (nlstate+ndeath)) {
 5440: 	(*nberr)++;
 5441: 	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);	
 5442: 	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);	
 5443: 	return 1;
 5444:       }
 5445:     }
 5446:   }
 5447: 
 5448:   /*for (i=1; i<=imx; i++){
 5449:   for (m=firstpass; (m<lastpass); m++){
 5450:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5451: }
 5452: 
 5453: }*/
 5454: 
 5455: 
 5456:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5457:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5458: 
 5459:   return (0);
 5460:  /* endread:*/
 5461:     printf("Exiting calandcheckages: ");
 5462:     return (1);
 5463: }
 5464: 
 5465: #if defined(_MSC_VER)
 5466: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5467: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5468: //#include "stdafx.h"
 5469: //#include <stdio.h>
 5470: //#include <tchar.h>
 5471: //#include <windows.h>
 5472: //#include <iostream>
 5473: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5474: 
 5475: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5476: 
 5477: BOOL IsWow64()
 5478: {
 5479: 	BOOL bIsWow64 = FALSE;
 5480: 
 5481: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5482: 	//  (HANDLE, PBOOL);
 5483: 
 5484: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5485: 
 5486: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5487: 	const char funcName[] = "IsWow64Process";
 5488: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5489: 		GetProcAddress(module, funcName);
 5490: 
 5491: 	if (NULL != fnIsWow64Process)
 5492: 	{
 5493: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5494: 			&bIsWow64))
 5495: 			//throw std::exception("Unknown error");
 5496: 			printf("Unknown error\n");
 5497: 	}
 5498: 	return bIsWow64 != FALSE;
 5499: }
 5500: #endif
 5501: void syscompilerinfo()
 5502:  {
 5503:    /* #include "syscompilerinfo.h"*/
 5504: #if defined(__GNUC__) 
 5505: #include <gnu/libc-version.h>  /* Only on gnu */
 5506: #endif
 5507: 
 5508: #include <stdint.h>
 5509:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5510: #if defined(__clang__)
 5511:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5512: #endif
 5513: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5514:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5515: #endif
 5516: #if defined(__GNUC__) || defined(__GNUG__)
 5517:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5518: #endif
 5519: #if defined(__HP_cc) || defined(__HP_aCC)
 5520:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5521: #endif
 5522: #if defined(__IBMC__) || defined(__IBMCPP__)
 5523:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5524: #endif
 5525: #if defined(_MSC_VER)
 5526:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5527: #endif
 5528: #if defined(__PGI)
 5529:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5530: #endif
 5531: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5532:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5533: #endif
 5534:    printf(" for ");fprintf(ficlog," for ");
 5535:    
 5536: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5537: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5538:     // Windows (x64 and x86)
 5539:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
 5540: #elif __unix__ // all unices, not all compilers
 5541:     // Unix
 5542:    printf("Unix ");fprintf(ficlog,"Unix ");
 5543: #elif __linux__
 5544:     // linux
 5545:    printf("linux ");fprintf(ficlog,"linux ");
 5546: #elif __APPLE__
 5547:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 5548:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
 5549: #endif
 5550: 
 5551: /*  __MINGW32__	  */
 5552: /*  __CYGWIN__	 */
 5553: /* __MINGW64__  */
 5554: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5555: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5556: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5557: /* _WIN64  // Defined for applications for Win64. */
 5558: /* _M_X64 // Defined for compilations that target x64 processors. */
 5559: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5560: 
 5561: #if UINTPTR_MAX == 0xffffffff
 5562:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
 5563: #elif UINTPTR_MAX == 0xffffffffffffffff
 5564:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
 5565: #else
 5566:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
 5567: #endif
 5568: 
 5569: /* struct utsname sysInfo;
 5570: 
 5571:    if (uname(&sysInfo) != -1) {
 5572:      printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5573:      fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5574:    }
 5575:    else
 5576:       perror("uname() error");
 5577: 	  */
 5578: #if defined(__GNUC__)
 5579: # if defined(__GNUC_PATCHLEVEL__)
 5580: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5581:                             + __GNUC_MINOR__ * 100 \
 5582:                             + __GNUC_PATCHLEVEL__)
 5583: # else
 5584: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5585:                             + __GNUC_MINOR__ * 100)
 5586: # endif
 5587:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 5588:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 5589:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 5590:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version()); 
 5591: 
 5592: #endif
 5593: 
 5594:    //   void main()
 5595:    //   {
 5596: #if defined(_MSC_VER)
 5597:    if (IsWow64()){
 5598: 	   printf("The program (probably compile for 32bit) is running under WOW64 (64bit) emulation.\n");
 5599: 	   fprintf(ficlog, "The program (ie 32bit) is running under WOW64 (64bit) emulation.\n");
 5600:    }
 5601:    else{
 5602: 	   printf("The process is not running under WOW64 (i.e probably on a 64bits windows).\n");
 5603: 	   frintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bits windows).\n");
 5604:    }
 5605:    //	   printf("\nPress Enter to continue...");
 5606:    //	   getchar();
 5607:    //   }
 5608: 
 5609: #endif
 5610:    
 5611: 
 5612:  }
 5613: 
 5614: /***********************************************/
 5615: /**************** Main Program *****************/
 5616: /***********************************************/
 5617: 
 5618: int main(int argc, char *argv[])
 5619: {
 5620: #ifdef GSL
 5621:   const gsl_multimin_fminimizer_type *T;
 5622:   size_t iteri = 0, it;
 5623:   int rval = GSL_CONTINUE;
 5624:   int status = GSL_SUCCESS;
 5625:   double ssval;
 5626: #endif
 5627:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5628:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5629: 
 5630:   int jj, ll, li, lj, lk;
 5631:   int numlinepar=0; /* Current linenumber of parameter file */
 5632:   int itimes;
 5633:   int NDIM=2;
 5634:   int vpopbased=0;
 5635: 
 5636:   char ca[32], cb[32];
 5637:   /*  FILE *fichtm; *//* Html File */
 5638:   /* FILE *ficgp;*/ /*Gnuplot File */
 5639:   struct stat info;
 5640:   double agedeb;
 5641:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5642: 
 5643:   double fret;
 5644:   double dum; /* Dummy variable */
 5645:   double ***p3mat;
 5646:   double ***mobaverage;
 5647: 
 5648:   char line[MAXLINE];
 5649:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5650:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5651:   char *tok, *val; /* pathtot */
 5652:   int firstobs=1, lastobs=10;
 5653:   int c,  h , cpt;
 5654:   int jl;
 5655:   int i1, j1, jk, stepsize;
 5656:   int *tab; 
 5657:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5658:   int mobilav=0,popforecast=0;
 5659:   int hstepm, nhstepm;
 5660:   int agemortsup;
 5661:   float  sumlpop=0.;
 5662:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5663:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5664: 
 5665:   double bage=0, fage=110, age, agelim, agebase;
 5666:   double ftolpl=FTOL;
 5667:   double **prlim;
 5668:   double ***param; /* Matrix of parameters */
 5669:   double  *p;
 5670:   double **matcov; /* Matrix of covariance */
 5671:   double ***delti3; /* Scale */
 5672:   double *delti; /* Scale */
 5673:   double ***eij, ***vareij;
 5674:   double **varpl; /* Variances of prevalence limits by age */
 5675:   double *epj, vepp;
 5676: 
 5677:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5678:   double **ximort;
 5679:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 5680:   int *dcwave;
 5681: 
 5682:   char z[1]="c";
 5683: 
 5684:   /*char  *strt;*/
 5685:   char strtend[80];
 5686: 
 5687: 
 5688: /*   setlocale (LC_ALL, ""); */
 5689: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5690: /*   textdomain (PACKAGE); */
 5691: /*   setlocale (LC_CTYPE, ""); */
 5692: /*   setlocale (LC_MESSAGES, ""); */
 5693: 
 5694:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5695:   rstart_time = time(NULL);  
 5696:   /*  (void) gettimeofday(&start_time,&tzp);*/
 5697:   start_time = *localtime(&rstart_time);
 5698:   curr_time=start_time;
 5699:   /*tml = *localtime(&start_time.tm_sec);*/
 5700:   /* strcpy(strstart,asctime(&tml)); */
 5701:   strcpy(strstart,asctime(&start_time));
 5702: 
 5703: /*  printf("Localtime (at start)=%s",strstart); */
 5704: /*  tp.tm_sec = tp.tm_sec +86400; */
 5705: /*  tm = *localtime(&start_time.tm_sec); */
 5706: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5707: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5708: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5709: /*   tp.tm_sec = mktime(&tmg); */
 5710: /*   strt=asctime(&tmg); */
 5711: /*   printf("Time(after) =%s",strstart);  */
 5712: /*  (void) time (&time_value);
 5713: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5714: *  tm = *localtime(&time_value);
 5715: *  strstart=asctime(&tm);
 5716: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5717: */
 5718: 
 5719:   nberr=0; /* Number of errors and warnings */
 5720:   nbwarn=0;
 5721:   getcwd(pathcd, size);
 5722: 
 5723:   printf("\n%s\n%s",version,fullversion);
 5724:   if(argc <=1){
 5725:     printf("\nEnter the parameter file name: ");
 5726:     fgets(pathr,FILENAMELENGTH,stdin);
 5727:     i=strlen(pathr);
 5728:     if(pathr[i-1]=='\n')
 5729:       pathr[i-1]='\0';
 5730:     i=strlen(pathr);
 5731:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 5732:       pathr[i-1]='\0';
 5733:    for (tok = pathr; tok != NULL; ){
 5734:       printf("Pathr |%s|\n",pathr);
 5735:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5736:       printf("val= |%s| pathr=%s\n",val,pathr);
 5737:       strcpy (pathtot, val);
 5738:       if(pathr[0] == '\0') break; /* Dirty */
 5739:     }
 5740:   }
 5741:   else{
 5742:     strcpy(pathtot,argv[1]);
 5743:   }
 5744:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5745:   /*cygwin_split_path(pathtot,path,optionfile);
 5746:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5747:   /* cutv(path,optionfile,pathtot,'\\');*/
 5748: 
 5749:   /* Split argv[0], imach program to get pathimach */
 5750:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5751:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5752:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5753:  /*   strcpy(pathimach,argv[0]); */
 5754:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5755:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5756:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5757:   chdir(path); /* Can be a relative path */
 5758:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5759:     printf("Current directory %s!\n",pathcd);
 5760:   strcpy(command,"mkdir ");
 5761:   strcat(command,optionfilefiname);
 5762:   if((outcmd=system(command)) != 0){
 5763:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5764:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5765:     /* fclose(ficlog); */
 5766: /*     exit(1); */
 5767:   }
 5768: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5769: /*     perror("mkdir"); */
 5770: /*   } */
 5771: 
 5772:   /*-------- arguments in the command line --------*/
 5773: 
 5774:   /* Log file */
 5775:   strcat(filelog, optionfilefiname);
 5776:   strcat(filelog,".log");    /* */
 5777:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5778:     printf("Problem with logfile %s\n",filelog);
 5779:     goto end;
 5780:   }
 5781:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5782:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5783:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5784:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5785:  path=%s \n\
 5786:  optionfile=%s\n\
 5787:  optionfilext=%s\n\
 5788:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5789: 
 5790:   syscompilerinfo();
 5791: 
 5792:   printf("Local time (at start):%s",strstart);
 5793:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5794:   fflush(ficlog);
 5795: /*   (void) gettimeofday(&curr_time,&tzp); */
 5796: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 5797: 
 5798:   /* */
 5799:   strcpy(fileres,"r");
 5800:   strcat(fileres, optionfilefiname);
 5801:   strcat(fileres,".txt");    /* Other files have txt extension */
 5802: 
 5803:   /*---------arguments file --------*/
 5804: 
 5805:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5806:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5807:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5808:     fflush(ficlog);
 5809:     /* goto end; */
 5810:     exit(70); 
 5811:   }
 5812: 
 5813: 
 5814: 
 5815:   strcpy(filereso,"o");
 5816:   strcat(filereso,fileres);
 5817:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5818:     printf("Problem with Output resultfile: %s\n", filereso);
 5819:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5820:     fflush(ficlog);
 5821:     goto end;
 5822:   }
 5823: 
 5824:   /* Reads comments: lines beginning with '#' */
 5825:   numlinepar=0;
 5826:   while((c=getc(ficpar))=='#' && c!= EOF){
 5827:     ungetc(c,ficpar);
 5828:     fgets(line, MAXLINE, ficpar);
 5829:     numlinepar++;
 5830:     fputs(line,stdout);
 5831:     fputs(line,ficparo);
 5832:     fputs(line,ficlog);
 5833:   }
 5834:   ungetc(c,ficpar);
 5835: 
 5836:   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=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 5837:   numlinepar++;
 5838:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 5839:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 5840:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 5841:   fflush(ficlog);
 5842:   while((c=getc(ficpar))=='#' && c!= EOF){
 5843:     ungetc(c,ficpar);
 5844:     fgets(line, MAXLINE, ficpar);
 5845:     numlinepar++;
 5846:     fputs(line, stdout);
 5847:     //puts(line);
 5848:     fputs(line,ficparo);
 5849:     fputs(line,ficlog);
 5850:   }
 5851:   ungetc(c,ficpar);
 5852: 
 5853:    
 5854:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 5855:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5856:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5857:      v1+v2*age+v2*v3 makes cptcovn = 3
 5858:   */
 5859:   if (strlen(model)>1) 
 5860:     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*/
 5861:   else
 5862:     ncovmodel=2;
 5863:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5864:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5865:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5866:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5867:     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);
 5868:     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);
 5869:     fflush(stdout);
 5870:     fclose (ficlog);
 5871:     goto end;
 5872:   }
 5873:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5874:   delti=delti3[1][1];
 5875:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5876:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5877:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5878:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5879:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5880:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5881:     fclose (ficparo);
 5882:     fclose (ficlog);
 5883:     goto end;
 5884:     exit(0);
 5885:   }
 5886:   else if(mle==-3) {
 5887:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5888:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5889:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5890:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5891:     matcov=matrix(1,npar,1,npar);
 5892:   }
 5893:   else{
 5894:     /* Read guessed parameters */
 5895:     /* Reads comments: lines beginning with '#' */
 5896:     while((c=getc(ficpar))=='#' && c!= EOF){
 5897:       ungetc(c,ficpar);
 5898:       fgets(line, MAXLINE, ficpar);
 5899:       numlinepar++;
 5900:       fputs(line,stdout);
 5901:       fputs(line,ficparo);
 5902:       fputs(line,ficlog);
 5903:     }
 5904:     ungetc(c,ficpar);
 5905:     
 5906:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5907:     for(i=1; i <=nlstate; i++){
 5908:       j=0;
 5909:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5910: 	if(jj==i) continue;
 5911: 	j++;
 5912: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5913: 	if ((i1 != i) && (j1 != j)){
 5914: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5915: It might be a problem of design; if ncovcol and the model are correct\n \
 5916: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5917: 	  exit(1);
 5918: 	}
 5919: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5920: 	if(mle==1)
 5921: 	  printf("%1d%1d",i,j);
 5922: 	fprintf(ficlog,"%1d%1d",i,j);
 5923: 	for(k=1; k<=ncovmodel;k++){
 5924: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5925: 	  if(mle==1){
 5926: 	    printf(" %lf",param[i][j][k]);
 5927: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5928: 	  }
 5929: 	  else
 5930: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5931: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5932: 	}
 5933: 	fscanf(ficpar,"\n");
 5934: 	numlinepar++;
 5935: 	if(mle==1)
 5936: 	  printf("\n");
 5937: 	fprintf(ficlog,"\n");
 5938: 	fprintf(ficparo,"\n");
 5939:       }
 5940:     }  
 5941:     fflush(ficlog);
 5942: 
 5943:     /* Reads scales values */
 5944:     p=param[1][1];
 5945:     
 5946:     /* Reads comments: lines beginning with '#' */
 5947:     while((c=getc(ficpar))=='#' && c!= EOF){
 5948:       ungetc(c,ficpar);
 5949:       fgets(line, MAXLINE, ficpar);
 5950:       numlinepar++;
 5951:       fputs(line,stdout);
 5952:       fputs(line,ficparo);
 5953:       fputs(line,ficlog);
 5954:     }
 5955:     ungetc(c,ficpar);
 5956: 
 5957:     for(i=1; i <=nlstate; i++){
 5958:       for(j=1; j <=nlstate+ndeath-1; j++){
 5959: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5960: 	if ( (i1-i) * (j1-j) != 0){
 5961: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5962: 	  exit(1);
 5963: 	}
 5964: 	printf("%1d%1d",i,j);
 5965: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5966: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5967: 	for(k=1; k<=ncovmodel;k++){
 5968: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5969: 	  printf(" %le",delti3[i][j][k]);
 5970: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5971: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5972: 	}
 5973: 	fscanf(ficpar,"\n");
 5974: 	numlinepar++;
 5975: 	printf("\n");
 5976: 	fprintf(ficparo,"\n");
 5977: 	fprintf(ficlog,"\n");
 5978:       }
 5979:     }
 5980:     fflush(ficlog);
 5981: 
 5982:     /* Reads covariance matrix */
 5983:     delti=delti3[1][1];
 5984: 
 5985: 
 5986:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5987:   
 5988:     /* Reads comments: lines beginning with '#' */
 5989:     while((c=getc(ficpar))=='#' && c!= EOF){
 5990:       ungetc(c,ficpar);
 5991:       fgets(line, MAXLINE, ficpar);
 5992:       numlinepar++;
 5993:       fputs(line,stdout);
 5994:       fputs(line,ficparo);
 5995:       fputs(line,ficlog);
 5996:     }
 5997:     ungetc(c,ficpar);
 5998:   
 5999:     matcov=matrix(1,npar,1,npar);
 6000:     for(i=1; i <=npar; i++)
 6001:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6002:       
 6003:     for(i=1; i <=npar; i++){
 6004:       fscanf(ficpar,"%s",str);
 6005:       if(mle==1)
 6006: 	printf("%s",str);
 6007:       fprintf(ficlog,"%s",str);
 6008:       fprintf(ficparo,"%s",str);
 6009:       for(j=1; j <=i; j++){
 6010: 	fscanf(ficpar," %le",&matcov[i][j]);
 6011: 	if(mle==1){
 6012: 	  printf(" %.5le",matcov[i][j]);
 6013: 	}
 6014: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6015: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6016:       }
 6017:       fscanf(ficpar,"\n");
 6018:       numlinepar++;
 6019:       if(mle==1)
 6020: 	printf("\n");
 6021:       fprintf(ficlog,"\n");
 6022:       fprintf(ficparo,"\n");
 6023:     }
 6024:     for(i=1; i <=npar; i++)
 6025:       for(j=i+1;j<=npar;j++)
 6026: 	matcov[i][j]=matcov[j][i];
 6027:     
 6028:     if(mle==1)
 6029:       printf("\n");
 6030:     fprintf(ficlog,"\n");
 6031:     
 6032:     fflush(ficlog);
 6033:     
 6034:     /*-------- Rewriting parameter file ----------*/
 6035:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6036:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6037:     strcat(rfileres,".");    /* */
 6038:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6039:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6040:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6041:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6042:     }
 6043:     fprintf(ficres,"#%s\n",version);
 6044:   }    /* End of mle != -3 */
 6045: 
 6046: 
 6047:   n= lastobs;
 6048:   num=lvector(1,n);
 6049:   moisnais=vector(1,n);
 6050:   annais=vector(1,n);
 6051:   moisdc=vector(1,n);
 6052:   andc=vector(1,n);
 6053:   agedc=vector(1,n);
 6054:   cod=ivector(1,n);
 6055:   weight=vector(1,n);
 6056:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6057:   mint=matrix(1,maxwav,1,n);
 6058:   anint=matrix(1,maxwav,1,n);
 6059:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6060:   tab=ivector(1,NCOVMAX);
 6061:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6062: 
 6063:   /* Reads data from file datafile */
 6064:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6065:     goto end;
 6066: 
 6067:   /* Calculation of the number of parameters from char model */
 6068:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6069: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6070: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6071: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6072: 	k=1 Tvar[1]=2 (from V2)
 6073:     */
 6074:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6075:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6076:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6077:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6078:   */
 6079:   /* For model-covariate k tells which data-covariate to use but
 6080:     because this model-covariate is a construction we invent a new column
 6081:     ncovcol + k1
 6082:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6083:     Tvar[3=V1*V4]=4+1 etc */
 6084:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6085:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6086:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6087:   */
 6088:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6089:   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
 6090: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6091: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6092:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6093: 			 4 covariates (3 plus signs)
 6094: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6095: 		      */  
 6096: 
 6097:   if(decodemodel(model, lastobs) == 1)
 6098:     goto end;
 6099: 
 6100:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6101:     nbwarn++;
 6102:     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); 
 6103:     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); 
 6104:   }
 6105:     /*  if(mle==1){*/
 6106:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6107:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6108:   }
 6109: 
 6110:     /*-calculation of age at interview from date of interview and age at death -*/
 6111:   agev=matrix(1,maxwav,1,imx);
 6112: 
 6113:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6114:     goto end;
 6115: 
 6116: 
 6117:   agegomp=(int)agemin;
 6118:   free_vector(moisnais,1,n);
 6119:   free_vector(annais,1,n);
 6120:   /* free_matrix(mint,1,maxwav,1,n);
 6121:      free_matrix(anint,1,maxwav,1,n);*/
 6122:   free_vector(moisdc,1,n);
 6123:   free_vector(andc,1,n);
 6124:   /* */
 6125:   
 6126:   wav=ivector(1,imx);
 6127:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6128:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6129:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6130:    
 6131:   /* Concatenates waves */
 6132:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6133:   /* */
 6134:  
 6135:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6136: 
 6137:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6138:   ncodemax[1]=1;
 6139:   Ndum =ivector(-1,NCOVMAX);  
 6140:   if (ncovmodel > 2)
 6141:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6142: 
 6143:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6144:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6145:   h=0;
 6146: 
 6147: 
 6148:   /*if (cptcovn > 0) */
 6149:       
 6150:  
 6151:   m=pow(2,cptcoveff);
 6152:  
 6153:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6154:     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 */ 
 6155:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6156: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6157: 	  h++;
 6158: 	  if (h>m) 
 6159: 	    h=1;
 6160: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6161: 	   *     h     1     2     3     4
 6162: 	   *______________________________  
 6163: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6164: 	   *     2     2     1     1     1
 6165: 	   *     3 i=2 1     2     1     1
 6166: 	   *     4     2     2     1     1
 6167: 	   *     5 i=3 1 i=2 1     2     1
 6168: 	   *     6     2     1     2     1
 6169: 	   *     7 i=4 1     2     2     1
 6170: 	   *     8     2     2     2     1
 6171: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6172: 	   *    10     2     1     1     1
 6173: 	   *    11 i=6 1     2     1     1
 6174: 	   *    12     2     2     1     1
 6175: 	   *    13 i=7 1 i=4 1     2     1    
 6176: 	   *    14     2     1     2     1
 6177: 	   *    15 i=8 1     2     2     1
 6178: 	   *    16     2     2     2     1
 6179: 	   */
 6180: 	  codtab[h][k]=j;
 6181: 	  /*codtab[h][Tvar[k]]=j;*/
 6182: 	  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]]);
 6183: 	} 
 6184:       }
 6185:     }
 6186:   } 
 6187:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6188:      codtab[1][2]=1;codtab[2][2]=2; */
 6189:   /* for(i=1; i <=m ;i++){ 
 6190:      for(k=1; k <=cptcovn; k++){
 6191:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6192:      }
 6193:      printf("\n");
 6194:      }
 6195:      scanf("%d",i);*/
 6196: 
 6197:  free_ivector(Ndum,-1,NCOVMAX);
 6198: 
 6199: 
 6200:     
 6201:   /*------------ gnuplot -------------*/
 6202:   strcpy(optionfilegnuplot,optionfilefiname);
 6203:   if(mle==-3)
 6204:     strcat(optionfilegnuplot,"-mort");
 6205:   strcat(optionfilegnuplot,".gp");
 6206: 
 6207:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6208:     printf("Problem with file %s",optionfilegnuplot);
 6209:   }
 6210:   else{
 6211:     fprintf(ficgp,"\n# %s\n", version); 
 6212:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6213:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6214:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6215:   }
 6216:   /*  fclose(ficgp);*/
 6217:   /*--------- index.htm --------*/
 6218: 
 6219:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6220:   if(mle==-3)
 6221:     strcat(optionfilehtm,"-mort");
 6222:   strcat(optionfilehtm,".htm");
 6223:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6224:     printf("Problem with %s \n",optionfilehtm);
 6225:     exit(0);
 6226:   }
 6227: 
 6228:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6229:   strcat(optionfilehtmcov,"-cov.htm");
 6230:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6231:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6232:   }
 6233:   else{
 6234:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6235: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6236: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6237: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6238:   }
 6239: 
 6240:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6241: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6242: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6243: \n\
 6244: <hr  size=\"2\" color=\"#EC5E5E\">\
 6245:  <ul><li><h4>Parameter files</h4>\n\
 6246:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6247:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6248:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6249:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6250:  - Date and time at start: %s</ul>\n",\
 6251: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6252: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6253: 	  fileres,fileres,\
 6254: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6255:   fflush(fichtm);
 6256: 
 6257:   strcpy(pathr,path);
 6258:   strcat(pathr,optionfilefiname);
 6259:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6260:   
 6261:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6262:      and prints on file fileres'p'. */
 6263:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6264: 
 6265:   fprintf(fichtm,"\n");
 6266:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6267: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6268: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6269: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6270:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6271:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6272:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6273:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6274:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6275:     
 6276:    
 6277:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6278:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6279:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6280: 
 6281:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6282: 
 6283:   if (mle==-3){
 6284:     ximort=matrix(1,NDIM,1,NDIM); 
 6285: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6286:     cens=ivector(1,n);
 6287:     ageexmed=vector(1,n);
 6288:     agecens=vector(1,n);
 6289:     dcwave=ivector(1,n);
 6290:  
 6291:     for (i=1; i<=imx; i++){
 6292:       dcwave[i]=-1;
 6293:       for (m=firstpass; m<=lastpass; m++)
 6294: 	if (s[m][i]>nlstate) {
 6295: 	  dcwave[i]=m;
 6296: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6297: 	  break;
 6298: 	}
 6299:     }
 6300: 
 6301:     for (i=1; i<=imx; i++) {
 6302:       if (wav[i]>0){
 6303: 	ageexmed[i]=agev[mw[1][i]][i];
 6304: 	j=wav[i];
 6305: 	agecens[i]=1.; 
 6306: 
 6307: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6308: 	  agecens[i]=agev[mw[j][i]][i];
 6309: 	  cens[i]= 1;
 6310: 	}else if (ageexmed[i]< 1) 
 6311: 	  cens[i]= -1;
 6312: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6313: 	  cens[i]=0 ;
 6314:       }
 6315:       else cens[i]=-1;
 6316:     }
 6317:     
 6318:     for (i=1;i<=NDIM;i++) {
 6319:       for (j=1;j<=NDIM;j++)
 6320: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6321:     }
 6322:     
 6323:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6324:     /*printf("%lf %lf", p[1], p[2]);*/
 6325:     
 6326:     
 6327: #ifdef GSL
 6328:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6329: #else
 6330:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6331: #endif
 6332:     strcpy(filerespow,"pow-mort"); 
 6333:     strcat(filerespow,fileres);
 6334:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6335:       printf("Problem with resultfile: %s\n", filerespow);
 6336:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6337:     }
 6338: #ifdef GSL
 6339:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6340: #else
 6341:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6342: #endif
 6343:     /*  for (i=1;i<=nlstate;i++)
 6344: 	for(j=1;j<=nlstate+ndeath;j++)
 6345: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6346:     */
 6347:     fprintf(ficrespow,"\n");
 6348: #ifdef GSL
 6349:     /* gsl starts here */ 
 6350:     T = gsl_multimin_fminimizer_nmsimplex;
 6351:     gsl_multimin_fminimizer *sfm = NULL;
 6352:     gsl_vector *ss, *x;
 6353:     gsl_multimin_function minex_func;
 6354: 
 6355:     /* Initial vertex size vector */
 6356:     ss = gsl_vector_alloc (NDIM);
 6357:     
 6358:     if (ss == NULL){
 6359:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6360:     }
 6361:     /* Set all step sizes to 1 */
 6362:     gsl_vector_set_all (ss, 0.001);
 6363: 
 6364:     /* Starting point */
 6365:     
 6366:     x = gsl_vector_alloc (NDIM);
 6367:     
 6368:     if (x == NULL){
 6369:       gsl_vector_free(ss);
 6370:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6371:     }
 6372:   
 6373:     /* Initialize method and iterate */
 6374:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6375: /*     gsl_vector_set(x, 0, 0.0268); */
 6376: /*     gsl_vector_set(x, 1, 0.083); */
 6377:     gsl_vector_set(x, 0, p[1]);
 6378:     gsl_vector_set(x, 1, p[2]);
 6379: 
 6380:     minex_func.f = &gompertz_f;
 6381:     minex_func.n = NDIM;
 6382:     minex_func.params = (void *)&p; /* ??? */
 6383:     
 6384:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6385:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6386:     
 6387:     printf("Iterations beginning .....\n\n");
 6388:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6389: 
 6390:     iteri=0;
 6391:     while (rval == GSL_CONTINUE){
 6392:       iteri++;
 6393:       status = gsl_multimin_fminimizer_iterate(sfm);
 6394:       
 6395:       if (status) printf("error: %s\n", gsl_strerror (status));
 6396:       fflush(0);
 6397:       
 6398:       if (status) 
 6399:         break;
 6400:       
 6401:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6402:       ssval = gsl_multimin_fminimizer_size (sfm);
 6403:       
 6404:       if (rval == GSL_SUCCESS)
 6405:         printf ("converged to a local maximum at\n");
 6406:       
 6407:       printf("%5d ", iteri);
 6408:       for (it = 0; it < NDIM; it++){
 6409: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6410:       }
 6411:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6412:     }
 6413:     
 6414:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6415:     
 6416:     gsl_vector_free(x); /* initial values */
 6417:     gsl_vector_free(ss); /* inital step size */
 6418:     for (it=0; it<NDIM; it++){
 6419:       p[it+1]=gsl_vector_get(sfm->x,it);
 6420:       fprintf(ficrespow," %.12lf", p[it]);
 6421:     }
 6422:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6423: #endif
 6424: #ifdef POWELL
 6425:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6426: #endif  
 6427:     fclose(ficrespow);
 6428:     
 6429:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6430: 
 6431:     for(i=1; i <=NDIM; i++)
 6432:       for(j=i+1;j<=NDIM;j++)
 6433: 	matcov[i][j]=matcov[j][i];
 6434:     
 6435:     printf("\nCovariance matrix\n ");
 6436:     for(i=1; i <=NDIM; i++) {
 6437:       for(j=1;j<=NDIM;j++){ 
 6438: 	printf("%f ",matcov[i][j]);
 6439:       }
 6440:       printf("\n ");
 6441:     }
 6442:     
 6443:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6444:     for (i=1;i<=NDIM;i++) 
 6445:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6446: 
 6447:     lsurv=vector(1,AGESUP);
 6448:     lpop=vector(1,AGESUP);
 6449:     tpop=vector(1,AGESUP);
 6450:     lsurv[agegomp]=100000;
 6451:     
 6452:     for (k=agegomp;k<=AGESUP;k++) {
 6453:       agemortsup=k;
 6454:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6455:     }
 6456:     
 6457:     for (k=agegomp;k<agemortsup;k++)
 6458:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6459:     
 6460:     for (k=agegomp;k<agemortsup;k++){
 6461:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6462:       sumlpop=sumlpop+lpop[k];
 6463:     }
 6464:     
 6465:     tpop[agegomp]=sumlpop;
 6466:     for (k=agegomp;k<(agemortsup-3);k++){
 6467:       /*  tpop[k+1]=2;*/
 6468:       tpop[k+1]=tpop[k]-lpop[k];
 6469:     }
 6470:     
 6471:     
 6472:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6473:     for (k=agegomp;k<(agemortsup-2);k++) 
 6474:       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]);
 6475:     
 6476:     
 6477:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6478:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6479:     
 6480:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6481: 		     stepm, weightopt,\
 6482: 		     model,imx,p,matcov,agemortsup);
 6483:     
 6484:     free_vector(lsurv,1,AGESUP);
 6485:     free_vector(lpop,1,AGESUP);
 6486:     free_vector(tpop,1,AGESUP);
 6487: #ifdef GSL
 6488:     free_ivector(cens,1,n);
 6489:     free_vector(agecens,1,n);
 6490:     free_ivector(dcwave,1,n);
 6491:     free_matrix(ximort,1,NDIM,1,NDIM);
 6492: #endif
 6493:   } /* Endof if mle==-3 */
 6494:   
 6495:   else{ /* For mle >=1 */
 6496:     globpr=0;/* debug */
 6497:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6498:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6499:     for (k=1; k<=npar;k++)
 6500:       printf(" %d %8.5f",k,p[k]);
 6501:     printf("\n");
 6502:     globpr=1; /* to print the contributions */
 6503:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6504:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6505:     for (k=1; k<=npar;k++)
 6506:       printf(" %d %8.5f",k,p[k]);
 6507:     printf("\n");
 6508:     if(mle>=1){ /* Could be 1 or 2 */
 6509:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6510:     }
 6511:     
 6512:     /*--------- results files --------------*/
 6513:     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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 6514:     
 6515:     
 6516:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6517:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6518:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6519:     for(i=1,jk=1; i <=nlstate; i++){
 6520:       for(k=1; k <=(nlstate+ndeath); k++){
 6521: 	if (k != i) {
 6522: 	  printf("%d%d ",i,k);
 6523: 	  fprintf(ficlog,"%d%d ",i,k);
 6524: 	  fprintf(ficres,"%1d%1d ",i,k);
 6525: 	  for(j=1; j <=ncovmodel; j++){
 6526: 	    printf("%lf ",p[jk]);
 6527: 	    fprintf(ficlog,"%lf ",p[jk]);
 6528: 	    fprintf(ficres,"%lf ",p[jk]);
 6529: 	    jk++; 
 6530: 	  }
 6531: 	  printf("\n");
 6532: 	  fprintf(ficlog,"\n");
 6533: 	  fprintf(ficres,"\n");
 6534: 	}
 6535:       }
 6536:     }
 6537:     if(mle!=0){
 6538:       /* Computing hessian and covariance matrix */
 6539:       ftolhess=ftol; /* Usually correct */
 6540:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6541:     }
 6542:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6543:     printf("# Scales (for hessian or gradient estimation)\n");
 6544:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6545:     for(i=1,jk=1; i <=nlstate; i++){
 6546:       for(j=1; j <=nlstate+ndeath; j++){
 6547: 	if (j!=i) {
 6548: 	  fprintf(ficres,"%1d%1d",i,j);
 6549: 	  printf("%1d%1d",i,j);
 6550: 	  fprintf(ficlog,"%1d%1d",i,j);
 6551: 	  for(k=1; k<=ncovmodel;k++){
 6552: 	    printf(" %.5e",delti[jk]);
 6553: 	    fprintf(ficlog," %.5e",delti[jk]);
 6554: 	    fprintf(ficres," %.5e",delti[jk]);
 6555: 	    jk++;
 6556: 	  }
 6557: 	  printf("\n");
 6558: 	  fprintf(ficlog,"\n");
 6559: 	  fprintf(ficres,"\n");
 6560: 	}
 6561:       }
 6562:     }
 6563:     
 6564:     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");
 6565:     if(mle>=1)
 6566:       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");
 6567:     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");
 6568:     /* # 121 Var(a12)\n\ */
 6569:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6570:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6571:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6572:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6573:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6574:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6575:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6576:     
 6577:     
 6578:     /* Just to have a covariance matrix which will be more understandable
 6579:        even is we still don't want to manage dictionary of variables
 6580:     */
 6581:     for(itimes=1;itimes<=2;itimes++){
 6582:       jj=0;
 6583:       for(i=1; i <=nlstate; i++){
 6584: 	for(j=1; j <=nlstate+ndeath; j++){
 6585: 	  if(j==i) continue;
 6586: 	  for(k=1; k<=ncovmodel;k++){
 6587: 	    jj++;
 6588: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6589: 	    if(itimes==1){
 6590: 	      if(mle>=1)
 6591: 		printf("#%1d%1d%d",i,j,k);
 6592: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6593: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6594: 	    }else{
 6595: 	      if(mle>=1)
 6596: 		printf("%1d%1d%d",i,j,k);
 6597: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6598: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6599: 	    }
 6600: 	    ll=0;
 6601: 	    for(li=1;li <=nlstate; li++){
 6602: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6603: 		if(lj==li) continue;
 6604: 		for(lk=1;lk<=ncovmodel;lk++){
 6605: 		  ll++;
 6606: 		  if(ll<=jj){
 6607: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6608: 		    if(ll<jj){
 6609: 		      if(itimes==1){
 6610: 			if(mle>=1)
 6611: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6612: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6613: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6614: 		      }else{
 6615: 			if(mle>=1)
 6616: 			  printf(" %.5e",matcov[jj][ll]); 
 6617: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6618: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6619: 		      }
 6620: 		    }else{
 6621: 		      if(itimes==1){
 6622: 			if(mle>=1)
 6623: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6624: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6625: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6626: 		      }else{
 6627: 			if(mle>=1)
 6628: 			  printf(" %.5e",matcov[jj][ll]); 
 6629: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6630: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6631: 		      }
 6632: 		    }
 6633: 		  }
 6634: 		} /* end lk */
 6635: 	      } /* end lj */
 6636: 	    } /* end li */
 6637: 	    if(mle>=1)
 6638: 	      printf("\n");
 6639: 	    fprintf(ficlog,"\n");
 6640: 	    fprintf(ficres,"\n");
 6641: 	    numlinepar++;
 6642: 	  } /* end k*/
 6643: 	} /*end j */
 6644:       } /* end i */
 6645:     } /* end itimes */
 6646:     
 6647:     fflush(ficlog);
 6648:     fflush(ficres);
 6649:     
 6650:     while((c=getc(ficpar))=='#' && c!= EOF){
 6651:       ungetc(c,ficpar);
 6652:       fgets(line, MAXLINE, ficpar);
 6653:       fputs(line,stdout);
 6654:       fputs(line,ficparo);
 6655:     }
 6656:     ungetc(c,ficpar);
 6657:     
 6658:     estepm=0;
 6659:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6660:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6661:     if (fage <= 2) {
 6662:       bage = ageminpar;
 6663:       fage = agemaxpar;
 6664:     }
 6665:     
 6666:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6667:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6668:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6669:     
 6670:     while((c=getc(ficpar))=='#' && c!= EOF){
 6671:       ungetc(c,ficpar);
 6672:       fgets(line, MAXLINE, ficpar);
 6673:       fputs(line,stdout);
 6674:       fputs(line,ficparo);
 6675:     }
 6676:     ungetc(c,ficpar);
 6677:     
 6678:     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);
 6679:     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);
 6680:     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);
 6681:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6682:     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);
 6683:     
 6684:     while((c=getc(ficpar))=='#' && c!= EOF){
 6685:       ungetc(c,ficpar);
 6686:       fgets(line, MAXLINE, ficpar);
 6687:       fputs(line,stdout);
 6688:       fputs(line,ficparo);
 6689:     }
 6690:     ungetc(c,ficpar);
 6691:     
 6692:     
 6693:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6694:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6695:     
 6696:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6697:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6698:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6699:     
 6700:     while((c=getc(ficpar))=='#' && c!= EOF){
 6701:       ungetc(c,ficpar);
 6702:       fgets(line, MAXLINE, ficpar);
 6703:       fputs(line,stdout);
 6704:       fputs(line,ficparo);
 6705:     }
 6706:     ungetc(c,ficpar);
 6707:     
 6708:     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);
 6709:     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);
 6710:     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);
 6711:     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);
 6712:     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);
 6713:     /* day and month of proj2 are not used but only year anproj2.*/
 6714:     
 6715:     
 6716:     
 6717:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 6718:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 6719:     
 6720:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6721:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6722:     
 6723:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6724: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6725: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6726:       
 6727:    /*------------ free_vector  -------------*/
 6728:    /*  chdir(path); */
 6729:  
 6730:     free_ivector(wav,1,imx);
 6731:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6732:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6733:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6734:     free_lvector(num,1,n);
 6735:     free_vector(agedc,1,n);
 6736:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6737:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6738:     fclose(ficparo);
 6739:     fclose(ficres);
 6740: 
 6741: 
 6742:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6743: #include "prevlim.h"  /* Use ficrespl, ficlog */
 6744:     fclose(ficrespl);
 6745: 
 6746: #ifdef FREEEXIT2
 6747: #include "freeexit2.h"
 6748: #endif
 6749: 
 6750:     /*------------- h Pij x at various ages ------------*/
 6751: #include "hpijx.h"
 6752:     fclose(ficrespij);
 6753: 
 6754:   /*-------------- Variance of one-step probabilities---*/
 6755:     k=1;
 6756:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6757: 
 6758: 
 6759:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6760:     for(i=1;i<=AGESUP;i++)
 6761:       for(j=1;j<=NCOVMAX;j++)
 6762: 	for(k=1;k<=NCOVMAX;k++)
 6763: 	  probs[i][j][k]=0.;
 6764: 
 6765:     /*---------- Forecasting ------------------*/
 6766:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6767:     if(prevfcast==1){
 6768:       /*    if(stepm ==1){*/
 6769:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6770:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6771:       /*      }  */
 6772:       /*      else{ */
 6773:       /*        erreur=108; */
 6774:       /*        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); */
 6775:       /*        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); */
 6776:       /*      } */
 6777:     }
 6778:   
 6779: 
 6780:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6781: 
 6782:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6783:     /*  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",\
 6784: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6785:     */
 6786: 
 6787:     if (mobilav!=0) {
 6788:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6789:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6790: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6791: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6792:       }
 6793:     }
 6794: 
 6795: 
 6796:     /*---------- Health expectancies, no variances ------------*/
 6797: 
 6798:     strcpy(filerese,"e");
 6799:     strcat(filerese,fileres);
 6800:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6801:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6802:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6803:     }
 6804:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6805:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6806:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6807:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6808:           
 6809:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6810: 	fprintf(ficreseij,"\n#****** ");
 6811: 	for(j=1;j<=cptcoveff;j++) {
 6812: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6813: 	}
 6814: 	fprintf(ficreseij,"******\n");
 6815: 
 6816: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6817: 	oldm=oldms;savm=savms;
 6818: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6819:       
 6820: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6821:       /*}*/
 6822:     }
 6823:     fclose(ficreseij);
 6824: 
 6825: 
 6826:     /*---------- Health expectancies and variances ------------*/
 6827: 
 6828: 
 6829:     strcpy(filerest,"t");
 6830:     strcat(filerest,fileres);
 6831:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6832:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6833:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6834:     }
 6835:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6836:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6837: 
 6838: 
 6839:     strcpy(fileresstde,"stde");
 6840:     strcat(fileresstde,fileres);
 6841:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6842:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6843:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6844:     }
 6845:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6846:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6847: 
 6848:     strcpy(filerescve,"cve");
 6849:     strcat(filerescve,fileres);
 6850:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6851:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6852:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6853:     }
 6854:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6855:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6856: 
 6857:     strcpy(fileresv,"v");
 6858:     strcat(fileresv,fileres);
 6859:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6860:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6861:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6862:     }
 6863:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6864:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6865: 
 6866:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6867:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6868:           
 6869:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6870:     	fprintf(ficrest,"\n#****** ");
 6871: 	for(j=1;j<=cptcoveff;j++) 
 6872: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6873: 	fprintf(ficrest,"******\n");
 6874: 
 6875: 	fprintf(ficresstdeij,"\n#****** ");
 6876: 	fprintf(ficrescveij,"\n#****** ");
 6877: 	for(j=1;j<=cptcoveff;j++) {
 6878: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6879: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6880: 	}
 6881: 	fprintf(ficresstdeij,"******\n");
 6882: 	fprintf(ficrescveij,"******\n");
 6883: 
 6884: 	fprintf(ficresvij,"\n#****** ");
 6885: 	for(j=1;j<=cptcoveff;j++) 
 6886: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6887: 	fprintf(ficresvij,"******\n");
 6888: 
 6889: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6890: 	oldm=oldms;savm=savms;
 6891: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6892: 	/*
 6893: 	 */
 6894: 	/* goto endfree; */
 6895:  
 6896: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6897: 	pstamp(ficrest);
 6898: 
 6899: 
 6900: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6901: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 6902: 	  cptcod= 0; /* To be deleted */
 6903: 	  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 */
 6904: 	  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 ");
 6905: 	  if(vpopbased==1)
 6906: 	    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);
 6907: 	  else
 6908: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6909: 	  fprintf(ficrest,"# Age e.. (std) ");
 6910: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6911: 	  fprintf(ficrest,"\n");
 6912: 
 6913: 	  epj=vector(1,nlstate+1);
 6914: 	  for(age=bage; age <=fage ;age++){
 6915: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6916: 	    if (vpopbased==1) {
 6917: 	      if(mobilav ==0){
 6918: 		for(i=1; i<=nlstate;i++)
 6919: 		  prlim[i][i]=probs[(int)age][i][k];
 6920: 	      }else{ /* mobilav */ 
 6921: 		for(i=1; i<=nlstate;i++)
 6922: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6923: 	      }
 6924: 	    }
 6925: 	
 6926: 	    fprintf(ficrest," %4.0f",age);
 6927: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6928: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6929: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6930: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6931: 	      }
 6932: 	      epj[nlstate+1] +=epj[j];
 6933: 	    }
 6934: 
 6935: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6936: 	      for(j=1;j <=nlstate;j++)
 6937: 		vepp += vareij[i][j][(int)age];
 6938: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6939: 	    for(j=1;j <=nlstate;j++){
 6940: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6941: 	    }
 6942: 	    fprintf(ficrest,"\n");
 6943: 	  }
 6944: 	}
 6945: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6946: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6947: 	free_vector(epj,1,nlstate+1);
 6948:       /*}*/
 6949:     }
 6950:     free_vector(weight,1,n);
 6951:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 6952:     free_imatrix(s,1,maxwav+1,1,n);
 6953:     free_matrix(anint,1,maxwav,1,n); 
 6954:     free_matrix(mint,1,maxwav,1,n);
 6955:     free_ivector(cod,1,n);
 6956:     free_ivector(tab,1,NCOVMAX);
 6957:     fclose(ficresstdeij);
 6958:     fclose(ficrescveij);
 6959:     fclose(ficresvij);
 6960:     fclose(ficrest);
 6961:     fclose(ficpar);
 6962:   
 6963:     /*------- Variance of period (stable) prevalence------*/   
 6964: 
 6965:     strcpy(fileresvpl,"vpl");
 6966:     strcat(fileresvpl,fileres);
 6967:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6968:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6969:       exit(0);
 6970:     }
 6971:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6972: 
 6973:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6974:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6975:           
 6976:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6977:     	fprintf(ficresvpl,"\n#****** ");
 6978: 	for(j=1;j<=cptcoveff;j++) 
 6979: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6980: 	fprintf(ficresvpl,"******\n");
 6981:       
 6982: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6983: 	oldm=oldms;savm=savms;
 6984: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6985: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6986:       /*}*/
 6987:     }
 6988: 
 6989:     fclose(ficresvpl);
 6990: 
 6991:     /*---------- End : free ----------------*/
 6992:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6993:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6994:   }  /* mle==-3 arrives here for freeing */
 6995:  /* endfree:*/
 6996:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 6997:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6998:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6999:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7000:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7001:     free_matrix(covar,0,NCOVMAX,1,n);
 7002:     free_matrix(matcov,1,npar,1,npar);
 7003:     /*free_vector(delti,1,npar);*/
 7004:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7005:     free_matrix(agev,1,maxwav,1,imx);
 7006:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7007: 
 7008:     free_ivector(ncodemax,1,NCOVMAX);
 7009:     free_ivector(Tvar,1,NCOVMAX);
 7010:     free_ivector(Tprod,1,NCOVMAX);
 7011:     free_ivector(Tvaraff,1,NCOVMAX);
 7012:     free_ivector(Tage,1,NCOVMAX);
 7013: 
 7014:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7015:     free_imatrix(codtab,1,100,1,10);
 7016:   fflush(fichtm);
 7017:   fflush(ficgp);
 7018:   
 7019: 
 7020:   if((nberr >0) || (nbwarn>0)){
 7021:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7022:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7023:   }else{
 7024:     printf("End of Imach\n");
 7025:     fprintf(ficlog,"End of Imach\n");
 7026:   }
 7027:   printf("See log file on %s\n",filelog);
 7028:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7029:   /*(void) gettimeofday(&end_time,&tzp);*/
 7030:   rend_time = time(NULL);  
 7031:   end_time = *localtime(&rend_time);
 7032:   /* tml = *localtime(&end_time.tm_sec); */
 7033:   strcpy(strtend,asctime(&end_time));
 7034:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7035:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7036:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7037: 
 7038:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7039:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7040:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7041:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7042: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7043:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7044:   fclose(fichtm);
 7045:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7046:   fclose(fichtmcov);
 7047:   fclose(ficgp);
 7048:   fclose(ficlog);
 7049:   /*------ End -----------*/
 7050: 
 7051: 
 7052:    printf("Before Current directory %s!\n",pathcd);
 7053:    if(chdir(pathcd) != 0)
 7054:     printf("Can't move to directory %s!\n",path);
 7055:   if(getcwd(pathcd,MAXLINE) > 0)
 7056:     printf("Current directory %s!\n",pathcd);
 7057:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7058:   sprintf(plotcmd,"gnuplot");
 7059: #ifdef _WIN32
 7060:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7061: #endif
 7062:   if(!stat(plotcmd,&info)){
 7063:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7064:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7065:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7066:     }else
 7067:       strcpy(pplotcmd,plotcmd);
 7068: #ifdef __unix
 7069:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7070:     if(!stat(plotcmd,&info)){
 7071:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7072:     }else
 7073:       strcpy(pplotcmd,plotcmd);
 7074: #endif
 7075:   }else
 7076:     strcpy(pplotcmd,plotcmd);
 7077:   
 7078:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7079:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7080: 
 7081:   if((outcmd=system(plotcmd)) != 0){
 7082:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7083:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7084:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7085:     if((outcmd=system(plotcmd)) != 0)
 7086:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7087:   }
 7088:   printf(" Successful, please wait...");
 7089:   while (z[0] != 'q') {
 7090:     /* chdir(path); */
 7091:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7092:     scanf("%s",z);
 7093: /*     if (z[0] == 'c') system("./imach"); */
 7094:     if (z[0] == 'e') {
 7095: #ifdef __APPLE__
 7096:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7097: #elif __linux
 7098:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7099: #else
 7100:       sprintf(pplotcmd, "%s", optionfilehtm);
 7101: #endif
 7102:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7103:       system(pplotcmd);
 7104:     }
 7105:     else if (z[0] == 'g') system(plotcmd);
 7106:     else if (z[0] == 'q') exit(0);
 7107:   }
 7108:   end:
 7109:   while (z[0] != 'q') {
 7110:     printf("\nType  q for exiting: ");
 7111:     scanf("%s",z);
 7112:   }
 7113: }

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