File:  [Local Repository] / imach / src / imach.c
Revision 1.143: download - view: text, annotated - select for diffs
Sun Jan 26 09:45:38 2014 UTC (10 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising

* imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
(Module): Version 0.98nR Running ok, but output format still only works for three covariates.

    1: /* $Id: imach.c,v 1.143 2014/01/26 09:45:38 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.143  2014/01/26 09:45:38  brouard
    5:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
    6: 
    7:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
    8:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
    9: 
   10:   Revision 1.142  2014/01/26 03:57:36  brouard
   11:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
   12: 
   13:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
   14: 
   15:   Revision 1.141  2014/01/26 02:42:01  brouard
   16:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
   17: 
   18:   Revision 1.140  2011/09/02 10:37:54  brouard
   19:   Summary: times.h is ok with mingw32 now.
   20: 
   21:   Revision 1.139  2010/06/14 07:50:17  brouard
   22:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
   23:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
   24: 
   25:   Revision 1.138  2010/04/30 18:19:40  brouard
   26:   *** empty log message ***
   27: 
   28:   Revision 1.137  2010/04/29 18:11:38  brouard
   29:   (Module): Checking covariates for more complex models
   30:   than V1+V2. A lot of change to be done. Unstable.
   31: 
   32:   Revision 1.136  2010/04/26 20:30:53  brouard
   33:   (Module): merging some libgsl code. Fixing computation
   34:   of likelione (using inter/intrapolation if mle = 0) in order to
   35:   get same likelihood as if mle=1.
   36:   Some cleaning of code and comments added.
   37: 
   38:   Revision 1.135  2009/10/29 15:33:14  brouard
   39:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   40: 
   41:   Revision 1.134  2009/10/29 13:18:53  brouard
   42:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
   43: 
   44:   Revision 1.133  2009/07/06 10:21:25  brouard
   45:   just nforces
   46: 
   47:   Revision 1.132  2009/07/06 08:22:05  brouard
   48:   Many tings
   49: 
   50:   Revision 1.131  2009/06/20 16:22:47  brouard
   51:   Some dimensions resccaled
   52: 
   53:   Revision 1.130  2009/05/26 06:44:34  brouard
   54:   (Module): Max Covariate is now set to 20 instead of 8. A
   55:   lot of cleaning with variables initialized to 0. Trying to make
   56:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
   57: 
   58:   Revision 1.129  2007/08/31 13:49:27  lievre
   59:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
   60: 
   61:   Revision 1.128  2006/06/30 13:02:05  brouard
   62:   (Module): Clarifications on computing e.j
   63: 
   64:   Revision 1.127  2006/04/28 18:11:50  brouard
   65:   (Module): Yes the sum of survivors was wrong since
   66:   imach-114 because nhstepm was no more computed in the age
   67:   loop. Now we define nhstepma in the age loop.
   68:   (Module): In order to speed up (in case of numerous covariates) we
   69:   compute health expectancies (without variances) in a first step
   70:   and then all the health expectancies with variances or standard
   71:   deviation (needs data from the Hessian matrices) which slows the
   72:   computation.
   73:   In the future we should be able to stop the program is only health
   74:   expectancies and graph are needed without standard deviations.
   75: 
   76:   Revision 1.126  2006/04/28 17:23:28  brouard
   77:   (Module): Yes the sum of survivors was wrong since
   78:   imach-114 because nhstepm was no more computed in the age
   79:   loop. Now we define nhstepma in the age loop.
   80:   Version 0.98h
   81: 
   82:   Revision 1.125  2006/04/04 15:20:31  lievre
   83:   Errors in calculation of health expectancies. Age was not initialized.
   84:   Forecasting file added.
   85: 
   86:   Revision 1.124  2006/03/22 17:13:53  lievre
   87:   Parameters are printed with %lf instead of %f (more numbers after the comma).
   88:   The log-likelihood is printed in the log file
   89: 
   90:   Revision 1.123  2006/03/20 10:52:43  brouard
   91:   * imach.c (Module): <title> changed, corresponds to .htm file
   92:   name. <head> headers where missing.
   93: 
   94:   * imach.c (Module): Weights can have a decimal point as for
   95:   English (a comma might work with a correct LC_NUMERIC environment,
   96:   otherwise the weight is truncated).
   97:   Modification of warning when the covariates values are not 0 or
   98:   1.
   99:   Version 0.98g
  100: 
  101:   Revision 1.122  2006/03/20 09:45:41  brouard
  102:   (Module): Weights can have a decimal point as for
  103:   English (a comma might work with a correct LC_NUMERIC environment,
  104:   otherwise the weight is truncated).
  105:   Modification of warning when the covariates values are not 0 or
  106:   1.
  107:   Version 0.98g
  108: 
  109:   Revision 1.121  2006/03/16 17:45:01  lievre
  110:   * imach.c (Module): Comments concerning covariates added
  111: 
  112:   * imach.c (Module): refinements in the computation of lli if
  113:   status=-2 in order to have more reliable computation if stepm is
  114:   not 1 month. Version 0.98f
  115: 
  116:   Revision 1.120  2006/03/16 15:10:38  lievre
  117:   (Module): refinements in the computation of lli if
  118:   status=-2 in order to have more reliable computation if stepm is
  119:   not 1 month. Version 0.98f
  120: 
  121:   Revision 1.119  2006/03/15 17:42:26  brouard
  122:   (Module): Bug if status = -2, the loglikelihood was
  123:   computed as likelihood omitting the logarithm. Version O.98e
  124: 
  125:   Revision 1.118  2006/03/14 18:20:07  brouard
  126:   (Module): varevsij Comments added explaining the second
  127:   table of variances if popbased=1 .
  128:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  129:   (Module): Function pstamp added
  130:   (Module): Version 0.98d
  131: 
  132:   Revision 1.117  2006/03/14 17:16:22  brouard
  133:   (Module): varevsij Comments added explaining the second
  134:   table of variances if popbased=1 .
  135:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  136:   (Module): Function pstamp added
  137:   (Module): Version 0.98d
  138: 
  139:   Revision 1.116  2006/03/06 10:29:27  brouard
  140:   (Module): Variance-covariance wrong links and
  141:   varian-covariance of ej. is needed (Saito).
  142: 
  143:   Revision 1.115  2006/02/27 12:17:45  brouard
  144:   (Module): One freematrix added in mlikeli! 0.98c
  145: 
  146:   Revision 1.114  2006/02/26 12:57:58  brouard
  147:   (Module): Some improvements in processing parameter
  148:   filename with strsep.
  149: 
  150:   Revision 1.113  2006/02/24 14:20:24  brouard
  151:   (Module): Memory leaks checks with valgrind and:
  152:   datafile was not closed, some imatrix were not freed and on matrix
  153:   allocation too.
  154: 
  155:   Revision 1.112  2006/01/30 09:55:26  brouard
  156:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  157: 
  158:   Revision 1.111  2006/01/25 20:38:18  brouard
  159:   (Module): Lots of cleaning and bugs added (Gompertz)
  160:   (Module): Comments can be added in data file. Missing date values
  161:   can be a simple dot '.'.
  162: 
  163:   Revision 1.110  2006/01/25 00:51:50  brouard
  164:   (Module): Lots of cleaning and bugs added (Gompertz)
  165: 
  166:   Revision 1.109  2006/01/24 19:37:15  brouard
  167:   (Module): Comments (lines starting with a #) are allowed in data.
  168: 
  169:   Revision 1.108  2006/01/19 18:05:42  lievre
  170:   Gnuplot problem appeared...
  171:   To be fixed
  172: 
  173:   Revision 1.107  2006/01/19 16:20:37  brouard
  174:   Test existence of gnuplot in imach path
  175: 
  176:   Revision 1.106  2006/01/19 13:24:36  brouard
  177:   Some cleaning and links added in html output
  178: 
  179:   Revision 1.105  2006/01/05 20:23:19  lievre
  180:   *** empty log message ***
  181: 
  182:   Revision 1.104  2005/09/30 16:11:43  lievre
  183:   (Module): sump fixed, loop imx fixed, and simplifications.
  184:   (Module): If the status is missing at the last wave but we know
  185:   that the person is alive, then we can code his/her status as -2
  186:   (instead of missing=-1 in earlier versions) and his/her
  187:   contributions to the likelihood is 1 - Prob of dying from last
  188:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  189:   the healthy state at last known wave). Version is 0.98
  190: 
  191:   Revision 1.103  2005/09/30 15:54:49  lievre
  192:   (Module): sump fixed, loop imx fixed, and simplifications.
  193: 
  194:   Revision 1.102  2004/09/15 17:31:30  brouard
  195:   Add the possibility to read data file including tab characters.
  196: 
  197:   Revision 1.101  2004/09/15 10:38:38  brouard
  198:   Fix on curr_time
  199: 
  200:   Revision 1.100  2004/07/12 18:29:06  brouard
  201:   Add version for Mac OS X. Just define UNIX in Makefile
  202: 
  203:   Revision 1.99  2004/06/05 08:57:40  brouard
  204:   *** empty log message ***
  205: 
  206:   Revision 1.98  2004/05/16 15:05:56  brouard
  207:   New version 0.97 . First attempt to estimate force of mortality
  208:   directly from the data i.e. without the need of knowing the health
  209:   state at each age, but using a Gompertz model: log u =a + b*age .
  210:   This is the basic analysis of mortality and should be done before any
  211:   other analysis, in order to test if the mortality estimated from the
  212:   cross-longitudinal survey is different from the mortality estimated
  213:   from other sources like vital statistic data.
  214: 
  215:   The same imach parameter file can be used but the option for mle should be -3.
  216: 
  217:   Agnès, who wrote this part of the code, tried to keep most of the
  218:   former routines in order to include the new code within the former code.
  219: 
  220:   The output is very simple: only an estimate of the intercept and of
  221:   the slope with 95% confident intervals.
  222: 
  223:   Current limitations:
  224:   A) Even if you enter covariates, i.e. with the
  225:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  226:   B) There is no computation of Life Expectancy nor Life Table.
  227: 
  228:   Revision 1.97  2004/02/20 13:25:42  lievre
  229:   Version 0.96d. Population forecasting command line is (temporarily)
  230:   suppressed.
  231: 
  232:   Revision 1.96  2003/07/15 15:38:55  brouard
  233:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  234:   rewritten within the same printf. Workaround: many printfs.
  235: 
  236:   Revision 1.95  2003/07/08 07:54:34  brouard
  237:   * imach.c (Repository):
  238:   (Repository): Using imachwizard code to output a more meaningful covariance
  239:   matrix (cov(a12,c31) instead of numbers.
  240: 
  241:   Revision 1.94  2003/06/27 13:00:02  brouard
  242:   Just cleaning
  243: 
  244:   Revision 1.93  2003/06/25 16:33:55  brouard
  245:   (Module): On windows (cygwin) function asctime_r doesn't
  246:   exist so I changed back to asctime which exists.
  247:   (Module): Version 0.96b
  248: 
  249:   Revision 1.92  2003/06/25 16:30:45  brouard
  250:   (Module): On windows (cygwin) function asctime_r doesn't
  251:   exist so I changed back to asctime which exists.
  252: 
  253:   Revision 1.91  2003/06/25 15:30:29  brouard
  254:   * imach.c (Repository): Duplicated warning errors corrected.
  255:   (Repository): Elapsed time after each iteration is now output. It
  256:   helps to forecast when convergence will be reached. Elapsed time
  257:   is stamped in powell.  We created a new html file for the graphs
  258:   concerning matrix of covariance. It has extension -cov.htm.
  259: 
  260:   Revision 1.90  2003/06/24 12:34:15  brouard
  261:   (Module): Some bugs corrected for windows. Also, when
  262:   mle=-1 a template is output in file "or"mypar.txt with the design
  263:   of the covariance matrix to be input.
  264: 
  265:   Revision 1.89  2003/06/24 12:30:52  brouard
  266:   (Module): Some bugs corrected for windows. Also, when
  267:   mle=-1 a template is output in file "or"mypar.txt with the design
  268:   of the covariance matrix to be input.
  269: 
  270:   Revision 1.88  2003/06/23 17:54:56  brouard
  271:   * 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.
  272: 
  273:   Revision 1.87  2003/06/18 12:26:01  brouard
  274:   Version 0.96
  275: 
  276:   Revision 1.86  2003/06/17 20:04:08  brouard
  277:   (Module): Change position of html and gnuplot routines and added
  278:   routine fileappend.
  279: 
  280:   Revision 1.85  2003/06/17 13:12:43  brouard
  281:   * imach.c (Repository): Check when date of death was earlier that
  282:   current date of interview. It may happen when the death was just
  283:   prior to the death. In this case, dh was negative and likelihood
  284:   was wrong (infinity). We still send an "Error" but patch by
  285:   assuming that the date of death was just one stepm after the
  286:   interview.
  287:   (Repository): Because some people have very long ID (first column)
  288:   we changed int to long in num[] and we added a new lvector for
  289:   memory allocation. But we also truncated to 8 characters (left
  290:   truncation)
  291:   (Repository): No more line truncation errors.
  292: 
  293:   Revision 1.84  2003/06/13 21:44:43  brouard
  294:   * imach.c (Repository): Replace "freqsummary" at a correct
  295:   place. It differs from routine "prevalence" which may be called
  296:   many times. Probs is memory consuming and must be used with
  297:   parcimony.
  298:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  299: 
  300:   Revision 1.83  2003/06/10 13:39:11  lievre
  301:   *** empty log message ***
  302: 
  303:   Revision 1.82  2003/06/05 15:57:20  brouard
  304:   Add log in  imach.c and  fullversion number is now printed.
  305: 
  306: */
  307: /*
  308:    Interpolated Markov Chain
  309: 
  310:   Short summary of the programme:
  311:   
  312:   This program computes Healthy Life Expectancies from
  313:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  314:   first survey ("cross") where individuals from different ages are
  315:   interviewed on their health status or degree of disability (in the
  316:   case of a health survey which is our main interest) -2- at least a
  317:   second wave of interviews ("longitudinal") which measure each change
  318:   (if any) in individual health status.  Health expectancies are
  319:   computed from the time spent in each health state according to a
  320:   model. More health states you consider, more time is necessary to reach the
  321:   Maximum Likelihood of the parameters involved in the model.  The
  322:   simplest model is the multinomial logistic model where pij is the
  323:   probability to be observed in state j at the second wave
  324:   conditional to be observed in state i at the first wave. Therefore
  325:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  326:   'age' is age and 'sex' is a covariate. If you want to have a more
  327:   complex model than "constant and age", you should modify the program
  328:   where the markup *Covariates have to be included here again* invites
  329:   you to do it.  More covariates you add, slower the
  330:   convergence.
  331: 
  332:   The advantage of this computer programme, compared to a simple
  333:   multinomial logistic model, is clear when the delay between waves is not
  334:   identical for each individual. Also, if a individual missed an
  335:   intermediate interview, the information is lost, but taken into
  336:   account using an interpolation or extrapolation.  
  337: 
  338:   hPijx is the probability to be observed in state i at age x+h
  339:   conditional to the observed state i at age x. The delay 'h' can be
  340:   split into an exact number (nh*stepm) of unobserved intermediate
  341:   states. This elementary transition (by month, quarter,
  342:   semester or year) is modelled as a multinomial logistic.  The hPx
  343:   matrix is simply the matrix product of nh*stepm elementary matrices
  344:   and the contribution of each individual to the likelihood is simply
  345:   hPijx.
  346: 
  347:   Also this programme outputs the covariance matrix of the parameters but also
  348:   of the life expectancies. It also computes the period (stable) prevalence. 
  349:   
  350:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  351:            Institut national d'études démographiques, Paris.
  352:   This software have been partly granted by Euro-REVES, a concerted action
  353:   from the European Union.
  354:   It is copyrighted identically to a GNU software product, ie programme and
  355:   software can be distributed freely for non commercial use. Latest version
  356:   can be accessed at http://euroreves.ined.fr/imach .
  357: 
  358:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  359:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  360:   
  361:   **********************************************************************/
  362: /*
  363:   main
  364:   read parameterfile
  365:   read datafile
  366:   concatwav
  367:   freqsummary
  368:   if (mle >= 1)
  369:     mlikeli
  370:   print results files
  371:   if mle==1 
  372:      computes hessian
  373:   read end of parameter file: agemin, agemax, bage, fage, estepm
  374:       begin-prev-date,...
  375:   open gnuplot file
  376:   open html file
  377:   period (stable) prevalence
  378:    for age prevalim()
  379:   h Pij x
  380:   variance of p varprob
  381:   forecasting if prevfcast==1 prevforecast call prevalence()
  382:   health expectancies
  383:   Variance-covariance of DFLE
  384:   prevalence()
  385:    movingaverage()
  386:   varevsij() 
  387:   if popbased==1 varevsij(,popbased)
  388:   total life expectancies
  389:   Variance of period (stable) prevalence
  390:  end
  391: */
  392: 
  393: 
  394: 
  395:  
  396: #include <math.h>
  397: #include <stdio.h>
  398: #include <stdlib.h>
  399: #include <string.h>
  400: #include <unistd.h>
  401: 
  402: #include <limits.h>
  403: #include <sys/types.h>
  404: #include <sys/stat.h>
  405: #include <errno.h>
  406: extern int errno;
  407: 
  408: #ifdef LINUX
  409: #include <time.h>
  410: #include "timeval.h"
  411: #else
  412: #include <sys/time.h>
  413: #endif
  414: 
  415: #ifdef GSL
  416: #include <gsl/gsl_errno.h>
  417: #include <gsl/gsl_multimin.h>
  418: #endif
  419: 
  420: /* #include <libintl.h> */
  421: /* #define _(String) gettext (String) */
  422: 
  423: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  424: 
  425: #define GNUPLOTPROGRAM "gnuplot"
  426: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  427: #define FILENAMELENGTH 132
  428: 
  429: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  430: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  431: 
  432: #define MAXPARM 128 /* Maximum number of parameters for the optimization */
  433: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
  434: 
  435: #define NINTERVMAX 8
  436: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
  437: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
  438: #define NCOVMAX 20 /* Maximum number of covariates */
  439: #define MAXN 20000
  440: #define YEARM 12. /* Number of months per year */
  441: #define AGESUP 130
  442: #define AGEBASE 40
  443: #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
  444: #ifdef UNIX
  445: #define DIRSEPARATOR '/'
  446: #define CHARSEPARATOR "/"
  447: #define ODIRSEPARATOR '\\'
  448: #else
  449: #define DIRSEPARATOR '\\'
  450: #define CHARSEPARATOR "\\"
  451: #define ODIRSEPARATOR '/'
  452: #endif
  453: 
  454: /* $Id: imach.c,v 1.143 2014/01/26 09:45:38 brouard Exp $ */
  455: /* $State: Exp $ */
  456: 
  457: char version[]="Imach version 0.98nR2, January 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
  458: char fullversion[]="$Revision: 1.143 $ $Date: 2014/01/26 09:45:38 $"; 
  459: char strstart[80];
  460: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  461: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  462: int nvar=0, nforce=0; /* Number of variables, number of forces */
  463: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov=0; /* Number of covariates, of covariates with '*age' */
  464: int npar=NPARMAX;
  465: int nlstate=2; /* Number of live states */
  466: int ndeath=1; /* Number of dead states */
  467: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  468: int popbased=0;
  469: 
  470: int *wav; /* Number of waves for this individuual 0 is possible */
  471: int maxwav=0; /* Maxim number of waves */
  472: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  473: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  474: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  475: 		   to the likelihood and the sum of weights (done by funcone)*/
  476: int mle=1, weightopt=0;
  477: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  478: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  479: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  480: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  481: double jmean=1; /* Mean space between 2 waves */
  482: double **oldm, **newm, **savm; /* Working pointers to matrices */
  483: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  484: /*FILE *fic ; */ /* Used in readdata only */
  485: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  486: FILE *ficlog, *ficrespow;
  487: int globpr=0; /* Global variable for printing or not */
  488: double fretone; /* Only one call to likelihood */
  489: long ipmx=0; /* Number of contributions */
  490: double sw; /* Sum of weights */
  491: char filerespow[FILENAMELENGTH];
  492: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  493: FILE *ficresilk;
  494: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  495: FILE *ficresprobmorprev;
  496: FILE *fichtm, *fichtmcov; /* Html File */
  497: FILE *ficreseij;
  498: char filerese[FILENAMELENGTH];
  499: FILE *ficresstdeij;
  500: char fileresstde[FILENAMELENGTH];
  501: FILE *ficrescveij;
  502: char filerescve[FILENAMELENGTH];
  503: FILE  *ficresvij;
  504: char fileresv[FILENAMELENGTH];
  505: FILE  *ficresvpl;
  506: char fileresvpl[FILENAMELENGTH];
  507: char title[MAXLINE];
  508: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  509: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  510: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  511: char command[FILENAMELENGTH];
  512: int  outcmd=0;
  513: 
  514: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  515: 
  516: char filelog[FILENAMELENGTH]; /* Log file */
  517: char filerest[FILENAMELENGTH];
  518: char fileregp[FILENAMELENGTH];
  519: char popfile[FILENAMELENGTH];
  520: 
  521: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  522: 
  523: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
  524: struct timezone tzp;
  525: extern int gettimeofday();
  526: struct tm tmg, tm, tmf, *gmtime(), *localtime();
  527: long time_value;
  528: extern long time();
  529: char strcurr[80], strfor[80];
  530: 
  531: char *endptr;
  532: long lval;
  533: double dval;
  534: 
  535: #define NR_END 1
  536: #define FREE_ARG char*
  537: #define FTOL 1.0e-10
  538: 
  539: #define NRANSI 
  540: #define ITMAX 200 
  541: 
  542: #define TOL 2.0e-4 
  543: 
  544: #define CGOLD 0.3819660 
  545: #define ZEPS 1.0e-10 
  546: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  547: 
  548: #define GOLD 1.618034 
  549: #define GLIMIT 100.0 
  550: #define TINY 1.0e-20 
  551: 
  552: static double maxarg1,maxarg2;
  553: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  554: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  555:   
  556: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  557: #define rint(a) floor(a+0.5)
  558: 
  559: static double sqrarg;
  560: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  561: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  562: int agegomp= AGEGOMP;
  563: 
  564: int imx; 
  565: int stepm=1;
  566: /* Stepm, step in month: minimum step interpolation*/
  567: 
  568: int estepm;
  569: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  570: 
  571: int m,nb;
  572: long *num;
  573: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  574: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  575: double **pmmij, ***probs;
  576: double *ageexmed,*agecens;
  577: double dateintmean=0;
  578: 
  579: double *weight;
  580: int **s; /* Status */
  581: double *agedc;
  582: double  **covar; /**< covar[i,j], value of jth covariate for individual i,
  583: 		  * covar=matrix(0,NCOVMAX,1,n); 
  584: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  585: double  idx; 
  586: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  587: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  588: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  589: double *lsurv, *lpop, *tpop;
  590: 
  591: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  592: double ftolhess; /**< Tolerance for computing hessian */
  593: 
  594: /**************** split *************************/
  595: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  596: {
  597:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  598:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  599:   */ 
  600:   char	*ss;				/* pointer */
  601:   int	l1, l2;				/* length counters */
  602: 
  603:   l1 = strlen(path );			/* length of path */
  604:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  605:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  606:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  607:     strcpy( name, path );		/* we got the fullname name because no directory */
  608:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  609:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  610:     /* get current working directory */
  611:     /*    extern  char* getcwd ( char *buf , int len);*/
  612:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  613:       return( GLOCK_ERROR_GETCWD );
  614:     }
  615:     /* got dirc from getcwd*/
  616:     printf(" DIRC = %s \n",dirc);
  617:   } else {				/* strip direcotry from path */
  618:     ss++;				/* after this, the filename */
  619:     l2 = strlen( ss );			/* length of filename */
  620:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  621:     strcpy( name, ss );		/* save file name */
  622:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  623:     dirc[l1-l2] = 0;			/* add zero */
  624:     printf(" DIRC2 = %s \n",dirc);
  625:   }
  626:   /* We add a separator at the end of dirc if not exists */
  627:   l1 = strlen( dirc );			/* length of directory */
  628:   if( dirc[l1-1] != DIRSEPARATOR ){
  629:     dirc[l1] =  DIRSEPARATOR;
  630:     dirc[l1+1] = 0; 
  631:     printf(" DIRC3 = %s \n",dirc);
  632:   }
  633:   ss = strrchr( name, '.' );		/* find last / */
  634:   if (ss >0){
  635:     ss++;
  636:     strcpy(ext,ss);			/* save extension */
  637:     l1= strlen( name);
  638:     l2= strlen(ss)+1;
  639:     strncpy( finame, name, l1-l2);
  640:     finame[l1-l2]= 0;
  641:   }
  642: 
  643:   return( 0 );				/* we're done */
  644: }
  645: 
  646: 
  647: /******************************************/
  648: 
  649: void replace_back_to_slash(char *s, char*t)
  650: {
  651:   int i;
  652:   int lg=0;
  653:   i=0;
  654:   lg=strlen(t);
  655:   for(i=0; i<= lg; i++) {
  656:     (s[i] = t[i]);
  657:     if (t[i]== '\\') s[i]='/';
  658:   }
  659: }
  660: 
  661: char *trimbb(char *out, char *in)
  662: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  663:   char *s;
  664:   s=out;
  665:   while (*in != '\0'){
  666:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  667:       in++;
  668:     }
  669:     *out++ = *in++;
  670:   }
  671:   *out='\0';
  672:   return s;
  673: }
  674: 
  675: char *cutv(char *blocc, char *alocc, char *in, char occ)
  676: {
  677:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  678:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  679:      gives blocc="abcdef2ghi" and alocc="j".
  680:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  681:   */
  682:   char *s, *t;
  683:   t=in;s=in;
  684:   while (*in != '\0'){
  685:     while( *in == occ){
  686:       *blocc++ = *in++;
  687:       s=in;
  688:     }
  689:     *blocc++ = *in++;
  690:   }
  691:   if (s == t) /* occ not found */
  692:     *(blocc-(in-s))='\0';
  693:   else
  694:     *(blocc-(in-s)-1)='\0';
  695:   in=s;
  696:   while ( *in != '\0'){
  697:     *alocc++ = *in++;
  698:   }
  699: 
  700:   *alocc='\0';
  701:   return s;
  702: }
  703: 
  704: int nbocc(char *s, char occ)
  705: {
  706:   int i,j=0;
  707:   int lg=20;
  708:   i=0;
  709:   lg=strlen(s);
  710:   for(i=0; i<= lg; i++) {
  711:   if  (s[i] == occ ) j++;
  712:   }
  713:   return j;
  714: }
  715: 
  716: /* void cutv(char *u,char *v, char*t, char occ) */
  717: /* { */
  718: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  719: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  720: /*      gives u="abcdef2ghi" and v="j" *\/ */
  721: /*   int i,lg,j,p=0; */
  722: /*   i=0; */
  723: /*   lg=strlen(t); */
  724: /*   for(j=0; j<=lg-1; j++) { */
  725: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  726: /*   } */
  727: 
  728: /*   for(j=0; j<p; j++) { */
  729: /*     (u[j] = t[j]); */
  730: /*   } */
  731: /*      u[p]='\0'; */
  732: 
  733: /*    for(j=0; j<= lg; j++) { */
  734: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  735: /*   } */
  736: /* } */
  737: 
  738: /********************** nrerror ********************/
  739: 
  740: void nrerror(char error_text[])
  741: {
  742:   fprintf(stderr,"ERREUR ...\n");
  743:   fprintf(stderr,"%s\n",error_text);
  744:   exit(EXIT_FAILURE);
  745: }
  746: /*********************** vector *******************/
  747: double *vector(int nl, int nh)
  748: {
  749:   double *v;
  750:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  751:   if (!v) nrerror("allocation failure in vector");
  752:   return v-nl+NR_END;
  753: }
  754: 
  755: /************************ free vector ******************/
  756: void free_vector(double*v, int nl, int nh)
  757: {
  758:   free((FREE_ARG)(v+nl-NR_END));
  759: }
  760: 
  761: /************************ivector *******************************/
  762: int *ivector(long nl,long nh)
  763: {
  764:   int *v;
  765:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  766:   if (!v) nrerror("allocation failure in ivector");
  767:   return v-nl+NR_END;
  768: }
  769: 
  770: /******************free ivector **************************/
  771: void free_ivector(int *v, long nl, long nh)
  772: {
  773:   free((FREE_ARG)(v+nl-NR_END));
  774: }
  775: 
  776: /************************lvector *******************************/
  777: long *lvector(long nl,long nh)
  778: {
  779:   long *v;
  780:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  781:   if (!v) nrerror("allocation failure in ivector");
  782:   return v-nl+NR_END;
  783: }
  784: 
  785: /******************free lvector **************************/
  786: void free_lvector(long *v, long nl, long nh)
  787: {
  788:   free((FREE_ARG)(v+nl-NR_END));
  789: }
  790: 
  791: /******************* imatrix *******************************/
  792: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  793:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  794: { 
  795:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  796:   int **m; 
  797:   
  798:   /* allocate pointers to rows */ 
  799:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  800:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  801:   m += NR_END; 
  802:   m -= nrl; 
  803:   
  804:   
  805:   /* allocate rows and set pointers to them */ 
  806:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  807:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  808:   m[nrl] += NR_END; 
  809:   m[nrl] -= ncl; 
  810:   
  811:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  812:   
  813:   /* return pointer to array of pointers to rows */ 
  814:   return m; 
  815: } 
  816: 
  817: /****************** free_imatrix *************************/
  818: void free_imatrix(m,nrl,nrh,ncl,nch)
  819:       int **m;
  820:       long nch,ncl,nrh,nrl; 
  821:      /* free an int matrix allocated by imatrix() */ 
  822: { 
  823:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
  824:   free((FREE_ARG) (m+nrl-NR_END)); 
  825: } 
  826: 
  827: /******************* matrix *******************************/
  828: double **matrix(long nrl, long nrh, long ncl, long nch)
  829: {
  830:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
  831:   double **m;
  832: 
  833:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  834:   if (!m) nrerror("allocation failure 1 in matrix()");
  835:   m += NR_END;
  836:   m -= nrl;
  837: 
  838:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  839:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  840:   m[nrl] += NR_END;
  841:   m[nrl] -= ncl;
  842: 
  843:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  844:   return m;
  845:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
  846:    */
  847: }
  848: 
  849: /*************************free matrix ************************/
  850: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
  851: {
  852:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  853:   free((FREE_ARG)(m+nrl-NR_END));
  854: }
  855: 
  856: /******************* ma3x *******************************/
  857: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
  858: {
  859:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
  860:   double ***m;
  861: 
  862:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
  863:   if (!m) nrerror("allocation failure 1 in matrix()");
  864:   m += NR_END;
  865:   m -= nrl;
  866: 
  867:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
  868:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
  869:   m[nrl] += NR_END;
  870:   m[nrl] -= ncl;
  871: 
  872:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
  873: 
  874:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
  875:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
  876:   m[nrl][ncl] += NR_END;
  877:   m[nrl][ncl] -= nll;
  878:   for (j=ncl+1; j<=nch; j++) 
  879:     m[nrl][j]=m[nrl][j-1]+nlay;
  880:   
  881:   for (i=nrl+1; i<=nrh; i++) {
  882:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
  883:     for (j=ncl+1; j<=nch; j++) 
  884:       m[i][j]=m[i][j-1]+nlay;
  885:   }
  886:   return m; 
  887:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
  888:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
  889:   */
  890: }
  891: 
  892: /*************************free ma3x ************************/
  893: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
  894: {
  895:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
  896:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
  897:   free((FREE_ARG)(m+nrl-NR_END));
  898: }
  899: 
  900: /*************** function subdirf ***********/
  901: char *subdirf(char fileres[])
  902: {
  903:   /* Caution optionfilefiname is hidden */
  904:   strcpy(tmpout,optionfilefiname);
  905:   strcat(tmpout,"/"); /* Add to the right */
  906:   strcat(tmpout,fileres);
  907:   return tmpout;
  908: }
  909: 
  910: /*************** function subdirf2 ***********/
  911: char *subdirf2(char fileres[], char *preop)
  912: {
  913:   
  914:   /* Caution optionfilefiname is hidden */
  915:   strcpy(tmpout,optionfilefiname);
  916:   strcat(tmpout,"/");
  917:   strcat(tmpout,preop);
  918:   strcat(tmpout,fileres);
  919:   return tmpout;
  920: }
  921: 
  922: /*************** function subdirf3 ***********/
  923: char *subdirf3(char fileres[], char *preop, char *preop2)
  924: {
  925:   
  926:   /* Caution optionfilefiname is hidden */
  927:   strcpy(tmpout,optionfilefiname);
  928:   strcat(tmpout,"/");
  929:   strcat(tmpout,preop);
  930:   strcat(tmpout,preop2);
  931:   strcat(tmpout,fileres);
  932:   return tmpout;
  933: }
  934: 
  935: /***************** f1dim *************************/
  936: extern int ncom; 
  937: extern double *pcom,*xicom;
  938: extern double (*nrfunc)(double []); 
  939:  
  940: double f1dim(double x) 
  941: { 
  942:   int j; 
  943:   double f;
  944:   double *xt; 
  945:  
  946:   xt=vector(1,ncom); 
  947:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
  948:   f=(*nrfunc)(xt); 
  949:   free_vector(xt,1,ncom); 
  950:   return f; 
  951: } 
  952: 
  953: /*****************brent *************************/
  954: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
  955: { 
  956:   int iter; 
  957:   double a,b,d,etemp;
  958:   double fu,fv,fw,fx;
  959:   double ftemp;
  960:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
  961:   double e=0.0; 
  962:  
  963:   a=(ax < cx ? ax : cx); 
  964:   b=(ax > cx ? ax : cx); 
  965:   x=w=v=bx; 
  966:   fw=fv=fx=(*f)(x); 
  967:   for (iter=1;iter<=ITMAX;iter++) { 
  968:     xm=0.5*(a+b); 
  969:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
  970:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
  971:     printf(".");fflush(stdout);
  972:     fprintf(ficlog,".");fflush(ficlog);
  973: #ifdef DEBUG
  974:     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);
  975:     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);
  976:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
  977: #endif
  978:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
  979:       *xmin=x; 
  980:       return fx; 
  981:     } 
  982:     ftemp=fu;
  983:     if (fabs(e) > tol1) { 
  984:       r=(x-w)*(fx-fv); 
  985:       q=(x-v)*(fx-fw); 
  986:       p=(x-v)*q-(x-w)*r; 
  987:       q=2.0*(q-r); 
  988:       if (q > 0.0) p = -p; 
  989:       q=fabs(q); 
  990:       etemp=e; 
  991:       e=d; 
  992:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
  993: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
  994:       else { 
  995: 	d=p/q; 
  996: 	u=x+d; 
  997: 	if (u-a < tol2 || b-u < tol2) 
  998: 	  d=SIGN(tol1,xm-x); 
  999:       } 
 1000:     } else { 
 1001:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1002:     } 
 1003:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1004:     fu=(*f)(u); 
 1005:     if (fu <= fx) { 
 1006:       if (u >= x) a=x; else b=x; 
 1007:       SHFT(v,w,x,u) 
 1008: 	SHFT(fv,fw,fx,fu) 
 1009: 	} else { 
 1010: 	  if (u < x) a=u; else b=u; 
 1011: 	  if (fu <= fw || w == x) { 
 1012: 	    v=w; 
 1013: 	    w=u; 
 1014: 	    fv=fw; 
 1015: 	    fw=fu; 
 1016: 	  } else if (fu <= fv || v == x || v == w) { 
 1017: 	    v=u; 
 1018: 	    fv=fu; 
 1019: 	  } 
 1020: 	} 
 1021:   } 
 1022:   nrerror("Too many iterations in brent"); 
 1023:   *xmin=x; 
 1024:   return fx; 
 1025: } 
 1026: 
 1027: /****************** mnbrak ***********************/
 1028: 
 1029: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1030: 	    double (*func)(double)) 
 1031: { 
 1032:   double ulim,u,r,q, dum;
 1033:   double fu; 
 1034:  
 1035:   *fa=(*func)(*ax); 
 1036:   *fb=(*func)(*bx); 
 1037:   if (*fb > *fa) { 
 1038:     SHFT(dum,*ax,*bx,dum) 
 1039:       SHFT(dum,*fb,*fa,dum) 
 1040:       } 
 1041:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1042:   *fc=(*func)(*cx); 
 1043:   while (*fb > *fc) { 
 1044:     r=(*bx-*ax)*(*fb-*fc); 
 1045:     q=(*bx-*cx)*(*fb-*fa); 
 1046:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1047:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
 1048:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
 1049:     if ((*bx-u)*(u-*cx) > 0.0) { 
 1050:       fu=(*func)(u); 
 1051:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
 1052:       fu=(*func)(u); 
 1053:       if (fu < *fc) { 
 1054: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1055: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1056: 	  } 
 1057:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
 1058:       u=ulim; 
 1059:       fu=(*func)(u); 
 1060:     } else { 
 1061:       u=(*cx)+GOLD*(*cx-*bx); 
 1062:       fu=(*func)(u); 
 1063:     } 
 1064:     SHFT(*ax,*bx,*cx,u) 
 1065:       SHFT(*fa,*fb,*fc,fu) 
 1066:       } 
 1067: } 
 1068: 
 1069: /*************** linmin ************************/
 1070: 
 1071: int ncom; 
 1072: double *pcom,*xicom;
 1073: double (*nrfunc)(double []); 
 1074:  
 1075: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1076: { 
 1077:   double brent(double ax, double bx, double cx, 
 1078: 	       double (*f)(double), double tol, double *xmin); 
 1079:   double f1dim(double x); 
 1080:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1081: 	      double *fc, double (*func)(double)); 
 1082:   int j; 
 1083:   double xx,xmin,bx,ax; 
 1084:   double fx,fb,fa;
 1085:  
 1086:   ncom=n; 
 1087:   pcom=vector(1,n); 
 1088:   xicom=vector(1,n); 
 1089:   nrfunc=func; 
 1090:   for (j=1;j<=n;j++) { 
 1091:     pcom[j]=p[j]; 
 1092:     xicom[j]=xi[j]; 
 1093:   } 
 1094:   ax=0.0; 
 1095:   xx=1.0; 
 1096:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
 1097:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
 1098: #ifdef DEBUG
 1099:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1100:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1101: #endif
 1102:   for (j=1;j<=n;j++) { 
 1103:     xi[j] *= xmin; 
 1104:     p[j] += xi[j]; 
 1105:   } 
 1106:   free_vector(xicom,1,n); 
 1107:   free_vector(pcom,1,n); 
 1108: } 
 1109: 
 1110: char *asc_diff_time(long time_sec, char ascdiff[])
 1111: {
 1112:   long sec_left, days, hours, minutes;
 1113:   days = (time_sec) / (60*60*24);
 1114:   sec_left = (time_sec) % (60*60*24);
 1115:   hours = (sec_left) / (60*60) ;
 1116:   sec_left = (sec_left) %(60*60);
 1117:   minutes = (sec_left) /60;
 1118:   sec_left = (sec_left) % (60);
 1119:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1120:   return ascdiff;
 1121: }
 1122: 
 1123: /*************** powell ************************/
 1124: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1125: 	    double (*func)(double [])) 
 1126: { 
 1127:   void linmin(double p[], double xi[], int n, double *fret, 
 1128: 	      double (*func)(double [])); 
 1129:   int i,ibig,j; 
 1130:   double del,t,*pt,*ptt,*xit;
 1131:   double fp,fptt;
 1132:   double *xits;
 1133:   int niterf, itmp;
 1134: 
 1135:   pt=vector(1,n); 
 1136:   ptt=vector(1,n); 
 1137:   xit=vector(1,n); 
 1138:   xits=vector(1,n); 
 1139:   *fret=(*func)(p); 
 1140:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1141:   for (*iter=1;;++(*iter)) { 
 1142:     fp=(*fret); 
 1143:     ibig=0; 
 1144:     del=0.0; 
 1145:     last_time=curr_time;
 1146:     (void) gettimeofday(&curr_time,&tzp);
 1147:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
 1148:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
 1149: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
 1150:    for (i=1;i<=n;i++) {
 1151:       printf(" %d %.12f",i, p[i]);
 1152:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1153:       fprintf(ficrespow," %.12lf", p[i]);
 1154:     }
 1155:     printf("\n");
 1156:     fprintf(ficlog,"\n");
 1157:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1158:     if(*iter <=3){
 1159:       tm = *localtime(&curr_time.tv_sec);
 1160:       strcpy(strcurr,asctime(&tm));
 1161: /*       asctime_r(&tm,strcurr); */
 1162:       forecast_time=curr_time; 
 1163:       itmp = strlen(strcurr);
 1164:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1165: 	strcurr[itmp-1]='\0';
 1166:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 1167:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
 1168:       for(niterf=10;niterf<=30;niterf+=10){
 1169: 	forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
 1170: 	tmf = *localtime(&forecast_time.tv_sec);
 1171: /* 	asctime_r(&tmf,strfor); */
 1172: 	strcpy(strfor,asctime(&tmf));
 1173: 	itmp = strlen(strfor);
 1174: 	if(strfor[itmp-1]=='\n')
 1175: 	strfor[itmp-1]='\0';
 1176: 	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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
 1177: 	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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
 1178:       }
 1179:     }
 1180:     for (i=1;i<=n;i++) { 
 1181:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1182:       fptt=(*fret); 
 1183: #ifdef DEBUG
 1184:       printf("fret=%lf \n",*fret);
 1185:       fprintf(ficlog,"fret=%lf \n",*fret);
 1186: #endif
 1187:       printf("%d",i);fflush(stdout);
 1188:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1189:       linmin(p,xit,n,fret,func); 
 1190:       if (fabs(fptt-(*fret)) > del) { 
 1191: 	del=fabs(fptt-(*fret)); 
 1192: 	ibig=i; 
 1193:       } 
 1194: #ifdef DEBUG
 1195:       printf("%d %.12e",i,(*fret));
 1196:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1197:       for (j=1;j<=n;j++) {
 1198: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1199: 	printf(" x(%d)=%.12e",j,xit[j]);
 1200: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1201:       }
 1202:       for(j=1;j<=n;j++) {
 1203: 	printf(" p=%.12e",p[j]);
 1204: 	fprintf(ficlog," p=%.12e",p[j]);
 1205:       }
 1206:       printf("\n");
 1207:       fprintf(ficlog,"\n");
 1208: #endif
 1209:     } 
 1210:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1211: #ifdef DEBUG
 1212:       int k[2],l;
 1213:       k[0]=1;
 1214:       k[1]=-1;
 1215:       printf("Max: %.12e",(*func)(p));
 1216:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1217:       for (j=1;j<=n;j++) {
 1218: 	printf(" %.12e",p[j]);
 1219: 	fprintf(ficlog," %.12e",p[j]);
 1220:       }
 1221:       printf("\n");
 1222:       fprintf(ficlog,"\n");
 1223:       for(l=0;l<=1;l++) {
 1224: 	for (j=1;j<=n;j++) {
 1225: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1226: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1227: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1228: 	}
 1229: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1230: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1231:       }
 1232: #endif
 1233: 
 1234: 
 1235:       free_vector(xit,1,n); 
 1236:       free_vector(xits,1,n); 
 1237:       free_vector(ptt,1,n); 
 1238:       free_vector(pt,1,n); 
 1239:       return; 
 1240:     } 
 1241:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1242:     for (j=1;j<=n;j++) { 
 1243:       ptt[j]=2.0*p[j]-pt[j]; 
 1244:       xit[j]=p[j]-pt[j]; 
 1245:       pt[j]=p[j]; 
 1246:     } 
 1247:     fptt=(*func)(ptt); 
 1248:     if (fptt < fp) { 
 1249:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
 1250:       if (t < 0.0) { 
 1251: 	linmin(p,xit,n,fret,func); 
 1252: 	for (j=1;j<=n;j++) { 
 1253: 	  xi[j][ibig]=xi[j][n]; 
 1254: 	  xi[j][n]=xit[j]; 
 1255: 	}
 1256: #ifdef DEBUG
 1257: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1258: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1259: 	for(j=1;j<=n;j++){
 1260: 	  printf(" %.12e",xit[j]);
 1261: 	  fprintf(ficlog," %.12e",xit[j]);
 1262: 	}
 1263: 	printf("\n");
 1264: 	fprintf(ficlog,"\n");
 1265: #endif
 1266:       }
 1267:     } 
 1268:   } 
 1269: } 
 1270: 
 1271: /**** Prevalence limit (stable or period prevalence)  ****************/
 1272: 
 1273: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1274: {
 1275:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1276:      matrix by transitions matrix until convergence is reached */
 1277: 
 1278:   int i, ii,j,k;
 1279:   double min, max, maxmin, maxmax,sumnew=0.;
 1280:   double **matprod2();
 1281:   double **out, cov[NCOVMAX+1], **pmij();
 1282:   double **newm;
 1283:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1284: 
 1285:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1286:     for (j=1;j<=nlstate+ndeath;j++){
 1287:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1288:     }
 1289: 
 1290:    cov[1]=1.;
 1291:  
 1292:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1293:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1294:     newm=savm;
 1295:     /* Covariates have to be included here again */
 1296:     cov[2]=agefin;
 1297:     
 1298:     for (k=1; k<=cptcovn;k++) {
 1299:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1300:       /*	printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
 1301:     }
 1302:     for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1303:     for (k=1; k<=cptcovprod;k++)
 1304:       cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1305:     
 1306:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1307:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1308:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1309:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1310:     
 1311:     savm=oldm;
 1312:     oldm=newm;
 1313:     maxmax=0.;
 1314:     for(j=1;j<=nlstate;j++){
 1315:       min=1.;
 1316:       max=0.;
 1317:       for(i=1; i<=nlstate; i++) {
 1318: 	sumnew=0;
 1319: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1320: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1321: 	max=FMAX(max,prlim[i][j]);
 1322: 	min=FMIN(min,prlim[i][j]);
 1323:       }
 1324:       maxmin=max-min;
 1325:       maxmax=FMAX(maxmax,maxmin);
 1326:     }
 1327:     if(maxmax < ftolpl){
 1328:       return prlim;
 1329:     }
 1330:   }
 1331: }
 1332: 
 1333: /*************** transition probabilities ***************/ 
 1334: 
 1335: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1336: {
 1337:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1338:      computes the probability to be observed in state j being in state i by appying the
 1339:      model to the ncovmodel covariates (including constant and age).
 1340:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1341:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1342:      ncth covariate in the global vector x is given by the formula:
 1343:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1344:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1345:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1346:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1347:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1348:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1349:   */
 1350:   double s1, lnpijopii;
 1351:   /*double t34;*/
 1352:   int i,j,j1, nc, ii, jj;
 1353: 
 1354:     for(i=1; i<= nlstate; i++){
 1355:       for(j=1; j<i;j++){
 1356: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1357: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1358: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1359: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1360: 	}
 1361: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1362: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1363:       }
 1364:       for(j=i+1; j<=nlstate+ndeath;j++){
 1365: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1366: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1367: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1368: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1369: 	}
 1370: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1371:       }
 1372:     }
 1373:     
 1374:     for(i=1; i<= nlstate; i++){
 1375:       s1=0;
 1376:       for(j=1; j<i; j++){
 1377: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1378: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1379:       }
 1380:       for(j=i+1; j<=nlstate+ndeath; j++){
 1381: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1382: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1383:       }
 1384:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1385:       ps[i][i]=1./(s1+1.);
 1386:       /* Computing other pijs */
 1387:       for(j=1; j<i; j++)
 1388: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1389:       for(j=i+1; j<=nlstate+ndeath; j++)
 1390: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1391:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1392:     } /* end i */
 1393:     
 1394:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1395:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1396: 	ps[ii][jj]=0;
 1397: 	ps[ii][ii]=1;
 1398:       }
 1399:     }
 1400:     
 1401: 
 1402: /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1403: /* 	 for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1404: /* 	   printf("ddd %lf ",ps[ii][jj]); */
 1405: /* 	 } */
 1406: /* 	 printf("\n "); */
 1407: /*        } */
 1408: /*        printf("\n ");printf("%lf ",cov[2]); */
 1409:        /*
 1410:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1411:       goto end;*/
 1412:     return ps;
 1413: }
 1414: 
 1415: /**************** Product of 2 matrices ******************/
 1416: 
 1417: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
 1418: {
 1419:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1420:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1421:   /* in, b, out are matrice of pointers which should have been initialized 
 1422:      before: only the contents of out is modified. The function returns
 1423:      a pointer to pointers identical to out */
 1424:   long i, j, k;
 1425:   for(i=nrl; i<= nrh; i++)
 1426:     for(k=ncolol; k<=ncoloh; k++)
 1427:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
 1428: 	out[i][k] +=in[i][j]*b[j][k];
 1429: 
 1430:   return out;
 1431: }
 1432: 
 1433: 
 1434: /************* Higher Matrix Product ***************/
 1435: 
 1436: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1437: {
 1438:   /* Computes the transition matrix starting at age 'age' over 
 1439:      'nhstepm*hstepm*stepm' months (i.e. until
 1440:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1441:      nhstepm*hstepm matrices. 
 1442:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1443:      (typically every 2 years instead of every month which is too big 
 1444:      for the memory).
 1445:      Model is determined by parameters x and covariates have to be 
 1446:      included manually here. 
 1447: 
 1448:      */
 1449: 
 1450:   int i, j, d, h, k;
 1451:   double **out, cov[NCOVMAX+1];
 1452:   double **newm;
 1453: 
 1454:   /* Hstepm could be zero and should return the unit matrix */
 1455:   for (i=1;i<=nlstate+ndeath;i++)
 1456:     for (j=1;j<=nlstate+ndeath;j++){
 1457:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1458:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1459:     }
 1460:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1461:   for(h=1; h <=nhstepm; h++){
 1462:     for(d=1; d <=hstepm; d++){
 1463:       newm=savm;
 1464:       /* Covariates have to be included here again */
 1465:       cov[1]=1.;
 1466:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1467:       for (k=1; k<=cptcovn;k++) 
 1468: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1469:       for (k=1; k<=cptcovage;k++)
 1470: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1471:       for (k=1; k<=cptcovprod;k++)
 1472: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1473: 
 1474: 
 1475:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1476:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1477:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1478: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1479:       savm=oldm;
 1480:       oldm=newm;
 1481:     }
 1482:     for(i=1; i<=nlstate+ndeath; i++)
 1483:       for(j=1;j<=nlstate+ndeath;j++) {
 1484: 	po[i][j][h]=newm[i][j];
 1485: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1486:       }
 1487:     /*printf("h=%d ",h);*/
 1488:   } /* end h */
 1489: /*     printf("\n H=%d \n",h); */
 1490:   return po;
 1491: }
 1492: 
 1493: 
 1494: /*************** log-likelihood *************/
 1495: double func( double *x)
 1496: {
 1497:   int i, ii, j, k, mi, d, kk;
 1498:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1499:   double **out;
 1500:   double sw; /* Sum of weights */
 1501:   double lli; /* Individual log likelihood */
 1502:   int s1, s2;
 1503:   double bbh, survp;
 1504:   long ipmx;
 1505:   /*extern weight */
 1506:   /* We are differentiating ll according to initial status */
 1507:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1508:   /*for(i=1;i<imx;i++) 
 1509:     printf(" %d\n",s[4][i]);
 1510:   */
 1511:   cov[1]=1.;
 1512: 
 1513:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1514: 
 1515:   if(mle==1){
 1516:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1517:       /* Computes the values of the ncovmodel covariates of the model
 1518: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1519: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1520: 	 to be observed in j being in i according to the model.
 1521:        */
 1522:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1523:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1524: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1525: 	 has been calculated etc */
 1526:       for(mi=1; mi<= wav[i]-1; mi++){
 1527: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1528: 	  for (j=1;j<=nlstate+ndeath;j++){
 1529: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1530: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1531: 	  }
 1532: 	for(d=0; d<dh[mi][i]; d++){
 1533: 	  newm=savm;
 1534: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1535: 	  for (kk=1; kk<=cptcovage;kk++) {
 1536: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1537: 	  }
 1538: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1539: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1540: 	  savm=oldm;
 1541: 	  oldm=newm;
 1542: 	} /* end mult */
 1543:       
 1544: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1545: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1546: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1547: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1548: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1549: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1550: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1551: 	 * probability in order to take into account the bias as a fraction of the way
 1552: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1553: 	 * -stepm/2 to stepm/2 .
 1554: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1555: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1556: 	 */
 1557: 	s1=s[mw[mi][i]][i];
 1558: 	s2=s[mw[mi+1][i]][i];
 1559: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1560: 	/* bias bh is positive if real duration
 1561: 	 * is higher than the multiple of stepm and negative otherwise.
 1562: 	 */
 1563: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1564: 	if( s2 > nlstate){ 
 1565: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1566: 	     then the contribution to the likelihood is the probability to 
 1567: 	     die between last step unit time and current  step unit time, 
 1568: 	     which is also equal to probability to die before dh 
 1569: 	     minus probability to die before dh-stepm . 
 1570: 	     In version up to 0.92 likelihood was computed
 1571: 	as if date of death was unknown. Death was treated as any other
 1572: 	health state: the date of the interview describes the actual state
 1573: 	and not the date of a change in health state. The former idea was
 1574: 	to consider that at each interview the state was recorded
 1575: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1576: 	introduced the exact date of death then we should have modified
 1577: 	the contribution of an exact death to the likelihood. This new
 1578: 	contribution is smaller and very dependent of the step unit
 1579: 	stepm. It is no more the probability to die between last interview
 1580: 	and month of death but the probability to survive from last
 1581: 	interview up to one month before death multiplied by the
 1582: 	probability to die within a month. Thanks to Chris
 1583: 	Jackson for correcting this bug.  Former versions increased
 1584: 	mortality artificially. The bad side is that we add another loop
 1585: 	which slows down the processing. The difference can be up to 10%
 1586: 	lower mortality.
 1587: 	  */
 1588: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1589: 
 1590: 
 1591: 	} else if  (s2==-2) {
 1592: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1593: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1594: 	  /*survp += out[s1][j]; */
 1595: 	  lli= log(survp);
 1596: 	}
 1597: 	
 1598:  	else if  (s2==-4) { 
 1599: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1600: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1601:  	  lli= log(survp); 
 1602:  	} 
 1603: 
 1604:  	else if  (s2==-5) { 
 1605:  	  for (j=1,survp=0. ; j<=2; j++)  
 1606: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1607:  	  lli= log(survp); 
 1608:  	} 
 1609: 	
 1610: 	else{
 1611: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1612: 	  /*  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 */
 1613: 	} 
 1614: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1615: 	/*if(lli ==000.0)*/
 1616: 	/*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); */
 1617:   	ipmx +=1;
 1618: 	sw += weight[i];
 1619: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1620:       } /* end of wave */
 1621:     } /* end of individual */
 1622:   }  else if(mle==2){
 1623:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1624:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1625:       for(mi=1; mi<= wav[i]-1; mi++){
 1626: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1627: 	  for (j=1;j<=nlstate+ndeath;j++){
 1628: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1629: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1630: 	  }
 1631: 	for(d=0; d<=dh[mi][i]; d++){
 1632: 	  newm=savm;
 1633: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1634: 	  for (kk=1; kk<=cptcovage;kk++) {
 1635: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1636: 	  }
 1637: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1638: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1639: 	  savm=oldm;
 1640: 	  oldm=newm;
 1641: 	} /* end mult */
 1642:       
 1643: 	s1=s[mw[mi][i]][i];
 1644: 	s2=s[mw[mi+1][i]][i];
 1645: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1646: 	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 */
 1647: 	ipmx +=1;
 1648: 	sw += weight[i];
 1649: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1650:       } /* end of wave */
 1651:     } /* end of individual */
 1652:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1653:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1654:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1655:       for(mi=1; mi<= wav[i]-1; mi++){
 1656: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1657: 	  for (j=1;j<=nlstate+ndeath;j++){
 1658: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1659: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1660: 	  }
 1661: 	for(d=0; d<dh[mi][i]; d++){
 1662: 	  newm=savm;
 1663: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1664: 	  for (kk=1; kk<=cptcovage;kk++) {
 1665: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1666: 	  }
 1667: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1668: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1669: 	  savm=oldm;
 1670: 	  oldm=newm;
 1671: 	} /* end mult */
 1672:       
 1673: 	s1=s[mw[mi][i]][i];
 1674: 	s2=s[mw[mi+1][i]][i];
 1675: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1676: 	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 */
 1677: 	ipmx +=1;
 1678: 	sw += weight[i];
 1679: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1680:       } /* end of wave */
 1681:     } /* end of individual */
 1682:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1683:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1684:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1685:       for(mi=1; mi<= wav[i]-1; mi++){
 1686: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1687: 	  for (j=1;j<=nlstate+ndeath;j++){
 1688: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1689: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1690: 	  }
 1691: 	for(d=0; d<dh[mi][i]; d++){
 1692: 	  newm=savm;
 1693: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1694: 	  for (kk=1; kk<=cptcovage;kk++) {
 1695: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1696: 	  }
 1697: 	
 1698: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1699: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1700: 	  savm=oldm;
 1701: 	  oldm=newm;
 1702: 	} /* end mult */
 1703:       
 1704: 	s1=s[mw[mi][i]][i];
 1705: 	s2=s[mw[mi+1][i]][i];
 1706: 	if( s2 > nlstate){ 
 1707: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1708: 	}else{
 1709: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1710: 	}
 1711: 	ipmx +=1;
 1712: 	sw += weight[i];
 1713: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1714: /* 	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]); */
 1715:       } /* end of wave */
 1716:     } /* end of individual */
 1717:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 1718:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1719:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1720:       for(mi=1; mi<= wav[i]-1; mi++){
 1721: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1722: 	  for (j=1;j<=nlstate+ndeath;j++){
 1723: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1724: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1725: 	  }
 1726: 	for(d=0; d<dh[mi][i]; d++){
 1727: 	  newm=savm;
 1728: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1729: 	  for (kk=1; kk<=cptcovage;kk++) {
 1730: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1731: 	  }
 1732: 	
 1733: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1734: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1735: 	  savm=oldm;
 1736: 	  oldm=newm;
 1737: 	} /* end mult */
 1738:       
 1739: 	s1=s[mw[mi][i]][i];
 1740: 	s2=s[mw[mi+1][i]][i];
 1741: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1742: 	ipmx +=1;
 1743: 	sw += weight[i];
 1744: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1745: 	/*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]);*/
 1746:       } /* end of wave */
 1747:     } /* end of individual */
 1748:   } /* End of if */
 1749:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1750:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1751:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1752:   return -l;
 1753: }
 1754: 
 1755: /*************** log-likelihood *************/
 1756: double funcone( double *x)
 1757: {
 1758:   /* Same as likeli but slower because of a lot of printf and if */
 1759:   int i, ii, j, k, mi, d, kk;
 1760:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1761:   double **out;
 1762:   double lli; /* Individual log likelihood */
 1763:   double llt;
 1764:   int s1, s2;
 1765:   double bbh, survp;
 1766:   /*extern weight */
 1767:   /* We are differentiating ll according to initial status */
 1768:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1769:   /*for(i=1;i<imx;i++) 
 1770:     printf(" %d\n",s[4][i]);
 1771:   */
 1772:   cov[1]=1.;
 1773: 
 1774:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1775: 
 1776:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1777:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1778:     for(mi=1; mi<= wav[i]-1; mi++){
 1779:       for (ii=1;ii<=nlstate+ndeath;ii++)
 1780: 	for (j=1;j<=nlstate+ndeath;j++){
 1781: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1782: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1783: 	}
 1784:       for(d=0; d<dh[mi][i]; d++){
 1785: 	newm=savm;
 1786: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1787: 	for (kk=1; kk<=cptcovage;kk++) {
 1788: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1789: 	}
 1790: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1791: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1792: 	savm=oldm;
 1793: 	oldm=newm;
 1794:       } /* end mult */
 1795:       
 1796:       s1=s[mw[mi][i]][i];
 1797:       s2=s[mw[mi+1][i]][i];
 1798:       bbh=(double)bh[mi][i]/(double)stepm; 
 1799:       /* bias is positive if real duration
 1800:        * is higher than the multiple of stepm and negative otherwise.
 1801:        */
 1802:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 1803: 	lli=log(out[s1][s2] - savm[s1][s2]);
 1804:       } else if  (s2==-2) {
 1805: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 1806: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1807: 	lli= log(survp);
 1808:       }else if (mle==1){
 1809: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1810:       } else if(mle==2){
 1811: 	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 */
 1812:       } else if(mle==3){  /* exponential inter-extrapolation */
 1813: 	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 */
 1814:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 1815: 	lli=log(out[s1][s2]); /* Original formula */
 1816:       } else{  /* mle=0 back to 1 */
 1817: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1818: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 1819:       } /* End of if */
 1820:       ipmx +=1;
 1821:       sw += weight[i];
 1822:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1823:       /*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]); */
 1824:       if(globpr){
 1825: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 1826:  %11.6f %11.6f %11.6f ", \
 1827: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 1828: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 1829: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 1830: 	  llt +=ll[k]*gipmx/gsw;
 1831: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 1832: 	}
 1833: 	fprintf(ficresilk," %10.6f\n", -llt);
 1834:       }
 1835:     } /* end of wave */
 1836:   } /* end of individual */
 1837:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 1838:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 1839:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 1840:   if(globpr==0){ /* First time we count the contributions and weights */
 1841:     gipmx=ipmx;
 1842:     gsw=sw;
 1843:   }
 1844:   return -l;
 1845: }
 1846: 
 1847: 
 1848: /*************** function likelione ***********/
 1849: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 1850: {
 1851:   /* This routine should help understanding what is done with 
 1852:      the selection of individuals/waves and
 1853:      to check the exact contribution to the likelihood.
 1854:      Plotting could be done.
 1855:    */
 1856:   int k;
 1857: 
 1858:   if(*globpri !=0){ /* Just counts and sums, no printings */
 1859:     strcpy(fileresilk,"ilk"); 
 1860:     strcat(fileresilk,fileres);
 1861:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 1862:       printf("Problem with resultfile: %s\n", fileresilk);
 1863:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 1864:     }
 1865:     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");
 1866:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 1867:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 1868:     for(k=1; k<=nlstate; k++) 
 1869:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 1870:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 1871:   }
 1872: 
 1873:   *fretone=(*funcone)(p);
 1874:   if(*globpri !=0){
 1875:     fclose(ficresilk);
 1876:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 1877:     fflush(fichtm); 
 1878:   } 
 1879:   return;
 1880: }
 1881: 
 1882: 
 1883: /*********** Maximum Likelihood Estimation ***************/
 1884: 
 1885: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 1886: {
 1887:   int i,j, iter;
 1888:   double **xi;
 1889:   double fret;
 1890:   double fretone; /* Only one call to likelihood */
 1891:   /*  char filerespow[FILENAMELENGTH];*/
 1892:   xi=matrix(1,npar,1,npar);
 1893:   for (i=1;i<=npar;i++)
 1894:     for (j=1;j<=npar;j++)
 1895:       xi[i][j]=(i==j ? 1.0 : 0.0);
 1896:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 1897:   strcpy(filerespow,"pow"); 
 1898:   strcat(filerespow,fileres);
 1899:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 1900:     printf("Problem with resultfile: %s\n", filerespow);
 1901:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 1902:   }
 1903:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 1904:   for (i=1;i<=nlstate;i++)
 1905:     for(j=1;j<=nlstate+ndeath;j++)
 1906:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 1907:   fprintf(ficrespow,"\n");
 1908: 
 1909:   powell(p,xi,npar,ftol,&iter,&fret,func);
 1910: 
 1911:   free_matrix(xi,1,npar,1,npar);
 1912:   fclose(ficrespow);
 1913:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
 1914:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1915:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
 1916: 
 1917: }
 1918: 
 1919: /**** Computes Hessian and covariance matrix ***/
 1920: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 1921: {
 1922:   double  **a,**y,*x,pd;
 1923:   double **hess;
 1924:   int i, j,jk;
 1925:   int *indx;
 1926: 
 1927:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 1928:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 1929:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 1930:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 1931:   double gompertz(double p[]);
 1932:   hess=matrix(1,npar,1,npar);
 1933: 
 1934:   printf("\nCalculation of the hessian matrix. Wait...\n");
 1935:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 1936:   for (i=1;i<=npar;i++){
 1937:     printf("%d",i);fflush(stdout);
 1938:     fprintf(ficlog,"%d",i);fflush(ficlog);
 1939:    
 1940:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 1941:     
 1942:     /*  printf(" %f ",p[i]);
 1943: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 1944:   }
 1945:   
 1946:   for (i=1;i<=npar;i++) {
 1947:     for (j=1;j<=npar;j++)  {
 1948:       if (j>i) { 
 1949: 	printf(".%d%d",i,j);fflush(stdout);
 1950: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 1951: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 1952: 	
 1953: 	hess[j][i]=hess[i][j];    
 1954: 	/*printf(" %lf ",hess[i][j]);*/
 1955:       }
 1956:     }
 1957:   }
 1958:   printf("\n");
 1959:   fprintf(ficlog,"\n");
 1960: 
 1961:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 1962:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 1963:   
 1964:   a=matrix(1,npar,1,npar);
 1965:   y=matrix(1,npar,1,npar);
 1966:   x=vector(1,npar);
 1967:   indx=ivector(1,npar);
 1968:   for (i=1;i<=npar;i++)
 1969:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 1970:   ludcmp(a,npar,indx,&pd);
 1971: 
 1972:   for (j=1;j<=npar;j++) {
 1973:     for (i=1;i<=npar;i++) x[i]=0;
 1974:     x[j]=1;
 1975:     lubksb(a,npar,indx,x);
 1976:     for (i=1;i<=npar;i++){ 
 1977:       matcov[i][j]=x[i];
 1978:     }
 1979:   }
 1980: 
 1981:   printf("\n#Hessian matrix#\n");
 1982:   fprintf(ficlog,"\n#Hessian matrix#\n");
 1983:   for (i=1;i<=npar;i++) { 
 1984:     for (j=1;j<=npar;j++) { 
 1985:       printf("%.3e ",hess[i][j]);
 1986:       fprintf(ficlog,"%.3e ",hess[i][j]);
 1987:     }
 1988:     printf("\n");
 1989:     fprintf(ficlog,"\n");
 1990:   }
 1991: 
 1992:   /* Recompute Inverse */
 1993:   for (i=1;i<=npar;i++)
 1994:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 1995:   ludcmp(a,npar,indx,&pd);
 1996: 
 1997:   /*  printf("\n#Hessian matrix recomputed#\n");
 1998: 
 1999:   for (j=1;j<=npar;j++) {
 2000:     for (i=1;i<=npar;i++) x[i]=0;
 2001:     x[j]=1;
 2002:     lubksb(a,npar,indx,x);
 2003:     for (i=1;i<=npar;i++){ 
 2004:       y[i][j]=x[i];
 2005:       printf("%.3e ",y[i][j]);
 2006:       fprintf(ficlog,"%.3e ",y[i][j]);
 2007:     }
 2008:     printf("\n");
 2009:     fprintf(ficlog,"\n");
 2010:   }
 2011:   */
 2012: 
 2013:   free_matrix(a,1,npar,1,npar);
 2014:   free_matrix(y,1,npar,1,npar);
 2015:   free_vector(x,1,npar);
 2016:   free_ivector(indx,1,npar);
 2017:   free_matrix(hess,1,npar,1,npar);
 2018: 
 2019: 
 2020: }
 2021: 
 2022: /*************** hessian matrix ****************/
 2023: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2024: {
 2025:   int i;
 2026:   int l=1, lmax=20;
 2027:   double k1,k2;
 2028:   double p2[MAXPARM+1]; /* identical to x */
 2029:   double res;
 2030:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2031:   double fx;
 2032:   int k=0,kmax=10;
 2033:   double l1;
 2034: 
 2035:   fx=func(x);
 2036:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2037:   for(l=0 ; l <=lmax; l++){
 2038:     l1=pow(10,l);
 2039:     delts=delt;
 2040:     for(k=1 ; k <kmax; k=k+1){
 2041:       delt = delta*(l1*k);
 2042:       p2[theta]=x[theta] +delt;
 2043:       k1=func(p2)-fx;
 2044:       p2[theta]=x[theta]-delt;
 2045:       k2=func(p2)-fx;
 2046:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2047:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2048:       
 2049: #ifdef DEBUGHESS
 2050:       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);
 2051:       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);
 2052: #endif
 2053:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2054:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2055: 	k=kmax;
 2056:       }
 2057:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2058: 	k=kmax; l=lmax*10.;
 2059:       }
 2060:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2061: 	delts=delt;
 2062:       }
 2063:     }
 2064:   }
 2065:   delti[theta]=delts;
 2066:   return res; 
 2067:   
 2068: }
 2069: 
 2070: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2071: {
 2072:   int i;
 2073:   int l=1, l1, lmax=20;
 2074:   double k1,k2,k3,k4,res,fx;
 2075:   double p2[MAXPARM+1];
 2076:   int k;
 2077: 
 2078:   fx=func(x);
 2079:   for (k=1; k<=2; k++) {
 2080:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2081:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2082:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2083:     k1=func(p2)-fx;
 2084:   
 2085:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2086:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2087:     k2=func(p2)-fx;
 2088:   
 2089:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2090:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2091:     k3=func(p2)-fx;
 2092:   
 2093:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2094:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2095:     k4=func(p2)-fx;
 2096:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2097: #ifdef DEBUG
 2098:     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);
 2099:     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);
 2100: #endif
 2101:   }
 2102:   return res;
 2103: }
 2104: 
 2105: /************** Inverse of matrix **************/
 2106: void ludcmp(double **a, int n, int *indx, double *d) 
 2107: { 
 2108:   int i,imax,j,k; 
 2109:   double big,dum,sum,temp; 
 2110:   double *vv; 
 2111:  
 2112:   vv=vector(1,n); 
 2113:   *d=1.0; 
 2114:   for (i=1;i<=n;i++) { 
 2115:     big=0.0; 
 2116:     for (j=1;j<=n;j++) 
 2117:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2118:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2119:     vv[i]=1.0/big; 
 2120:   } 
 2121:   for (j=1;j<=n;j++) { 
 2122:     for (i=1;i<j;i++) { 
 2123:       sum=a[i][j]; 
 2124:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2125:       a[i][j]=sum; 
 2126:     } 
 2127:     big=0.0; 
 2128:     for (i=j;i<=n;i++) { 
 2129:       sum=a[i][j]; 
 2130:       for (k=1;k<j;k++) 
 2131: 	sum -= a[i][k]*a[k][j]; 
 2132:       a[i][j]=sum; 
 2133:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2134: 	big=dum; 
 2135: 	imax=i; 
 2136:       } 
 2137:     } 
 2138:     if (j != imax) { 
 2139:       for (k=1;k<=n;k++) { 
 2140: 	dum=a[imax][k]; 
 2141: 	a[imax][k]=a[j][k]; 
 2142: 	a[j][k]=dum; 
 2143:       } 
 2144:       *d = -(*d); 
 2145:       vv[imax]=vv[j]; 
 2146:     } 
 2147:     indx[j]=imax; 
 2148:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2149:     if (j != n) { 
 2150:       dum=1.0/(a[j][j]); 
 2151:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2152:     } 
 2153:   } 
 2154:   free_vector(vv,1,n);  /* Doesn't work */
 2155: ;
 2156: } 
 2157: 
 2158: void lubksb(double **a, int n, int *indx, double b[]) 
 2159: { 
 2160:   int i,ii=0,ip,j; 
 2161:   double sum; 
 2162:  
 2163:   for (i=1;i<=n;i++) { 
 2164:     ip=indx[i]; 
 2165:     sum=b[ip]; 
 2166:     b[ip]=b[i]; 
 2167:     if (ii) 
 2168:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2169:     else if (sum) ii=i; 
 2170:     b[i]=sum; 
 2171:   } 
 2172:   for (i=n;i>=1;i--) { 
 2173:     sum=b[i]; 
 2174:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2175:     b[i]=sum/a[i][i]; 
 2176:   } 
 2177: } 
 2178: 
 2179: void pstamp(FILE *fichier)
 2180: {
 2181:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2182: }
 2183: 
 2184: /************ Frequencies ********************/
 2185: 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[])
 2186: {  /* Some frequencies */
 2187:   
 2188:   int i, m, jk, k1,i1, j1, bool, z1,j;
 2189:   int first;
 2190:   double ***freq; /* Frequencies */
 2191:   double *pp, **prop;
 2192:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2193:   char fileresp[FILENAMELENGTH];
 2194:   
 2195:   pp=vector(1,nlstate);
 2196:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2197:   strcpy(fileresp,"p");
 2198:   strcat(fileresp,fileres);
 2199:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2200:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2201:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2202:     exit(0);
 2203:   }
 2204:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2205:   j1=0;
 2206:   
 2207:   j=cptcoveff;
 2208:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2209: 
 2210:   first=1;
 2211: 
 2212:   for(k1=1; k1<=j;k1++){   /* Loop on covariates */
 2213:     for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
 2214:       j1++;
 2215:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2216: 	scanf("%d", i);*/
 2217:       for (i=-5; i<=nlstate+ndeath; i++)  
 2218: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2219: 	  for(m=iagemin; m <= iagemax+3; m++)
 2220: 	    freq[i][jk][m]=0;
 2221:       
 2222:       for (i=1; i<=nlstate; i++)  
 2223: 	for(m=iagemin; m <= iagemax+3; m++)
 2224: 	  prop[i][m]=0;
 2225:       
 2226:       dateintsum=0;
 2227:       k2cpt=0;
 2228:       for (i=1; i<=imx; i++) {
 2229: 	bool=1;
 2230: 	if  (cptcovn>0) {
 2231: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2232: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2233: 	      bool=0;
 2234: 	}
 2235: 	if (bool==1){
 2236: 	  for(m=firstpass; m<=lastpass; m++){
 2237: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2238: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2239: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2240: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2241: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2242: 	      if (m<lastpass) {
 2243: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2244: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2245: 	      }
 2246: 	      
 2247: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2248: 		dateintsum=dateintsum+k2;
 2249: 		k2cpt++;
 2250: 	      }
 2251: 	      /*}*/
 2252: 	  }
 2253: 	}
 2254:       }
 2255:        
 2256:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2257:       pstamp(ficresp);
 2258:       if  (cptcovn>0) {
 2259: 	fprintf(ficresp, "\n#********** Variable "); 
 2260: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2261: 	fprintf(ficresp, "**********\n#");
 2262: 	fprintf(ficlog, "\n#********** Variable "); 
 2263: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2264: 	fprintf(ficlog, "**********\n#");
 2265:       }
 2266:       for(i=1; i<=nlstate;i++) 
 2267: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2268:       fprintf(ficresp, "\n");
 2269:       
 2270:       for(i=iagemin; i <= iagemax+3; i++){
 2271: 	if(i==iagemax+3){
 2272: 	  fprintf(ficlog,"Total");
 2273: 	}else{
 2274: 	  if(first==1){
 2275: 	    first=0;
 2276: 	    printf("See log file for details...\n");
 2277: 	  }
 2278: 	  fprintf(ficlog,"Age %d", i);
 2279: 	}
 2280: 	for(jk=1; jk <=nlstate ; jk++){
 2281: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2282: 	    pp[jk] += freq[jk][m][i]; 
 2283: 	}
 2284: 	for(jk=1; jk <=nlstate ; jk++){
 2285: 	  for(m=-1, pos=0; m <=0 ; m++)
 2286: 	    pos += freq[jk][m][i];
 2287: 	  if(pp[jk]>=1.e-10){
 2288: 	    if(first==1){
 2289: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2290: 	    }
 2291: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2292: 	  }else{
 2293: 	    if(first==1)
 2294: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2295: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2296: 	  }
 2297: 	}
 2298: 
 2299: 	for(jk=1; jk <=nlstate ; jk++){
 2300: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2301: 	    pp[jk] += freq[jk][m][i];
 2302: 	}	
 2303: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2304: 	  pos += pp[jk];
 2305: 	  posprop += prop[jk][i];
 2306: 	}
 2307: 	for(jk=1; jk <=nlstate ; jk++){
 2308: 	  if(pos>=1.e-5){
 2309: 	    if(first==1)
 2310: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2311: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2312: 	  }else{
 2313: 	    if(first==1)
 2314: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2315: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2316: 	  }
 2317: 	  if( i <= iagemax){
 2318: 	    if(pos>=1.e-5){
 2319: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2320: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2321: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2322: 	    }
 2323: 	    else
 2324: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2325: 	  }
 2326: 	}
 2327: 	
 2328: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2329: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2330: 	    if(freq[jk][m][i] !=0 ) {
 2331: 	    if(first==1)
 2332: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2333: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2334: 	    }
 2335: 	if(i <= iagemax)
 2336: 	  fprintf(ficresp,"\n");
 2337: 	if(first==1)
 2338: 	  printf("Others in log...\n");
 2339: 	fprintf(ficlog,"\n");
 2340:       }
 2341:     }
 2342:   }
 2343:   dateintmean=dateintsum/k2cpt; 
 2344:  
 2345:   fclose(ficresp);
 2346:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2347:   free_vector(pp,1,nlstate);
 2348:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2349:   /* End of Freq */
 2350: }
 2351: 
 2352: /************ Prevalence ********************/
 2353: 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)
 2354: {  
 2355:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2356:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2357:      We still use firstpass and lastpass as another selection.
 2358:   */
 2359:  
 2360:   int i, m, jk, k1, i1, j1, bool, z1,j;
 2361:   double ***freq; /* Frequencies */
 2362:   double *pp, **prop;
 2363:   double pos,posprop; 
 2364:   double  y2; /* in fractional years */
 2365:   int iagemin, iagemax;
 2366: 
 2367:   iagemin= (int) agemin;
 2368:   iagemax= (int) agemax;
 2369:   /*pp=vector(1,nlstate);*/
 2370:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2371:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2372:   j1=0;
 2373:   
 2374:   j=cptcoveff;
 2375:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2376:   
 2377:   for(k1=1; k1<=j;k1++){
 2378:     for(i1=1; i1<=ncodemax[k1];i1++){
 2379:       j1++;
 2380:       
 2381:       for (i=1; i<=nlstate; i++)  
 2382: 	for(m=iagemin; m <= iagemax+3; m++)
 2383: 	  prop[i][m]=0.0;
 2384:      
 2385:       for (i=1; i<=imx; i++) { /* Each individual */
 2386: 	bool=1;
 2387: 	if  (cptcovn>0) {
 2388: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2389: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2390: 	      bool=0;
 2391: 	} 
 2392: 	if (bool==1) { 
 2393: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2394: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2395: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2396: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2397: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2398: 	      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); 
 2399:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2400: 		/*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]]);*/
 2401:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2402:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2403:  	      } 
 2404: 	    }
 2405: 	  } /* end selection of waves */
 2406: 	}
 2407:       }
 2408:       for(i=iagemin; i <= iagemax+3; i++){  
 2409: 	
 2410:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2411:  	  posprop += prop[jk][i]; 
 2412:  	} 
 2413: 
 2414:  	for(jk=1; jk <=nlstate ; jk++){	    
 2415:  	  if( i <=  iagemax){ 
 2416:  	    if(posprop>=1.e-5){ 
 2417:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2418:  	    } else
 2419: 	      printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
 2420:  	  } 
 2421:  	}/* end jk */ 
 2422:       }/* end i */ 
 2423:     } /* end i1 */
 2424:   } /* end k1 */
 2425:   
 2426:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2427:   /*free_vector(pp,1,nlstate);*/
 2428:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2429: }  /* End of prevalence */
 2430: 
 2431: /************* Waves Concatenation ***************/
 2432: 
 2433: 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)
 2434: {
 2435:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2436:      Death is a valid wave (if date is known).
 2437:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2438:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2439:      and mw[mi+1][i]. dh depends on stepm.
 2440:      */
 2441: 
 2442:   int i, mi, m;
 2443:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2444:      double sum=0., jmean=0.;*/
 2445:   int first;
 2446:   int j, k=0,jk, ju, jl;
 2447:   double sum=0.;
 2448:   first=0;
 2449:   jmin=1e+5;
 2450:   jmax=-1;
 2451:   jmean=0.;
 2452:   for(i=1; i<=imx; i++){
 2453:     mi=0;
 2454:     m=firstpass;
 2455:     while(s[m][i] <= nlstate){
 2456:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2457: 	mw[++mi][i]=m;
 2458:       if(m >=lastpass)
 2459: 	break;
 2460:       else
 2461: 	m++;
 2462:     }/* end while */
 2463:     if (s[m][i] > nlstate){
 2464:       mi++;	/* Death is another wave */
 2465:       /* if(mi==0)  never been interviewed correctly before death */
 2466: 	 /* Only death is a correct wave */
 2467:       mw[mi][i]=m;
 2468:     }
 2469: 
 2470:     wav[i]=mi;
 2471:     if(mi==0){
 2472:       nbwarn++;
 2473:       if(first==0){
 2474: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2475: 	first=1;
 2476:       }
 2477:       if(first==1){
 2478: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2479:       }
 2480:     } /* end mi==0 */
 2481:   } /* End individuals */
 2482: 
 2483:   for(i=1; i<=imx; i++){
 2484:     for(mi=1; mi<wav[i];mi++){
 2485:       if (stepm <=0)
 2486: 	dh[mi][i]=1;
 2487:       else{
 2488: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2489: 	  if (agedc[i] < 2*AGESUP) {
 2490: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2491: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2492: 	    else if(j<0){
 2493: 	      nberr++;
 2494: 	      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]);
 2495: 	      j=1; /* Temporary Dangerous patch */
 2496: 	      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);
 2497: 	      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]);
 2498: 	      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);
 2499: 	    }
 2500: 	    k=k+1;
 2501: 	    if (j >= jmax){
 2502: 	      jmax=j;
 2503: 	      ijmax=i;
 2504: 	    }
 2505: 	    if (j <= jmin){
 2506: 	      jmin=j;
 2507: 	      ijmin=i;
 2508: 	    }
 2509: 	    sum=sum+j;
 2510: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2511: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2512: 	  }
 2513: 	}
 2514: 	else{
 2515: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2516: /* 	  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]); */
 2517: 
 2518: 	  k=k+1;
 2519: 	  if (j >= jmax) {
 2520: 	    jmax=j;
 2521: 	    ijmax=i;
 2522: 	  }
 2523: 	  else if (j <= jmin){
 2524: 	    jmin=j;
 2525: 	    ijmin=i;
 2526: 	  }
 2527: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2528: 	  /*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]);*/
 2529: 	  if(j<0){
 2530: 	    nberr++;
 2531: 	    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]);
 2532: 	    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]);
 2533: 	  }
 2534: 	  sum=sum+j;
 2535: 	}
 2536: 	jk= j/stepm;
 2537: 	jl= j -jk*stepm;
 2538: 	ju= j -(jk+1)*stepm;
 2539: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2540: 	  if(jl==0){
 2541: 	    dh[mi][i]=jk;
 2542: 	    bh[mi][i]=0;
 2543: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2544: 		  * to avoid the price of an extra matrix product in likelihood */
 2545: 	    dh[mi][i]=jk+1;
 2546: 	    bh[mi][i]=ju;
 2547: 	  }
 2548: 	}else{
 2549: 	  if(jl <= -ju){
 2550: 	    dh[mi][i]=jk;
 2551: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2552: 				 * is higher than the multiple of stepm and negative otherwise.
 2553: 				 */
 2554: 	  }
 2555: 	  else{
 2556: 	    dh[mi][i]=jk+1;
 2557: 	    bh[mi][i]=ju;
 2558: 	  }
 2559: 	  if(dh[mi][i]==0){
 2560: 	    dh[mi][i]=1; /* At least one step */
 2561: 	    bh[mi][i]=ju; /* At least one step */
 2562: 	    /*  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);*/
 2563: 	  }
 2564: 	} /* end if mle */
 2565:       }
 2566:     } /* end wave */
 2567:   }
 2568:   jmean=sum/k;
 2569:   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);
 2570:   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);
 2571:  }
 2572: 
 2573: /*********** Tricode ****************************/
 2574: void tricode(int *Tvar, int **nbcode, int imx)
 2575: {
 2576:   /* Uses cptcovn+2*cptcovprod as the number of covariates */
 2577:   /*	  Tvar[i]=atoi(stre); /* find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 */
 2578: 
 2579:   int Ndum[20],ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2580:   int modmaxcovj=0; /* Modality max of covariates j */
 2581:   cptcoveff=0; 
 2582:  
 2583:   for (k=0; k<maxncov; k++) Ndum[k]=0;
 2584:   for (k=1; k<=7; k++) ncodemax[k]=0; /* Horrible constant again */
 2585: 
 2586:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) { /* For each covariate j */
 2587:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum value of the 
 2588: 			       modality of this covariate Vj*/ 
 2589:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2590: 				      modality of the nth covariate of individual i. */
 2591:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2592:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2593:       if (ij > modmaxcovj) modmaxcovj=ij; 
 2594:       /* getting the maximum value of the modality of the covariate
 2595: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2596: 	 female is 1, then modmaxcovj=1.*/
 2597:     }
 2598:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2599:     for (i=0; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each modality of model-cov j */
 2600:       if( Ndum[i] != 0 )
 2601: 	ncodemax[j]++; 
 2602:       /* Number of modalities of the j th covariate. In fact
 2603: 	 ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2604: 	 historical reasons */
 2605:     } /* Ndum[-1] number of undefined modalities */
 2606: 
 2607:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 2608:     ij=1; 
 2609:     for (i=1; i<=ncodemax[j]; i++) { /* i= 1 to 2 for dichotomous */
 2610:       for (k=0; k<= modmaxcovj; k++) { /* k=-1 ? NCOVMAX*//* maxncov or modmaxcovj */
 2611: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 2612: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 2613: 				     k is a modality. If we have model=V1+V1*sex 
 2614: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 2615: 	  ij++;
 2616: 	}
 2617: 	if (ij > ncodemax[j]) break; 
 2618:       }  /* end of loop on */
 2619:     } /* end of loop on modality */ 
 2620:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 2621:   
 2622:   for (k=0; k< maxncov; k++) Ndum[k]=0;
 2623:   
 2624:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
 2625:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
 2626:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
 2627:    Ndum[ij]++;
 2628:  }
 2629: 
 2630:  ij=1;
 2631:  for (i=1; i<= maxncov; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 2632:    if((Ndum[i]!=0) && (i<=ncovcol)){
 2633:      Tvaraff[ij]=i; /*For printing */
 2634:      ij++;
 2635:    }
 2636:  }
 2637:  ij--;
 2638:  cptcoveff=ij; /*Number of simple covariates*/
 2639: }
 2640: 
 2641: /*********** Health Expectancies ****************/
 2642: 
 2643: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 2644: 
 2645: {
 2646:   /* Health expectancies, no variances */
 2647:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
 2648:   int nhstepma, nstepma; /* Decreasing with age */
 2649:   double age, agelim, hf;
 2650:   double ***p3mat;
 2651:   double eip;
 2652: 
 2653:   pstamp(ficreseij);
 2654:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 2655:   fprintf(ficreseij,"# Age");
 2656:   for(i=1; i<=nlstate;i++){
 2657:     for(j=1; j<=nlstate;j++){
 2658:       fprintf(ficreseij," e%1d%1d ",i,j);
 2659:     }
 2660:     fprintf(ficreseij," e%1d. ",i);
 2661:   }
 2662:   fprintf(ficreseij,"\n");
 2663: 
 2664:   
 2665:   if(estepm < stepm){
 2666:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2667:   }
 2668:   else  hstepm=estepm;   
 2669:   /* We compute the life expectancy from trapezoids spaced every estepm months
 2670:    * This is mainly to measure the difference between two models: for example
 2671:    * if stepm=24 months pijx are given only every 2 years and by summing them
 2672:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 2673:    * progression in between and thus overestimating or underestimating according
 2674:    * to the curvature of the survival function. If, for the same date, we 
 2675:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 2676:    * to compare the new estimate of Life expectancy with the same linear 
 2677:    * hypothesis. A more precise result, taking into account a more precise
 2678:    * curvature will be obtained if estepm is as small as stepm. */
 2679: 
 2680:   /* For example we decided to compute the life expectancy with the smallest unit */
 2681:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2682:      nhstepm is the number of hstepm from age to agelim 
 2683:      nstepm is the number of stepm from age to agelin. 
 2684:      Look at hpijx to understand the reason of that which relies in memory size
 2685:      and note for a fixed period like estepm months */
 2686:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2687:      survival function given by stepm (the optimization length). Unfortunately it
 2688:      means that if the survival funtion is printed only each two years of age and if
 2689:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2690:      results. So we changed our mind and took the option of the best precision.
 2691:   */
 2692:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2693: 
 2694:   agelim=AGESUP;
 2695:   /* If stepm=6 months */
 2696:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 2697:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 2698:     
 2699: /* nhstepm age range expressed in number of stepm */
 2700:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2701:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2702:   /* if (stepm >= YEARM) hstepm=1;*/
 2703:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2704:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2705: 
 2706:   for (age=bage; age<=fage; age ++){ 
 2707:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2708:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2709:     /* if (stepm >= YEARM) hstepm=1;*/
 2710:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 2711: 
 2712:     /* If stepm=6 months */
 2713:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 2714:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 2715:     
 2716:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 2717:     
 2718:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2719:     
 2720:     printf("%d|",(int)age);fflush(stdout);
 2721:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2722:     
 2723:     /* Computing expectancies */
 2724:     for(i=1; i<=nlstate;i++)
 2725:       for(j=1; j<=nlstate;j++)
 2726: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2727: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 2728: 	  
 2729: 	  /* 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]);*/
 2730: 
 2731: 	}
 2732: 
 2733:     fprintf(ficreseij,"%3.0f",age );
 2734:     for(i=1; i<=nlstate;i++){
 2735:       eip=0;
 2736:       for(j=1; j<=nlstate;j++){
 2737: 	eip +=eij[i][j][(int)age];
 2738: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 2739:       }
 2740:       fprintf(ficreseij,"%9.4f", eip );
 2741:     }
 2742:     fprintf(ficreseij,"\n");
 2743:     
 2744:   }
 2745:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2746:   printf("\n");
 2747:   fprintf(ficlog,"\n");
 2748:   
 2749: }
 2750: 
 2751: 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[] )
 2752: 
 2753: {
 2754:   /* Covariances of health expectancies eij and of total life expectancies according
 2755:    to initial status i, ei. .
 2756:   */
 2757:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 2758:   int nhstepma, nstepma; /* Decreasing with age */
 2759:   double age, agelim, hf;
 2760:   double ***p3matp, ***p3matm, ***varhe;
 2761:   double **dnewm,**doldm;
 2762:   double *xp, *xm;
 2763:   double **gp, **gm;
 2764:   double ***gradg, ***trgradg;
 2765:   int theta;
 2766: 
 2767:   double eip, vip;
 2768: 
 2769:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 2770:   xp=vector(1,npar);
 2771:   xm=vector(1,npar);
 2772:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 2773:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 2774:   
 2775:   pstamp(ficresstdeij);
 2776:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 2777:   fprintf(ficresstdeij,"# Age");
 2778:   for(i=1; i<=nlstate;i++){
 2779:     for(j=1; j<=nlstate;j++)
 2780:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 2781:     fprintf(ficresstdeij," e%1d. ",i);
 2782:   }
 2783:   fprintf(ficresstdeij,"\n");
 2784: 
 2785:   pstamp(ficrescveij);
 2786:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 2787:   fprintf(ficrescveij,"# Age");
 2788:   for(i=1; i<=nlstate;i++)
 2789:     for(j=1; j<=nlstate;j++){
 2790:       cptj= (j-1)*nlstate+i;
 2791:       for(i2=1; i2<=nlstate;i2++)
 2792: 	for(j2=1; j2<=nlstate;j2++){
 2793: 	  cptj2= (j2-1)*nlstate+i2;
 2794: 	  if(cptj2 <= cptj)
 2795: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 2796: 	}
 2797:     }
 2798:   fprintf(ficrescveij,"\n");
 2799:   
 2800:   if(estepm < stepm){
 2801:     printf ("Problem %d lower than %d\n",estepm, stepm);
 2802:   }
 2803:   else  hstepm=estepm;   
 2804:   /* We compute the life expectancy from trapezoids spaced every estepm months
 2805:    * This is mainly to measure the difference between two models: for example
 2806:    * if stepm=24 months pijx are given only every 2 years and by summing them
 2807:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 2808:    * progression in between and thus overestimating or underestimating according
 2809:    * to the curvature of the survival function. If, for the same date, we 
 2810:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 2811:    * to compare the new estimate of Life expectancy with the same linear 
 2812:    * hypothesis. A more precise result, taking into account a more precise
 2813:    * curvature will be obtained if estepm is as small as stepm. */
 2814: 
 2815:   /* For example we decided to compute the life expectancy with the smallest unit */
 2816:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 2817:      nhstepm is the number of hstepm from age to agelim 
 2818:      nstepm is the number of stepm from age to agelin. 
 2819:      Look at hpijx to understand the reason of that which relies in memory size
 2820:      and note for a fixed period like estepm months */
 2821:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 2822:      survival function given by stepm (the optimization length). Unfortunately it
 2823:      means that if the survival funtion is printed only each two years of age and if
 2824:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 2825:      results. So we changed our mind and took the option of the best precision.
 2826:   */
 2827:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 2828: 
 2829:   /* If stepm=6 months */
 2830:   /* nhstepm age range expressed in number of stepm */
 2831:   agelim=AGESUP;
 2832:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 2833:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2834:   /* if (stepm >= YEARM) hstepm=1;*/
 2835:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 2836:   
 2837:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2838:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2839:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 2840:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 2841:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 2842:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 2843: 
 2844:   for (age=bage; age<=fage; age ++){ 
 2845:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 2846:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 2847:     /* if (stepm >= YEARM) hstepm=1;*/
 2848:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 2849: 
 2850:     /* If stepm=6 months */
 2851:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 2852:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 2853:     
 2854:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 2855: 
 2856:     /* Computing  Variances of health expectancies */
 2857:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 2858:        decrease memory allocation */
 2859:     for(theta=1; theta <=npar; theta++){
 2860:       for(i=1; i<=npar; i++){ 
 2861: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 2862: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 2863:       }
 2864:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 2865:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 2866:   
 2867:       for(j=1; j<= nlstate; j++){
 2868: 	for(i=1; i<=nlstate; i++){
 2869: 	  for(h=0; h<=nhstepm-1; h++){
 2870: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 2871: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 2872: 	  }
 2873: 	}
 2874:       }
 2875:      
 2876:       for(ij=1; ij<= nlstate*nlstate; ij++)
 2877: 	for(h=0; h<=nhstepm-1; h++){
 2878: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 2879: 	}
 2880:     }/* End theta */
 2881:     
 2882:     
 2883:     for(h=0; h<=nhstepm-1; h++)
 2884:       for(j=1; j<=nlstate*nlstate;j++)
 2885: 	for(theta=1; theta <=npar; theta++)
 2886: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 2887:     
 2888: 
 2889:      for(ij=1;ij<=nlstate*nlstate;ij++)
 2890:       for(ji=1;ji<=nlstate*nlstate;ji++)
 2891: 	varhe[ij][ji][(int)age] =0.;
 2892: 
 2893:      printf("%d|",(int)age);fflush(stdout);
 2894:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 2895:      for(h=0;h<=nhstepm-1;h++){
 2896:       for(k=0;k<=nhstepm-1;k++){
 2897: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 2898: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 2899: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 2900: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 2901: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 2902:       }
 2903:     }
 2904: 
 2905:     /* Computing expectancies */
 2906:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 2907:     for(i=1; i<=nlstate;i++)
 2908:       for(j=1; j<=nlstate;j++)
 2909: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 2910: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 2911: 	  
 2912: 	  /* 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]);*/
 2913: 
 2914: 	}
 2915: 
 2916:     fprintf(ficresstdeij,"%3.0f",age );
 2917:     for(i=1; i<=nlstate;i++){
 2918:       eip=0.;
 2919:       vip=0.;
 2920:       for(j=1; j<=nlstate;j++){
 2921: 	eip += eij[i][j][(int)age];
 2922: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 2923: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 2924: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 2925:       }
 2926:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 2927:     }
 2928:     fprintf(ficresstdeij,"\n");
 2929: 
 2930:     fprintf(ficrescveij,"%3.0f",age );
 2931:     for(i=1; i<=nlstate;i++)
 2932:       for(j=1; j<=nlstate;j++){
 2933: 	cptj= (j-1)*nlstate+i;
 2934: 	for(i2=1; i2<=nlstate;i2++)
 2935: 	  for(j2=1; j2<=nlstate;j2++){
 2936: 	    cptj2= (j2-1)*nlstate+i2;
 2937: 	    if(cptj2 <= cptj)
 2938: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 2939: 	  }
 2940:       }
 2941:     fprintf(ficrescveij,"\n");
 2942:    
 2943:   }
 2944:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 2945:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 2946:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 2947:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 2948:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2949:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 2950:   printf("\n");
 2951:   fprintf(ficlog,"\n");
 2952: 
 2953:   free_vector(xm,1,npar);
 2954:   free_vector(xp,1,npar);
 2955:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 2956:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 2957:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 2958: }
 2959: 
 2960: /************ Variance ******************/
 2961: 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[])
 2962: {
 2963:   /* Variance of health expectancies */
 2964:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 2965:   /* double **newm;*/
 2966:   double **dnewm,**doldm;
 2967:   double **dnewmp,**doldmp;
 2968:   int i, j, nhstepm, hstepm, h, nstepm ;
 2969:   int k, cptcode;
 2970:   double *xp;
 2971:   double **gp, **gm;  /* for var eij */
 2972:   double ***gradg, ***trgradg; /*for var eij */
 2973:   double **gradgp, **trgradgp; /* for var p point j */
 2974:   double *gpp, *gmp; /* for var p point j */
 2975:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 2976:   double ***p3mat;
 2977:   double age,agelim, hf;
 2978:   double ***mobaverage;
 2979:   int theta;
 2980:   char digit[4];
 2981:   char digitp[25];
 2982: 
 2983:   char fileresprobmorprev[FILENAMELENGTH];
 2984: 
 2985:   if(popbased==1){
 2986:     if(mobilav!=0)
 2987:       strcpy(digitp,"-populbased-mobilav-");
 2988:     else strcpy(digitp,"-populbased-nomobil-");
 2989:   }
 2990:   else 
 2991:     strcpy(digitp,"-stablbased-");
 2992: 
 2993:   if (mobilav!=0) {
 2994:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 2995:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 2996:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 2997:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 2998:     }
 2999:   }
 3000: 
 3001:   strcpy(fileresprobmorprev,"prmorprev"); 
 3002:   sprintf(digit,"%-d",ij);
 3003:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3004:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3005:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3006:   strcat(fileresprobmorprev,fileres);
 3007:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3008:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3009:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3010:   }
 3011:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3012:  
 3013:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3014:   pstamp(ficresprobmorprev);
 3015:   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);
 3016:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3017:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3018:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3019:     for(i=1; i<=nlstate;i++)
 3020:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3021:   }  
 3022:   fprintf(ficresprobmorprev,"\n");
 3023:   fprintf(ficgp,"\n# Routine varevsij");
 3024:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3025:   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");
 3026:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3027: /*   } */
 3028:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3029:   pstamp(ficresvij);
 3030:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3031:   if(popbased==1)
 3032:     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);
 3033:   else
 3034:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3035:   fprintf(ficresvij,"# Age");
 3036:   for(i=1; i<=nlstate;i++)
 3037:     for(j=1; j<=nlstate;j++)
 3038:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3039:   fprintf(ficresvij,"\n");
 3040: 
 3041:   xp=vector(1,npar);
 3042:   dnewm=matrix(1,nlstate,1,npar);
 3043:   doldm=matrix(1,nlstate,1,nlstate);
 3044:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3045:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3046: 
 3047:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3048:   gpp=vector(nlstate+1,nlstate+ndeath);
 3049:   gmp=vector(nlstate+1,nlstate+ndeath);
 3050:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3051:   
 3052:   if(estepm < stepm){
 3053:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3054:   }
 3055:   else  hstepm=estepm;   
 3056:   /* For example we decided to compute the life expectancy with the smallest unit */
 3057:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3058:      nhstepm is the number of hstepm from age to agelim 
 3059:      nstepm is the number of stepm from age to agelin. 
 3060:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3061:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3062:      survival function given by stepm (the optimization length). Unfortunately it
 3063:      means that if the survival funtion is printed every two years of age and if
 3064:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3065:      results. So we changed our mind and took the option of the best precision.
 3066:   */
 3067:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3068:   agelim = AGESUP;
 3069:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3070:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3071:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3072:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3073:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3074:     gp=matrix(0,nhstepm,1,nlstate);
 3075:     gm=matrix(0,nhstepm,1,nlstate);
 3076: 
 3077: 
 3078:     for(theta=1; theta <=npar; theta++){
 3079:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3080: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3081:       }
 3082:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3083:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3084: 
 3085:       if (popbased==1) {
 3086: 	if(mobilav ==0){
 3087: 	  for(i=1; i<=nlstate;i++)
 3088: 	    prlim[i][i]=probs[(int)age][i][ij];
 3089: 	}else{ /* mobilav */ 
 3090: 	  for(i=1; i<=nlstate;i++)
 3091: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3092: 	}
 3093:       }
 3094:   
 3095:       for(j=1; j<= nlstate; j++){
 3096: 	for(h=0; h<=nhstepm; h++){
 3097: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3098: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3099: 	}
 3100:       }
 3101:       /* This for computing probability of death (h=1 means
 3102:          computed over hstepm matrices product = hstepm*stepm months) 
 3103:          as a weighted average of prlim.
 3104:       */
 3105:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3106: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3107: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3108:       }    
 3109:       /* end probability of death */
 3110: 
 3111:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3112: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3113:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3114:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3115:  
 3116:       if (popbased==1) {
 3117: 	if(mobilav ==0){
 3118: 	  for(i=1; i<=nlstate;i++)
 3119: 	    prlim[i][i]=probs[(int)age][i][ij];
 3120: 	}else{ /* mobilav */ 
 3121: 	  for(i=1; i<=nlstate;i++)
 3122: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3123: 	}
 3124:       }
 3125: 
 3126:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3127: 	for(h=0; h<=nhstepm; h++){
 3128: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3129: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3130: 	}
 3131:       }
 3132:       /* This for computing probability of death (h=1 means
 3133:          computed over hstepm matrices product = hstepm*stepm months) 
 3134:          as a weighted average of prlim.
 3135:       */
 3136:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3137: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3138:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3139:       }    
 3140:       /* end probability of death */
 3141: 
 3142:       for(j=1; j<= nlstate; j++) /* vareij */
 3143: 	for(h=0; h<=nhstepm; h++){
 3144: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3145: 	}
 3146: 
 3147:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3148: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3149:       }
 3150: 
 3151:     } /* End theta */
 3152: 
 3153:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3154: 
 3155:     for(h=0; h<=nhstepm; h++) /* veij */
 3156:       for(j=1; j<=nlstate;j++)
 3157: 	for(theta=1; theta <=npar; theta++)
 3158: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3159: 
 3160:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3161:       for(theta=1; theta <=npar; theta++)
 3162: 	trgradgp[j][theta]=gradgp[theta][j];
 3163:   
 3164: 
 3165:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3166:     for(i=1;i<=nlstate;i++)
 3167:       for(j=1;j<=nlstate;j++)
 3168: 	vareij[i][j][(int)age] =0.;
 3169: 
 3170:     for(h=0;h<=nhstepm;h++){
 3171:       for(k=0;k<=nhstepm;k++){
 3172: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3173: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3174: 	for(i=1;i<=nlstate;i++)
 3175: 	  for(j=1;j<=nlstate;j++)
 3176: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3177:       }
 3178:     }
 3179:   
 3180:     /* pptj */
 3181:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3182:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3183:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3184:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3185: 	varppt[j][i]=doldmp[j][i];
 3186:     /* end ppptj */
 3187:     /*  x centered again */
 3188:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3189:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3190:  
 3191:     if (popbased==1) {
 3192:       if(mobilav ==0){
 3193: 	for(i=1; i<=nlstate;i++)
 3194: 	  prlim[i][i]=probs[(int)age][i][ij];
 3195:       }else{ /* mobilav */ 
 3196: 	for(i=1; i<=nlstate;i++)
 3197: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3198:       }
 3199:     }
 3200:              
 3201:     /* This for computing probability of death (h=1 means
 3202:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3203:        as a weighted average of prlim.
 3204:     */
 3205:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3206:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3207: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3208:     }    
 3209:     /* end probability of death */
 3210: 
 3211:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3212:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3213:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3214:       for(i=1; i<=nlstate;i++){
 3215: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3216:       }
 3217:     } 
 3218:     fprintf(ficresprobmorprev,"\n");
 3219: 
 3220:     fprintf(ficresvij,"%.0f ",age );
 3221:     for(i=1; i<=nlstate;i++)
 3222:       for(j=1; j<=nlstate;j++){
 3223: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3224:       }
 3225:     fprintf(ficresvij,"\n");
 3226:     free_matrix(gp,0,nhstepm,1,nlstate);
 3227:     free_matrix(gm,0,nhstepm,1,nlstate);
 3228:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3229:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3230:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3231:   } /* End age */
 3232:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3233:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3234:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3235:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3236:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small;set size 0.65, 0.65");
 3237:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3238:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3239: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3240: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3241: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3242:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 2 ",subdirf(fileresprobmorprev));
 3243:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 3 ",subdirf(fileresprobmorprev));
 3244:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 3 ",subdirf(fileresprobmorprev));
 3245:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3246:   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);
 3247:   /*  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);
 3248: */
 3249: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3250:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3251: 
 3252:   free_vector(xp,1,npar);
 3253:   free_matrix(doldm,1,nlstate,1,nlstate);
 3254:   free_matrix(dnewm,1,nlstate,1,npar);
 3255:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3256:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3257:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3258:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3259:   fclose(ficresprobmorprev);
 3260:   fflush(ficgp);
 3261:   fflush(fichtm); 
 3262: }  /* end varevsij */
 3263: 
 3264: /************ Variance of prevlim ******************/
 3265: 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[])
 3266: {
 3267:   /* Variance of prevalence limit */
 3268:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3269:   double **newm;
 3270:   double **dnewm,**doldm;
 3271:   int i, j, nhstepm, hstepm;
 3272:   int k, cptcode;
 3273:   double *xp;
 3274:   double *gp, *gm;
 3275:   double **gradg, **trgradg;
 3276:   double age,agelim;
 3277:   int theta;
 3278:   
 3279:   pstamp(ficresvpl);
 3280:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3281:   fprintf(ficresvpl,"# Age");
 3282:   for(i=1; i<=nlstate;i++)
 3283:       fprintf(ficresvpl," %1d-%1d",i,i);
 3284:   fprintf(ficresvpl,"\n");
 3285: 
 3286:   xp=vector(1,npar);
 3287:   dnewm=matrix(1,nlstate,1,npar);
 3288:   doldm=matrix(1,nlstate,1,nlstate);
 3289:   
 3290:   hstepm=1*YEARM; /* Every year of age */
 3291:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3292:   agelim = AGESUP;
 3293:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3294:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3295:     if (stepm >= YEARM) hstepm=1;
 3296:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3297:     gradg=matrix(1,npar,1,nlstate);
 3298:     gp=vector(1,nlstate);
 3299:     gm=vector(1,nlstate);
 3300: 
 3301:     for(theta=1; theta <=npar; theta++){
 3302:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3303: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3304:       }
 3305:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3306:       for(i=1;i<=nlstate;i++)
 3307: 	gp[i] = prlim[i][i];
 3308:     
 3309:       for(i=1; i<=npar; i++) /* Computes gradient */
 3310: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3311:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3312:       for(i=1;i<=nlstate;i++)
 3313: 	gm[i] = prlim[i][i];
 3314: 
 3315:       for(i=1;i<=nlstate;i++)
 3316: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3317:     } /* End theta */
 3318: 
 3319:     trgradg =matrix(1,nlstate,1,npar);
 3320: 
 3321:     for(j=1; j<=nlstate;j++)
 3322:       for(theta=1; theta <=npar; theta++)
 3323: 	trgradg[j][theta]=gradg[theta][j];
 3324: 
 3325:     for(i=1;i<=nlstate;i++)
 3326:       varpl[i][(int)age] =0.;
 3327:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3328:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3329:     for(i=1;i<=nlstate;i++)
 3330:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3331: 
 3332:     fprintf(ficresvpl,"%.0f ",age );
 3333:     for(i=1; i<=nlstate;i++)
 3334:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3335:     fprintf(ficresvpl,"\n");
 3336:     free_vector(gp,1,nlstate);
 3337:     free_vector(gm,1,nlstate);
 3338:     free_matrix(gradg,1,npar,1,nlstate);
 3339:     free_matrix(trgradg,1,nlstate,1,npar);
 3340:   } /* End age */
 3341: 
 3342:   free_vector(xp,1,npar);
 3343:   free_matrix(doldm,1,nlstate,1,npar);
 3344:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3345: 
 3346: }
 3347: 
 3348: /************ Variance of one-step probabilities  ******************/
 3349: 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[])
 3350: {
 3351:   int i, j=0,  i1, k1, l1, t, tj;
 3352:   int k2, l2, j1,  z1;
 3353:   int k=0,l, cptcode;
 3354:   int first=1, first1;
 3355:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3356:   double **dnewm,**doldm;
 3357:   double *xp;
 3358:   double *gp, *gm;
 3359:   double **gradg, **trgradg;
 3360:   double **mu;
 3361:   double age,agelim, cov[NCOVMAX];
 3362:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3363:   int theta;
 3364:   char fileresprob[FILENAMELENGTH];
 3365:   char fileresprobcov[FILENAMELENGTH];
 3366:   char fileresprobcor[FILENAMELENGTH];
 3367: 
 3368:   double ***varpij;
 3369: 
 3370:   strcpy(fileresprob,"prob"); 
 3371:   strcat(fileresprob,fileres);
 3372:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3373:     printf("Problem with resultfile: %s\n", fileresprob);
 3374:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3375:   }
 3376:   strcpy(fileresprobcov,"probcov"); 
 3377:   strcat(fileresprobcov,fileres);
 3378:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3379:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3380:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3381:   }
 3382:   strcpy(fileresprobcor,"probcor"); 
 3383:   strcat(fileresprobcor,fileres);
 3384:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3385:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3386:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3387:   }
 3388:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3389:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3390:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3391:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3392:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3393:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3394:   pstamp(ficresprob);
 3395:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3396:   fprintf(ficresprob,"# Age");
 3397:   pstamp(ficresprobcov);
 3398:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3399:   fprintf(ficresprobcov,"# Age");
 3400:   pstamp(ficresprobcor);
 3401:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3402:   fprintf(ficresprobcor,"# Age");
 3403: 
 3404: 
 3405:   for(i=1; i<=nlstate;i++)
 3406:     for(j=1; j<=(nlstate+ndeath);j++){
 3407:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3408:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3409:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3410:     }  
 3411:  /* fprintf(ficresprob,"\n");
 3412:   fprintf(ficresprobcov,"\n");
 3413:   fprintf(ficresprobcor,"\n");
 3414:  */
 3415:   xp=vector(1,npar);
 3416:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3417:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3418:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3419:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3420:   first=1;
 3421:   fprintf(ficgp,"\n# Routine varprob");
 3422:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3423:   fprintf(fichtm,"\n");
 3424: 
 3425:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3426:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3427:   file %s<br>\n",optionfilehtmcov);
 3428:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3429: and drawn. It helps understanding how is the covariance between two incidences.\
 3430:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3431:   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. \
 3432: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3433: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3434: standard deviations wide on each axis. <br>\
 3435:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3436:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3437: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3438: 
 3439:   cov[1]=1;
 3440:   tj=cptcoveff;
 3441:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3442:   j1=0;
 3443:   for(t=1; t<=tj;t++){
 3444:     for(i1=1; i1<=ncodemax[t];i1++){ 
 3445:       j1++;
 3446:       if  (cptcovn>0) {
 3447: 	fprintf(ficresprob, "\n#********** Variable "); 
 3448: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3449: 	fprintf(ficresprob, "**********\n#\n");
 3450: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3451: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3452: 	fprintf(ficresprobcov, "**********\n#\n");
 3453: 	
 3454: 	fprintf(ficgp, "\n#********** Variable "); 
 3455: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3456: 	fprintf(ficgp, "**********\n#\n");
 3457: 	
 3458: 	
 3459: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3460: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3461: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3462: 	
 3463: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3464: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3465: 	fprintf(ficresprobcor, "**********\n#");    
 3466:       }
 3467:       
 3468:       for (age=bage; age<=fage; age ++){ 
 3469: 	cov[2]=age;
 3470: 	for (k=1; k<=cptcovn;k++) {
 3471: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
 3472: 	}
 3473: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3474: 	for (k=1; k<=cptcovprod;k++)
 3475: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3476: 	
 3477: 	gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3478: 	trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3479: 	gp=vector(1,(nlstate)*(nlstate+ndeath));
 3480: 	gm=vector(1,(nlstate)*(nlstate+ndeath));
 3481:     
 3482: 	for(theta=1; theta <=npar; theta++){
 3483: 	  for(i=1; i<=npar; i++)
 3484: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3485: 	  
 3486: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3487: 	  
 3488: 	  k=0;
 3489: 	  for(i=1; i<= (nlstate); i++){
 3490: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3491: 	      k=k+1;
 3492: 	      gp[k]=pmmij[i][j];
 3493: 	    }
 3494: 	  }
 3495: 	  
 3496: 	  for(i=1; i<=npar; i++)
 3497: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3498:     
 3499: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3500: 	  k=0;
 3501: 	  for(i=1; i<=(nlstate); i++){
 3502: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3503: 	      k=k+1;
 3504: 	      gm[k]=pmmij[i][j];
 3505: 	    }
 3506: 	  }
 3507:      
 3508: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3509: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3510: 	}
 3511: 
 3512: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3513: 	  for(theta=1; theta <=npar; theta++)
 3514: 	    trgradg[j][theta]=gradg[theta][j];
 3515: 	
 3516: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3517: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3518: 	free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3519: 	free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3520: 	free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3521: 	free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3522: 
 3523: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3524: 	
 3525: 	k=0;
 3526: 	for(i=1; i<=(nlstate); i++){
 3527: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3528: 	    k=k+1;
 3529: 	    mu[k][(int) age]=pmmij[i][j];
 3530: 	  }
 3531: 	}
 3532:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3533: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3534: 	    varpij[i][j][(int)age] = doldm[i][j];
 3535: 
 3536: 	/*printf("\n%d ",(int)age);
 3537: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3538: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3539: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3540: 	  }*/
 3541: 
 3542: 	fprintf(ficresprob,"\n%d ",(int)age);
 3543: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3544: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3545: 
 3546: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3547: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3548: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3549: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3550: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3551: 	}
 3552: 	i=0;
 3553: 	for (k=1; k<=(nlstate);k++){
 3554:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3555:  	    i=i++;
 3556: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3557: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3558: 	    for (j=1; j<=i;j++){
 3559: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3560: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3561: 	    }
 3562: 	  }
 3563: 	}/* end of loop for state */
 3564:       } /* end of loop for age */
 3565: 
 3566:       /* Confidence intervalle of pij  */
 3567:       /*
 3568: 	fprintf(ficgp,"\nunset parametric;unset label");
 3569: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3570: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3571: 	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);
 3572: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3573: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3574: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3575:       */
 3576: 
 3577:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3578:       first1=1;
 3579:       for (k2=1; k2<=(nlstate);k2++){
 3580: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3581: 	  if(l2==k2) continue;
 3582: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3583: 	  for (k1=1; k1<=(nlstate);k1++){
 3584: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3585: 	      if(l1==k1) continue;
 3586: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3587: 	      if(i<=j) continue;
 3588: 	      for (age=bage; age<=fage; age ++){ 
 3589: 		if ((int)age %5==0){
 3590: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3591: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3592: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3593: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3594: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3595: 		  c12=cv12/sqrt(v1*v2);
 3596: 		  /* Computing eigen value of matrix of covariance */
 3597: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3598: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3599: 		  if ((lc2 <0) || (lc1 <0) ){
 3600: 		    printf("Error: 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. Continuing by making them positive: WRONG RESULTS.\n", lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
 3601: 		    fprintf(ficlog,"Error: 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", lc1, lc2, v1, v2, cv12);fflush(ficlog);
 3602: 		    lc1=fabs(lc1);
 3603: 		    lc2=fabs(lc2);
 3604: 		  }
 3605: 
 3606: 		  /* Eigen vectors */
 3607: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 3608: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 3609: 		  v21=(lc1-v1)/cv12*v11;
 3610: 		  v12=-v21;
 3611: 		  v22=v11;
 3612: 		  tnalp=v21/v11;
 3613: 		  if(first1==1){
 3614: 		    first1=0;
 3615: 		    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);
 3616: 		  }
 3617: 		  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);
 3618: 		  /*printf(fignu*/
 3619: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 3620: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 3621: 		  if(first==1){
 3622: 		    first=0;
 3623:  		    fprintf(ficgp,"\nset parametric;unset label");
 3624: 		    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);
 3625: 		    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3626: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 3627:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 3628: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 3629: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 3630: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3631: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3632: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 3633: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3634: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3635: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3636: 		    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",\
 3637: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3638: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3639: 		  }else{
 3640: 		    first=0;
 3641: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 3642: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 3643: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 3644: 		    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",\
 3645: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 3646: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 3647: 		  }/* if first */
 3648: 		} /* age mod 5 */
 3649: 	      } /* end loop age */
 3650: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3651: 	      first=1;
 3652: 	    } /*l12 */
 3653: 	  } /* k12 */
 3654: 	} /*l1 */
 3655:       }/* k1 */
 3656:     } /* loop covariates */
 3657:   }
 3658:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 3659:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 3660:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3661:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 3662:   free_vector(xp,1,npar);
 3663:   fclose(ficresprob);
 3664:   fclose(ficresprobcov);
 3665:   fclose(ficresprobcor);
 3666:   fflush(ficgp);
 3667:   fflush(fichtmcov);
 3668: }
 3669: 
 3670: 
 3671: /******************* Printing html file ***********/
 3672: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 3673: 		  int lastpass, int stepm, int weightopt, char model[],\
 3674: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 3675: 		  int popforecast, int estepm ,\
 3676: 		  double jprev1, double mprev1,double anprev1, \
 3677: 		  double jprev2, double mprev2,double anprev2){
 3678:   int jj1, k1, i1, cpt;
 3679: 
 3680:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 3681:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 3682: </ul>");
 3683:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 3684:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 3685: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 3686:    fprintf(fichtm,"\
 3687:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 3688: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 3689:    fprintf(fichtm,"\
 3690:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 3691: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 3692:    fprintf(fichtm,"\
 3693:  - (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): \
 3694:    <a href=\"%s\">%s</a> <br>\n",
 3695: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 3696:    fprintf(fichtm,"\
 3697:  - Population projections by age and states: \
 3698:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 3699: 
 3700: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 3701: 
 3702:  m=cptcoveff;
 3703:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3704: 
 3705:  jj1=0;
 3706:  for(k1=1; k1<=m;k1++){
 3707:    for(i1=1; i1<=ncodemax[k1];i1++){
 3708:      jj1++;
 3709:      if (cptcovn > 0) {
 3710:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3711:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3712: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3713:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3714:      }
 3715:      /* Pij */
 3716:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
 3717: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 3718:      /* Quasi-incidences */
 3719:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 3720:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \
 3721: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 3722:        /* Period (stable) prevalence in each health state */
 3723:        for(cpt=1; cpt<nlstate;cpt++){
 3724: 	 fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
 3725: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 3726:        }
 3727:      for(cpt=1; cpt<=nlstate;cpt++) {
 3728:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
 3729: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 3730:      }
 3731:    } /* end i1 */
 3732:  }/* End k1 */
 3733:  fprintf(fichtm,"</ul>");
 3734: 
 3735: 
 3736:  fprintf(fichtm,"\
 3737: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 3738:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 3739: 
 3740:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3741: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 3742:  fprintf(fichtm,"\
 3743:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3744: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 3745: 
 3746:  fprintf(fichtm,"\
 3747:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 3748: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 3749:  fprintf(fichtm,"\
 3750:  - 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): \
 3751:    <a href=\"%s\">%s</a> <br>\n</li>",
 3752: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 3753:  fprintf(fichtm,"\
 3754:  - (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): \
 3755:    <a href=\"%s\">%s</a> <br>\n</li>",
 3756: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 3757:  fprintf(fichtm,"\
 3758:  - 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",
 3759: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 3760:  fprintf(fichtm,"\
 3761:  - 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",
 3762: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 3763:  fprintf(fichtm,"\
 3764:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 3765: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 3766: 
 3767: /*  if(popforecast==1) fprintf(fichtm,"\n */
 3768: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 3769: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 3770: /* 	<br>",fileres,fileres,fileres,fileres); */
 3771: /*  else  */
 3772: /*    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); */
 3773:  fflush(fichtm);
 3774:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 3775: 
 3776:  m=cptcoveff;
 3777:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 3778: 
 3779:  jj1=0;
 3780:  for(k1=1; k1<=m;k1++){
 3781:    for(i1=1; i1<=ncodemax[k1];i1++){
 3782:      jj1++;
 3783:      if (cptcovn > 0) {
 3784:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 3785:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 3786: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 3787:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 3788:      }
 3789:      for(cpt=1; cpt<=nlstate;cpt++) {
 3790:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 3791: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
 3792: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 3793:      }
 3794:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 3795: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 3796: true period expectancies (those weighted with period prevalences are also\
 3797:  drawn in addition to the population based expectancies computed using\
 3798:  observed and cahotic prevalences: %s%d.png<br>\
 3799: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 3800:    } /* end i1 */
 3801:  }/* End k1 */
 3802:  fprintf(fichtm,"</ul>");
 3803:  fflush(fichtm);
 3804: }
 3805: 
 3806: /******************* Gnuplot file **************/
 3807: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 3808: 
 3809:   char dirfileres[132],optfileres[132];
 3810:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 3811:   int ng=0;
 3812: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 3813: /*     printf("Problem with file %s",optionfilegnuplot); */
 3814: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 3815: /*   } */
 3816: 
 3817:   /*#ifdef windows */
 3818:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 3819:     /*#endif */
 3820:   m=pow(2,cptcoveff);
 3821: 
 3822:   strcpy(dirfileres,optionfilefiname);
 3823:   strcpy(optfileres,"vpl");
 3824:  /* 1eme*/
 3825:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 3826:    for (k1=1; k1<= m ; k1 ++) {
 3827:      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 3828:      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
 3829:      fprintf(ficgp,"set xlabel \"Age\" \n\
 3830: set ylabel \"Probability\" \n\
 3831: set ter png small\n\
 3832: set size 0.65,0.65\n\
 3833: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 3834: 
 3835:      for (i=1; i<= nlstate ; i ++) {
 3836:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3837:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
 3838:      }
 3839:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 1,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 3840:      for (i=1; i<= nlstate ; i ++) {
 3841:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3842:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3843:      } 
 3844:      fprintf(ficgp,"\" t\"95\%% CI\" w l lt 2,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
 3845:      for (i=1; i<= nlstate ; i ++) {
 3846:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 3847:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 3848:      }  
 3849:      fprintf(ficgp,"\" t\"\" w l lt 2,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 3",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
 3850:    }
 3851:   }
 3852:   /*2 eme*/
 3853:   
 3854:   for (k1=1; k1<= m ; k1 ++) { 
 3855:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 3856:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
 3857:     
 3858:     for (i=1; i<= nlstate+1 ; i ++) {
 3859:       k=2*i;
 3860:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3861:       for (j=1; j<= nlstate+1 ; j ++) {
 3862: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3863: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3864:       }   
 3865:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 3866:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 3867:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3868:       for (j=1; j<= nlstate+1 ; j ++) {
 3869: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3870: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3871:       }   
 3872:       fprintf(ficgp,"\" t\"\" w l lt 1,");
 3873:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 3874:       for (j=1; j<= nlstate+1 ; j ++) {
 3875: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 3876: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 3877:       }   
 3878:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 1");
 3879:       else fprintf(ficgp,"\" t\"\" w l lt 1,");
 3880:     }
 3881:   }
 3882:   
 3883:   /*3eme*/
 3884:   
 3885:   for (k1=1; k1<= m ; k1 ++) { 
 3886:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 3887:       /*       k=2+nlstate*(2*cpt-2); */
 3888:       k=2+(nlstate+1)*(cpt-1);
 3889:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 3890:       fprintf(ficgp,"set ter png small\n\
 3891: set size 0.65,0.65\n\
 3892: 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);
 3893:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3894: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3895: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3896: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 3897: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 3898: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 3899: 	
 3900:       */
 3901:       for (i=1; i< nlstate ; i ++) {
 3902: 	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);
 3903: 	/*	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);*/
 3904: 	
 3905:       } 
 3906:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 3907:     }
 3908:   }
 3909:   
 3910:   /* CV preval stable (period) */
 3911:   for (k1=1; k1<= m ; k1 ++) { 
 3912:     for (cpt=1; cpt<=nlstate ; cpt ++) {
 3913:       k=3;
 3914:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 3915:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 3916: set ter png small\nset size 0.65,0.65\n\
 3917: unset log y\n\
 3918: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
 3919:       
 3920:       for (i=1; i< nlstate ; i ++)
 3921: 	fprintf(ficgp,"+$%d",k+i+1);
 3922:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
 3923:       
 3924:       l=3+(nlstate+ndeath)*cpt;
 3925:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
 3926:       for (i=1; i< nlstate ; i ++) {
 3927: 	l=3+(nlstate+ndeath)*cpt;
 3928: 	fprintf(ficgp,"+$%d",l+i+1);
 3929:       }
 3930:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
 3931:     } 
 3932:   }  
 3933:   
 3934:   /* proba elementaires */
 3935:   for(i=1,jk=1; i <=nlstate; i++){
 3936:     for(k=1; k <=(nlstate+ndeath); k++){
 3937:       if (k != i) {
 3938: 	for(j=1; j <=ncovmodel; j++){
 3939: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 3940: 	  jk++; 
 3941: 	  fprintf(ficgp,"\n");
 3942: 	}
 3943:       }
 3944:     }
 3945:    }
 3946: 
 3947:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 3948:      for(jk=1; jk <=m; jk++) {
 3949:        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 3950:        if (ng==2)
 3951: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 3952:        else
 3953: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 3954:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 3955:        i=1;
 3956:        for(k2=1; k2<=nlstate; k2++) {
 3957: 	 k3=i;
 3958: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 3959: 	   if (k != k2){
 3960: 	     if(ng==2)
 3961: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 3962: 	     else
 3963: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 3964: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 3965: 	     for(j=3; j <=ncovmodel; j++) {
 3966: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
 3967: 		 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3968: 		 ij++;
 3969: 	       }
 3970: 	       else
 3971: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3972: 	     }
 3973: 	     fprintf(ficgp,")/(1");
 3974: 	     
 3975: 	     for(k1=1; k1 <=nlstate; k1++){   
 3976: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 3977: 	       ij=1;
 3978: 	       for(j=3; j <=ncovmodel; j++){
 3979: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 3980: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 3981: 		   ij++;
 3982: 		 }
 3983: 		 else
 3984: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 3985: 	       }
 3986: 	       fprintf(ficgp,")");
 3987: 	     }
 3988: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 3989: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 3990: 	     i=i+ncovmodel;
 3991: 	   }
 3992: 	 } /* end k */
 3993:        } /* end k2 */
 3994:      } /* end jk */
 3995:    } /* end ng */
 3996:    fflush(ficgp); 
 3997: }  /* end gnuplot */
 3998: 
 3999: 
 4000: /*************** Moving average **************/
 4001: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4002: 
 4003:   int i, cpt, cptcod;
 4004:   int modcovmax =1;
 4005:   int mobilavrange, mob;
 4006:   double age;
 4007: 
 4008:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4009: 			   a covariate has 2 modalities */
 4010:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4011: 
 4012:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4013:     if(mobilav==1) mobilavrange=5; /* default */
 4014:     else mobilavrange=mobilav;
 4015:     for (age=bage; age<=fage; age++)
 4016:       for (i=1; i<=nlstate;i++)
 4017: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4018: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4019:     /* We keep the original values on the extreme ages bage, fage and for 
 4020:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4021:        we use a 5 terms etc. until the borders are no more concerned. 
 4022:     */ 
 4023:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4024:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4025: 	for (i=1; i<=nlstate;i++){
 4026: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4027: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4028: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4029: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4030: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4031: 	      }
 4032: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4033: 	  }
 4034: 	}
 4035:       }/* end age */
 4036:     }/* end mob */
 4037:   }else return -1;
 4038:   return 0;
 4039: }/* End movingaverage */
 4040: 
 4041: 
 4042: /************** Forecasting ******************/
 4043: 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){
 4044:   /* proj1, year, month, day of starting projection 
 4045:      agemin, agemax range of age
 4046:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4047:      anproj2 year of en of projection (same day and month as proj1).
 4048:   */
 4049:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
 4050:   int *popage;
 4051:   double agec; /* generic age */
 4052:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4053:   double *popeffectif,*popcount;
 4054:   double ***p3mat;
 4055:   double ***mobaverage;
 4056:   char fileresf[FILENAMELENGTH];
 4057: 
 4058:   agelim=AGESUP;
 4059:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4060:  
 4061:   strcpy(fileresf,"f"); 
 4062:   strcat(fileresf,fileres);
 4063:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4064:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4065:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4066:   }
 4067:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4068:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4069: 
 4070:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4071: 
 4072:   if (mobilav!=0) {
 4073:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4074:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4075:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4076:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4077:     }
 4078:   }
 4079: 
 4080:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4081:   if (stepm<=12) stepsize=1;
 4082:   if(estepm < stepm){
 4083:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4084:   }
 4085:   else  hstepm=estepm;   
 4086: 
 4087:   hstepm=hstepm/stepm; 
 4088:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4089:                                fractional in yp1 */
 4090:   anprojmean=yp;
 4091:   yp2=modf((yp1*12),&yp);
 4092:   mprojmean=yp;
 4093:   yp1=modf((yp2*30.5),&yp);
 4094:   jprojmean=yp;
 4095:   if(jprojmean==0) jprojmean=1;
 4096:   if(mprojmean==0) jprojmean=1;
 4097: 
 4098:   i1=cptcoveff;
 4099:   if (cptcovn < 1){i1=1;}
 4100:   
 4101:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4102:   
 4103:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4104: 
 4105: /* 	      if (h==(int)(YEARM*yearp)){ */
 4106:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4107:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4108:       k=k+1;
 4109:       fprintf(ficresf,"\n#******");
 4110:       for(j=1;j<=cptcoveff;j++) {
 4111: 	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]]);
 4112:       }
 4113:       fprintf(ficresf,"******\n");
 4114:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4115:       for(j=1; j<=nlstate+ndeath;j++){ 
 4116: 	for(i=1; i<=nlstate;i++) 	      
 4117:           fprintf(ficresf," p%d%d",i,j);
 4118: 	fprintf(ficresf," p.%d",j);
 4119:       }
 4120:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4121: 	fprintf(ficresf,"\n");
 4122: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4123: 
 4124:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4125: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4126: 	  nhstepm = nhstepm/hstepm; 
 4127: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4128: 	  oldm=oldms;savm=savms;
 4129: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4130: 	
 4131: 	  for (h=0; h<=nhstepm; h++){
 4132: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4133:               fprintf(ficresf,"\n");
 4134:               for(j=1;j<=cptcoveff;j++) 
 4135:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4136: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4137: 	    } 
 4138: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4139: 	      ppij=0.;
 4140: 	      for(i=1; i<=nlstate;i++) {
 4141: 		if (mobilav==1) 
 4142: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4143: 		else {
 4144: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4145: 		}
 4146: 		if (h*hstepm/YEARM*stepm== yearp) {
 4147: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4148: 		}
 4149: 	      } /* end i */
 4150: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4151: 		fprintf(ficresf," %.3f", ppij);
 4152: 	      }
 4153: 	    }/* end j */
 4154: 	  } /* end h */
 4155: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4156: 	} /* end agec */
 4157:       } /* end yearp */
 4158:     } /* end cptcod */
 4159:   } /* end  cptcov */
 4160:        
 4161:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4162: 
 4163:   fclose(ficresf);
 4164: }
 4165: 
 4166: /************** Forecasting *****not tested NB*************/
 4167: 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){
 4168:   
 4169:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4170:   int *popage;
 4171:   double calagedatem, agelim, kk1, kk2;
 4172:   double *popeffectif,*popcount;
 4173:   double ***p3mat,***tabpop,***tabpopprev;
 4174:   double ***mobaverage;
 4175:   char filerespop[FILENAMELENGTH];
 4176: 
 4177:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4178:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4179:   agelim=AGESUP;
 4180:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4181:   
 4182:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4183:   
 4184:   
 4185:   strcpy(filerespop,"pop"); 
 4186:   strcat(filerespop,fileres);
 4187:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4188:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4189:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4190:   }
 4191:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4192:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4193: 
 4194:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4195: 
 4196:   if (mobilav!=0) {
 4197:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4198:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4199:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4200:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4201:     }
 4202:   }
 4203: 
 4204:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4205:   if (stepm<=12) stepsize=1;
 4206:   
 4207:   agelim=AGESUP;
 4208:   
 4209:   hstepm=1;
 4210:   hstepm=hstepm/stepm; 
 4211:   
 4212:   if (popforecast==1) {
 4213:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4214:       printf("Problem with population file : %s\n",popfile);exit(0);
 4215:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4216:     } 
 4217:     popage=ivector(0,AGESUP);
 4218:     popeffectif=vector(0,AGESUP);
 4219:     popcount=vector(0,AGESUP);
 4220:     
 4221:     i=1;   
 4222:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4223:    
 4224:     imx=i;
 4225:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4226:   }
 4227: 
 4228:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4229:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4230:       k=k+1;
 4231:       fprintf(ficrespop,"\n#******");
 4232:       for(j=1;j<=cptcoveff;j++) {
 4233: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4234:       }
 4235:       fprintf(ficrespop,"******\n");
 4236:       fprintf(ficrespop,"# Age");
 4237:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4238:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4239:       
 4240:       for (cpt=0; cpt<=0;cpt++) { 
 4241: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4242: 	
 4243:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4244: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4245: 	  nhstepm = nhstepm/hstepm; 
 4246: 	  
 4247: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4248: 	  oldm=oldms;savm=savms;
 4249: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4250: 	
 4251: 	  for (h=0; h<=nhstepm; h++){
 4252: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4253: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4254: 	    } 
 4255: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4256: 	      kk1=0.;kk2=0;
 4257: 	      for(i=1; i<=nlstate;i++) {	      
 4258: 		if (mobilav==1) 
 4259: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4260: 		else {
 4261: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4262: 		}
 4263: 	      }
 4264: 	      if (h==(int)(calagedatem+12*cpt)){
 4265: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4266: 		  /*fprintf(ficrespop," %.3f", kk1);
 4267: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4268: 	      }
 4269: 	    }
 4270: 	    for(i=1; i<=nlstate;i++){
 4271: 	      kk1=0.;
 4272: 		for(j=1; j<=nlstate;j++){
 4273: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4274: 		}
 4275: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4276: 	    }
 4277: 
 4278: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4279: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4280: 	  }
 4281: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4282: 	}
 4283:       }
 4284:  
 4285:   /******/
 4286: 
 4287:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4288: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4289: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4290: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4291: 	  nhstepm = nhstepm/hstepm; 
 4292: 	  
 4293: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4294: 	  oldm=oldms;savm=savms;
 4295: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4296: 	  for (h=0; h<=nhstepm; h++){
 4297: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4298: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4299: 	    } 
 4300: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4301: 	      kk1=0.;kk2=0;
 4302: 	      for(i=1; i<=nlstate;i++) {	      
 4303: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4304: 	      }
 4305: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4306: 	    }
 4307: 	  }
 4308: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4309: 	}
 4310:       }
 4311:    } 
 4312:   }
 4313:  
 4314:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4315: 
 4316:   if (popforecast==1) {
 4317:     free_ivector(popage,0,AGESUP);
 4318:     free_vector(popeffectif,0,AGESUP);
 4319:     free_vector(popcount,0,AGESUP);
 4320:   }
 4321:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4322:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4323:   fclose(ficrespop);
 4324: } /* End of popforecast */
 4325: 
 4326: int fileappend(FILE *fichier, char *optionfich)
 4327: {
 4328:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4329:     printf("Problem with file: %s\n", optionfich);
 4330:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4331:     return (0);
 4332:   }
 4333:   fflush(fichier);
 4334:   return (1);
 4335: }
 4336: 
 4337: 
 4338: /**************** function prwizard **********************/
 4339: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4340: {
 4341: 
 4342:   /* Wizard to print covariance matrix template */
 4343: 
 4344:   char ca[32], cb[32], cc[32];
 4345:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
 4346:   int numlinepar;
 4347: 
 4348:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4349:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4350:   for(i=1; i <=nlstate; i++){
 4351:     jj=0;
 4352:     for(j=1; j <=nlstate+ndeath; j++){
 4353:       if(j==i) continue;
 4354:       jj++;
 4355:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4356:       printf("%1d%1d",i,j);
 4357:       fprintf(ficparo,"%1d%1d",i,j);
 4358:       for(k=1; k<=ncovmodel;k++){
 4359: 	/* 	  printf(" %lf",param[i][j][k]); */
 4360: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4361: 	printf(" 0.");
 4362: 	fprintf(ficparo," 0.");
 4363:       }
 4364:       printf("\n");
 4365:       fprintf(ficparo,"\n");
 4366:     }
 4367:   }
 4368:   printf("# Scales (for hessian or gradient estimation)\n");
 4369:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4370:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4371:   for(i=1; i <=nlstate; i++){
 4372:     jj=0;
 4373:     for(j=1; j <=nlstate+ndeath; j++){
 4374:       if(j==i) continue;
 4375:       jj++;
 4376:       fprintf(ficparo,"%1d%1d",i,j);
 4377:       printf("%1d%1d",i,j);
 4378:       fflush(stdout);
 4379:       for(k=1; k<=ncovmodel;k++){
 4380: 	/* 	printf(" %le",delti3[i][j][k]); */
 4381: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4382: 	printf(" 0.");
 4383: 	fprintf(ficparo," 0.");
 4384:       }
 4385:       numlinepar++;
 4386:       printf("\n");
 4387:       fprintf(ficparo,"\n");
 4388:     }
 4389:   }
 4390:   printf("# Covariance matrix\n");
 4391: /* # 121 Var(a12)\n\ */
 4392: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4393: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4394: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4395: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4396: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4397: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4398: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4399:   fflush(stdout);
 4400:   fprintf(ficparo,"# Covariance matrix\n");
 4401:   /* # 121 Var(a12)\n\ */
 4402:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4403:   /* #   ...\n\ */
 4404:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4405:   
 4406:   for(itimes=1;itimes<=2;itimes++){
 4407:     jj=0;
 4408:     for(i=1; i <=nlstate; i++){
 4409:       for(j=1; j <=nlstate+ndeath; j++){
 4410: 	if(j==i) continue;
 4411: 	for(k=1; k<=ncovmodel;k++){
 4412: 	  jj++;
 4413: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4414: 	  if(itimes==1){
 4415: 	    printf("#%1d%1d%d",i,j,k);
 4416: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4417: 	  }else{
 4418: 	    printf("%1d%1d%d",i,j,k);
 4419: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4420: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4421: 	  }
 4422: 	  ll=0;
 4423: 	  for(li=1;li <=nlstate; li++){
 4424: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4425: 	      if(lj==li) continue;
 4426: 	      for(lk=1;lk<=ncovmodel;lk++){
 4427: 		ll++;
 4428: 		if(ll<=jj){
 4429: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4430: 		  if(ll<jj){
 4431: 		    if(itimes==1){
 4432: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4433: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4434: 		    }else{
 4435: 		      printf(" 0.");
 4436: 		      fprintf(ficparo," 0.");
 4437: 		    }
 4438: 		  }else{
 4439: 		    if(itimes==1){
 4440: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4441: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4442: 		    }else{
 4443: 		      printf(" 0.");
 4444: 		      fprintf(ficparo," 0.");
 4445: 		    }
 4446: 		  }
 4447: 		}
 4448: 	      } /* end lk */
 4449: 	    } /* end lj */
 4450: 	  } /* end li */
 4451: 	  printf("\n");
 4452: 	  fprintf(ficparo,"\n");
 4453: 	  numlinepar++;
 4454: 	} /* end k*/
 4455:       } /*end j */
 4456:     } /* end i */
 4457:   } /* end itimes */
 4458: 
 4459: } /* end of prwizard */
 4460: /******************* Gompertz Likelihood ******************************/
 4461: double gompertz(double x[])
 4462: { 
 4463:   double A,B,L=0.0,sump=0.,num=0.;
 4464:   int i,n=0; /* n is the size of the sample */
 4465: 
 4466:   for (i=0;i<=imx-1 ; i++) {
 4467:     sump=sump+weight[i];
 4468:     /*    sump=sump+1;*/
 4469:     num=num+1;
 4470:   }
 4471:  
 4472:  
 4473:   /* for (i=0; i<=imx; i++) 
 4474:      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]);*/
 4475: 
 4476:   for (i=1;i<=imx ; i++)
 4477:     {
 4478:       if (cens[i] == 1 && wav[i]>1)
 4479: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4480:       
 4481:       if (cens[i] == 0 && wav[i]>1)
 4482: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4483: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4484:       
 4485:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4486:       if (wav[i] > 1 ) { /* ??? */
 4487: 	L=L+A*weight[i];
 4488: 	/* 	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]);*/
 4489:       }
 4490:     }
 4491: 
 4492:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4493:  
 4494:   return -2*L*num/sump;
 4495: }
 4496: 
 4497: #ifdef GSL
 4498: /******************* Gompertz_f Likelihood ******************************/
 4499: double gompertz_f(const gsl_vector *v, void *params)
 4500: { 
 4501:   double A,B,LL=0.0,sump=0.,num=0.;
 4502:   double *x= (double *) v->data;
 4503:   int i,n=0; /* n is the size of the sample */
 4504: 
 4505:   for (i=0;i<=imx-1 ; i++) {
 4506:     sump=sump+weight[i];
 4507:     /*    sump=sump+1;*/
 4508:     num=num+1;
 4509:   }
 4510:  
 4511:  
 4512:   /* for (i=0; i<=imx; i++) 
 4513:      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]);*/
 4514:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4515:   for (i=1;i<=imx ; i++)
 4516:     {
 4517:       if (cens[i] == 1 && wav[i]>1)
 4518: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4519:       
 4520:       if (cens[i] == 0 && wav[i]>1)
 4521: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4522: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4523:       
 4524:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4525:       if (wav[i] > 1 ) { /* ??? */
 4526: 	LL=LL+A*weight[i];
 4527: 	/* 	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]);*/
 4528:       }
 4529:     }
 4530: 
 4531:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4532:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4533:  
 4534:   return -2*LL*num/sump;
 4535: }
 4536: #endif
 4537: 
 4538: /******************* Printing html file ***********/
 4539: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4540: 		  int lastpass, int stepm, int weightopt, char model[],\
 4541: 		  int imx,  double p[],double **matcov,double agemortsup){
 4542:   int i,k;
 4543: 
 4544:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4545:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4546:   for (i=1;i<=2;i++) 
 4547:     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]));
 4548:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4549:   fprintf(fichtm,"</ul>");
 4550: 
 4551: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4552: 
 4553:  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>");
 4554: 
 4555:  for (k=agegomp;k<(agemortsup-2);k++) 
 4556:    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]);
 4557: 
 4558:  
 4559:   fflush(fichtm);
 4560: }
 4561: 
 4562: /******************* Gnuplot file **************/
 4563: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4564: 
 4565:   char dirfileres[132],optfileres[132];
 4566:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
 4567:   int ng;
 4568: 
 4569: 
 4570:   /*#ifdef windows */
 4571:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4572:     /*#endif */
 4573: 
 4574: 
 4575:   strcpy(dirfileres,optionfilefiname);
 4576:   strcpy(optfileres,"vpl");
 4577:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4578:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4579:   fprintf(ficgp, "set ter png small\n set log y\n"); 
 4580:   fprintf(ficgp, "set size 0.65,0.65\n");
 4581:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4582: 
 4583: } 
 4584: 
 4585: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 4586: {
 4587: 
 4588:   /*-------- data file ----------*/
 4589:   FILE *fic;
 4590:   char dummy[]="                         ";
 4591:   int i, j, n;
 4592:   int linei, month, year,iout;
 4593:   char line[MAXLINE], linetmp[MAXLINE];
 4594:   char stra[80], strb[80];
 4595:   char *stratrunc;
 4596:   int lstra;
 4597: 
 4598: 
 4599:   if((fic=fopen(datafile,"r"))==NULL)    {
 4600:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 4601:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 4602:   }
 4603: 
 4604:   i=1;
 4605:   linei=0;
 4606:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 4607:     linei=linei+1;
 4608:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 4609:       if(line[j] == '\t')
 4610: 	line[j] = ' ';
 4611:     }
 4612:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 4613:       ;
 4614:     };
 4615:     line[j+1]=0;  /* Trims blanks at end of line */
 4616:     if(line[0]=='#'){
 4617:       fprintf(ficlog,"Comment line\n%s\n",line);
 4618:       printf("Comment line\n%s\n",line);
 4619:       continue;
 4620:     }
 4621:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 4622:     for (j=0; line[j]!='\0';j++){
 4623:       line[j]=linetmp[j];
 4624:     }
 4625:   
 4626: 
 4627:     for (j=maxwav;j>=1;j--){
 4628:       cutv(stra, strb, line, ' '); 
 4629:       if(strb[0]=='.') { /* Missing status */
 4630: 	lval=-1;
 4631:       }else{
 4632: 	errno=0;
 4633: 	lval=strtol(strb,&endptr,10); 
 4634:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 4635: 	if( strb[0]=='\0' || (*endptr != '\0')){
 4636: 	  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);
 4637: 	  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);
 4638: 	  return 1;
 4639: 	}
 4640:       }
 4641:       s[j][i]=lval;
 4642:       
 4643:       strcpy(line,stra);
 4644:       cutv(stra, strb,line,' ');
 4645:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4646:       }
 4647:       else  if(iout=sscanf(strb,"%s.") != 0){
 4648: 	month=99;
 4649: 	year=9999;
 4650:       }else{
 4651: 	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);
 4652: 	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);
 4653: 	return 1;
 4654:       }
 4655:       anint[j][i]= (double) year; 
 4656:       mint[j][i]= (double)month; 
 4657:       strcpy(line,stra);
 4658:     } /* ENd Waves */
 4659:     
 4660:     cutv(stra, strb,line,' '); 
 4661:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4662:     }
 4663:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 4664:       month=99;
 4665:       year=9999;
 4666:     }else{
 4667:       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);
 4668: 	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);
 4669: 	return 1;
 4670:     }
 4671:     andc[i]=(double) year; 
 4672:     moisdc[i]=(double) month; 
 4673:     strcpy(line,stra);
 4674:     
 4675:     cutv(stra, strb,line,' '); 
 4676:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 4677:     }
 4678:     else  if(iout=sscanf(strb,"%s.") != 0){
 4679:       month=99;
 4680:       year=9999;
 4681:     }else{
 4682:       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);
 4683:       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);
 4684: 	return 1;
 4685:     }
 4686:     if (year==9999) {
 4687:       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);
 4688:       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);
 4689: 	return 1;
 4690: 
 4691:     }
 4692:     annais[i]=(double)(year);
 4693:     moisnais[i]=(double)(month); 
 4694:     strcpy(line,stra);
 4695:     
 4696:     cutv(stra, strb,line,' '); 
 4697:     errno=0;
 4698:     dval=strtod(strb,&endptr); 
 4699:     if( strb[0]=='\0' || (*endptr != '\0')){
 4700:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 4701:       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);
 4702:       fflush(ficlog);
 4703:       return 1;
 4704:     }
 4705:     weight[i]=dval; 
 4706:     strcpy(line,stra);
 4707:     
 4708:     for (j=ncovcol;j>=1;j--){
 4709:       cutv(stra, strb,line,' '); 
 4710:       if(strb[0]=='.') { /* Missing status */
 4711: 	lval=-1;
 4712:       }else{
 4713: 	errno=0;
 4714: 	lval=strtol(strb,&endptr,10); 
 4715: 	if( strb[0]=='\0' || (*endptr != '\0')){
 4716: 	  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);
 4717: 	  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);
 4718: 	  return 1;
 4719: 	}
 4720:       }
 4721:       if(lval <-1 || lval >1){
 4722: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 4723:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 4724:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 4725:  For example, for multinomial values like 1, 2 and 3,\n \
 4726:  build V1=0 V2=0 for the reference value (1),\n \
 4727:         V1=1 V2=0 for (2) \n \
 4728:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 4729:  output of IMaCh is often meaningless.\n \
 4730:  Exiting.\n",lval,linei, i,line,j);
 4731: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 4732:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 4733:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 4734:  For example, for multinomial values like 1, 2 and 3,\n \
 4735:  build V1=0 V2=0 for the reference value (1),\n \
 4736:         V1=1 V2=0 for (2) \n \
 4737:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 4738:  output of IMaCh is often meaningless.\n \
 4739:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 4740: 	return 1;
 4741:       }
 4742:       covar[j][i]=(double)(lval);
 4743:       strcpy(line,stra);
 4744:     }  
 4745:     lstra=strlen(stra);
 4746:      
 4747:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 4748:       stratrunc = &(stra[lstra-9]);
 4749:       num[i]=atol(stratrunc);
 4750:     }
 4751:     else
 4752:       num[i]=atol(stra);
 4753:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 4754:       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;}*/
 4755:     
 4756:     i=i+1;
 4757:   } /* End loop reading  data */
 4758: 
 4759:   *imax=i-1; /* Number of individuals */
 4760:   fclose(fic);
 4761:  
 4762:   return (0);
 4763:   endread:
 4764:     printf("Exiting readdata: ");
 4765:     fclose(fic);
 4766:     return (1);
 4767: 
 4768: 
 4769: 
 4770: }
 4771: 
 4772: int decodemodel ( char model[], int lastobs)
 4773: {
 4774:   int i, j, k;
 4775:   int i1, j1, k1, k2;
 4776:   char modelsav[80];
 4777:    char stra[80], strb[80], strc[80], strd[80],stre[80];
 4778: 
 4779:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 4780:     j=0, j1=0, k1=1, k2=1;
 4781:     j=nbocc(model,'+'); /* j=Number of '+' */
 4782:     j1=nbocc(model,'*'); /* j1=Number of '*' */
 4783:     cptcovn=j+1; /* Number of covariates V1+V2*age+V3 =>(2 plus signs) + 1=3 
 4784: 		  but the covariates which are product must be computed and stored. */
 4785:     cptcovprod=j1; /*Number of products  V1*V2 +v3*age = 2 */
 4786:     
 4787:     strcpy(modelsav,model); 
 4788:     if (strstr(model,"AGE") !=0){
 4789:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 4790:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 4791:       return 1;
 4792:     }
 4793:     if (strstr(model,"v") !=0){
 4794:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 4795:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 4796:       return 1;
 4797:     }
 4798:     
 4799:     /* This loop fills the array Tvar from the string 'model'.*/
 4800:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 4801:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 4802:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 4803:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 4804:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 4805:     /* 	k=1 Tvar[1]=2 (from V2) */
 4806:     /* 	k=5 Tvar[5] */
 4807:     /* for (k=1; k<=cptcovn;k++) { */
 4808:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 4809:     /* 	} */
 4810:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4811:     for(k=cptcovn; k>=1;k--){
 4812:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 4813: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 
 4814: 				    */ 
 4815:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 4816:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 4817:       /*scanf("%d",i);*/
 4818:       if (strchr(strb,'*')) {  /* Model includes a product V2+V1+V4+V3*age strb=V3*age */
 4819: 	cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn: strb=V3*age strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 4820: 	if (strcmp(strc,"age")==0) { /* Vn*age */
 4821: 	  cptcovprod--;
 4822: 	  cutv(strb,stre,strd,'V'); /* stre="V3" */
 4823: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=2 ; V1+V2*age Tvar[2]=2 */
 4824: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 4825: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 4826: 	  /*printf("stre=%s ", stre);*/
 4827: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 4828: 	  cptcovprod--;
 4829: 	  cutv(strb,stre,strc,'V');
 4830: 	  Tvar[k]=atoi(stre);
 4831: 	  cptcovage++;
 4832: 	  Tage[cptcovage]=k;
 4833: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 4834: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 4835: 	  cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 4836: 	  Tvar[k]=ncovcol+k1;  /* For model-covariate k tells which data-covariate to use but
 4837: 				  because this model-covariate is a construction we invent a new column
 4838: 				  ncovcol + k1
 4839: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 4840: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 4841: 	  cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
 4842: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 4843: 	  Tvard[k1][1]=atoi(strc); /* m 1 for V1*/
 4844: 	  Tvard[k1][2]=atoi(stre); /* n 4 for V4*/
 4845: 	  Tvar[cptcovn+k2]=Tvard[k1][1]; /* Tvar[(cptcovn=4+k2=1)=5]= 1 (V1) */
 4846: 	  Tvar[cptcovn+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovn=4+(k2=1)+1)=6]= 4 (V4) */
 4847: 	  for (i=1; i<=lastobs;i++){
 4848: 	    /* Computes the new covariate which is a product of
 4849: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 */
 4850: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 4851: 	  }
 4852: 	  k1++;
 4853: 	  k2=k2+2;
 4854: 	} /* End age is not in the model */
 4855:       } /* End if model includes a product */
 4856:       else { /* no more sum */
 4857: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 4858:        /*  scanf("%d",i);*/
 4859: 	cutv(strd,strc,strb,'V');
 4860: 	Tvar[k]=atoi(strc);
 4861:       }
 4862:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 4863:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 4864: 	scanf("%d",i);*/
 4865:     } /* end of loop + */
 4866:   } /* end model */
 4867:   
 4868:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 4869:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 4870: 
 4871:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 4872:   printf("cptcovprod=%d ", cptcovprod);
 4873:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 4874: 
 4875:   scanf("%d ",i);*/
 4876: 
 4877: 
 4878:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 4879:   endread:
 4880:     printf("Exiting decodemodel: ");
 4881:     return (1);
 4882: }
 4883: 
 4884: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 4885: {
 4886:   int i, m;
 4887: 
 4888:   for (i=1; i<=imx; i++) {
 4889:     for(m=2; (m<= maxwav); m++) {
 4890:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 4891: 	anint[m][i]=9999;
 4892: 	s[m][i]=-1;
 4893:       }
 4894:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 4895: 	*nberr++;
 4896: 	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\n",(int)moisdc[i],(int)andc[i],num[i],i);
 4897: 	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\n",(int)moisdc[i],(int)andc[i],num[i],i);
 4898: 	s[m][i]=-1;
 4899:       }
 4900:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 4901: 	*nberr++;
 4902: 	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]); 
 4903: 	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]); 
 4904: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 4905:       }
 4906:     }
 4907:   }
 4908: 
 4909:   for (i=1; i<=imx; i++)  {
 4910:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 4911:     for(m=firstpass; (m<= lastpass); m++){
 4912:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 4913: 	if (s[m][i] >= nlstate+1) {
 4914: 	  if(agedc[i]>0)
 4915: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
 4916: 	      agev[m][i]=agedc[i];
 4917: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 4918: 	    else {
 4919: 	      if ((int)andc[i]!=9999){
 4920: 		nbwarn++;
 4921: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 4922: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 4923: 		agev[m][i]=-1;
 4924: 	      }
 4925: 	    }
 4926: 	}
 4927: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 4928: 				 years but with the precision of a month */
 4929: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 4930: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 4931: 	    agev[m][i]=1;
 4932: 	  else if(agev[m][i] < *agemin){ 
 4933: 	    *agemin=agev[m][i];
 4934: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 4935: 	  }
 4936: 	  else if(agev[m][i] >*agemax){
 4937: 	    *agemax=agev[m][i];
 4938: 	    printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);
 4939: 	  }
 4940: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 4941: 	  /*	 agev[m][i] = age[i]+2*m;*/
 4942: 	}
 4943: 	else { /* =9 */
 4944: 	  agev[m][i]=1;
 4945: 	  s[m][i]=-1;
 4946: 	}
 4947:       }
 4948:       else /*= 0 Unknown */
 4949: 	agev[m][i]=1;
 4950:     }
 4951:     
 4952:   }
 4953:   for (i=1; i<=imx; i++)  {
 4954:     for(m=firstpass; (m<=lastpass); m++){
 4955:       if (s[m][i] > (nlstate+ndeath)) {
 4956: 	*nberr++;
 4957: 	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);	
 4958: 	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);	
 4959: 	return 1;
 4960:       }
 4961:     }
 4962:   }
 4963: 
 4964:   /*for (i=1; i<=imx; i++){
 4965:   for (m=firstpass; (m<lastpass); m++){
 4966:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 4967: }
 4968: 
 4969: }*/
 4970: 
 4971: 
 4972:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 4973:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 4974: 
 4975:   return (0);
 4976:   endread:
 4977:     printf("Exiting calandcheckages: ");
 4978:     return (1);
 4979: }
 4980: 
 4981: 
 4982: /***********************************************/
 4983: /**************** Main Program *****************/
 4984: /***********************************************/
 4985: 
 4986: int main(int argc, char *argv[])
 4987: {
 4988: #ifdef GSL
 4989:   const gsl_multimin_fminimizer_type *T;
 4990:   size_t iteri = 0, it;
 4991:   int rval = GSL_CONTINUE;
 4992:   int status = GSL_SUCCESS;
 4993:   double ssval;
 4994: #endif
 4995:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 4996:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
 4997:   int linei, month, year,iout;
 4998:   int jj, ll, li, lj, lk, imk;
 4999:   int numlinepar=0; /* Current linenumber of parameter file */
 5000:   int itimes;
 5001:   int NDIM=2;
 5002:   int vpopbased=0;
 5003: 
 5004:   char ca[32], cb[32], cc[32];
 5005:   /*  FILE *fichtm; *//* Html File */
 5006:   /* FILE *ficgp;*/ /*Gnuplot File */
 5007:   struct stat info;
 5008:   double agedeb, agefin,hf;
 5009:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5010: 
 5011:   double fret;
 5012:   double **xi,tmp,delta;
 5013: 
 5014:   double dum; /* Dummy variable */
 5015:   double ***p3mat;
 5016:   double ***mobaverage;
 5017:   int *indx;
 5018:   char line[MAXLINE], linepar[MAXLINE];
 5019:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5020:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5021:   char **bp, *tok, *val; /* pathtot */
 5022:   int firstobs=1, lastobs=10;
 5023:   int sdeb, sfin; /* Status at beginning and end */
 5024:   int c,  h , cpt,l;
 5025:   int ju,jl, mi;
 5026:   int i1,j1, jk,aa,bb, stepsize, ij;
 5027:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
 5028:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5029:   int mobilav=0,popforecast=0;
 5030:   int hstepm, nhstepm;
 5031:   int agemortsup;
 5032:   float  sumlpop=0.;
 5033:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5034:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5035: 
 5036:   double bage, fage, age, agelim, agebase;
 5037:   double ftolpl=FTOL;
 5038:   double **prlim;
 5039:   double ***param; /* Matrix of parameters */
 5040:   double  *p;
 5041:   double **matcov; /* Matrix of covariance */
 5042:   double ***delti3; /* Scale */
 5043:   double *delti; /* Scale */
 5044:   double ***eij, ***vareij;
 5045:   double **varpl; /* Variances of prevalence limits by age */
 5046:   double *epj, vepp;
 5047:   double kk1, kk2;
 5048:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5049:   double **ximort;
 5050:   char *alph[]={"a","a","b","c","d","e"}, str[4];
 5051:   int *dcwave;
 5052: 
 5053:   char z[1]="c", occ;
 5054: 
 5055:   /*char  *strt;*/
 5056:   char strtend[80];
 5057: 
 5058:   long total_usecs;
 5059:  
 5060: /*   setlocale (LC_ALL, ""); */
 5061: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5062: /*   textdomain (PACKAGE); */
 5063: /*   setlocale (LC_CTYPE, ""); */
 5064: /*   setlocale (LC_MESSAGES, ""); */
 5065: 
 5066:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5067:   (void) gettimeofday(&start_time,&tzp);
 5068:   curr_time=start_time;
 5069:   tm = *localtime(&start_time.tv_sec);
 5070:   tmg = *gmtime(&start_time.tv_sec);
 5071:   strcpy(strstart,asctime(&tm));
 5072: 
 5073: /*  printf("Localtime (at start)=%s",strstart); */
 5074: /*  tp.tv_sec = tp.tv_sec +86400; */
 5075: /*  tm = *localtime(&start_time.tv_sec); */
 5076: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5077: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5078: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5079: /*   tp.tv_sec = mktime(&tmg); */
 5080: /*   strt=asctime(&tmg); */
 5081: /*   printf("Time(after) =%s",strstart);  */
 5082: /*  (void) time (&time_value);
 5083: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5084: *  tm = *localtime(&time_value);
 5085: *  strstart=asctime(&tm);
 5086: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5087: */
 5088: 
 5089:   nberr=0; /* Number of errors and warnings */
 5090:   nbwarn=0;
 5091:   getcwd(pathcd, size);
 5092: 
 5093:   printf("\n%s\n%s",version,fullversion);
 5094:   if(argc <=1){
 5095:     printf("\nEnter the parameter file name: ");
 5096:     fgets(pathr,FILENAMELENGTH,stdin);
 5097:     i=strlen(pathr);
 5098:     if(pathr[i-1]=='\n')
 5099:       pathr[i-1]='\0';
 5100:    for (tok = pathr; tok != NULL; ){
 5101:       printf("Pathr |%s|\n",pathr);
 5102:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5103:       printf("val= |%s| pathr=%s\n",val,pathr);
 5104:       strcpy (pathtot, val);
 5105:       if(pathr[0] == '\0') break; /* Dirty */
 5106:     }
 5107:   }
 5108:   else{
 5109:     strcpy(pathtot,argv[1]);
 5110:   }
 5111:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5112:   /*cygwin_split_path(pathtot,path,optionfile);
 5113:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5114:   /* cutv(path,optionfile,pathtot,'\\');*/
 5115: 
 5116:   /* Split argv[0], imach program to get pathimach */
 5117:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5118:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5119:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5120:  /*   strcpy(pathimach,argv[0]); */
 5121:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5122:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5123:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5124:   chdir(path); /* Can be a relative path */
 5125:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5126:     printf("Current directory %s!\n",pathcd);
 5127:   strcpy(command,"mkdir ");
 5128:   strcat(command,optionfilefiname);
 5129:   if((outcmd=system(command)) != 0){
 5130:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5131:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5132:     /* fclose(ficlog); */
 5133: /*     exit(1); */
 5134:   }
 5135: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5136: /*     perror("mkdir"); */
 5137: /*   } */
 5138: 
 5139:   /*-------- arguments in the command line --------*/
 5140: 
 5141:   /* Log file */
 5142:   strcat(filelog, optionfilefiname);
 5143:   strcat(filelog,".log");    /* */
 5144:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5145:     printf("Problem with logfile %s\n",filelog);
 5146:     goto end;
 5147:   }
 5148:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5149:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5150:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5151:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5152:  path=%s \n\
 5153:  optionfile=%s\n\
 5154:  optionfilext=%s\n\
 5155:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5156: 
 5157:   printf("Local time (at start):%s",strstart);
 5158:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5159:   fflush(ficlog);
 5160: /*   (void) gettimeofday(&curr_time,&tzp); */
 5161: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
 5162: 
 5163:   /* */
 5164:   strcpy(fileres,"r");
 5165:   strcat(fileres, optionfilefiname);
 5166:   strcat(fileres,".txt");    /* Other files have txt extension */
 5167: 
 5168:   /*---------arguments file --------*/
 5169: 
 5170:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5171:     printf("Problem with optionfile %s\n",optionfile);
 5172:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
 5173:     fflush(ficlog);
 5174:     goto end;
 5175:   }
 5176: 
 5177: 
 5178: 
 5179:   strcpy(filereso,"o");
 5180:   strcat(filereso,fileres);
 5181:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5182:     printf("Problem with Output resultfile: %s\n", filereso);
 5183:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5184:     fflush(ficlog);
 5185:     goto end;
 5186:   }
 5187: 
 5188:   /* Reads comments: lines beginning with '#' */
 5189:   numlinepar=0;
 5190:   while((c=getc(ficpar))=='#' && c!= EOF){
 5191:     ungetc(c,ficpar);
 5192:     fgets(line, MAXLINE, ficpar);
 5193:     numlinepar++;
 5194:     fputs(line,stdout);
 5195:     fputs(line,ficparo);
 5196:     fputs(line,ficlog);
 5197:   }
 5198:   ungetc(c,ficpar);
 5199: 
 5200:   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);
 5201:   numlinepar++;
 5202:   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);
 5203:   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);
 5204:   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);
 5205:   fflush(ficlog);
 5206:   while((c=getc(ficpar))=='#' && c!= EOF){
 5207:     ungetc(c,ficpar);
 5208:     fgets(line, MAXLINE, ficpar);
 5209:     numlinepar++;
 5210:     fputs(line, stdout);
 5211:     //puts(line);
 5212:     fputs(line,ficparo);
 5213:     fputs(line,ficlog);
 5214:   }
 5215:   ungetc(c,ficpar);
 5216: 
 5217:    
 5218:   covar=matrix(0,NCOVMAX,1,n); 
 5219:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5220:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5221:      v1+v2*age+v2*v3 makes cptcovn = 3
 5222:   */
 5223:   if (strlen(model)>1) 
 5224:     cptcovn=nbocc(model,'+')+1;
 5225:   /* ncovprod */
 5226:   ncovmodel=2+cptcovn; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
 5227:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5228:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5229:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5230:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5231:     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);
 5232:     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);
 5233:     fflush(stdout);
 5234:     fclose (ficlog);
 5235:     goto end;
 5236:   }
 5237:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5238:   delti=delti3[1][1];
 5239:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5240:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5241:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5242:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5243:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5244:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5245:     fclose (ficparo);
 5246:     fclose (ficlog);
 5247:     goto end;
 5248:     exit(0);
 5249:   }
 5250:   else if(mle==-3) {
 5251:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5252:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5253:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5254:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5255:     matcov=matrix(1,npar,1,npar);
 5256:   }
 5257:   else{
 5258:     /* Read guess parameters */
 5259:     /* Reads comments: lines beginning with '#' */
 5260:     while((c=getc(ficpar))=='#' && c!= EOF){
 5261:       ungetc(c,ficpar);
 5262:       fgets(line, MAXLINE, ficpar);
 5263:       numlinepar++;
 5264:       fputs(line,stdout);
 5265:       fputs(line,ficparo);
 5266:       fputs(line,ficlog);
 5267:     }
 5268:     ungetc(c,ficpar);
 5269:     
 5270:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5271:     for(i=1; i <=nlstate; i++){
 5272:       j=0;
 5273:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5274: 	if(jj==i) continue;
 5275: 	j++;
 5276: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5277: 	if ((i1 != i) && (j1 != j)){
 5278: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5279: It might be a problem of design; if ncovcol and the model are correct\n \
 5280: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5281: 	  exit(1);
 5282: 	}
 5283: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5284: 	if(mle==1)
 5285: 	  printf("%1d%1d",i,j);
 5286: 	fprintf(ficlog,"%1d%1d",i,j);
 5287: 	for(k=1; k<=ncovmodel;k++){
 5288: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5289: 	  if(mle==1){
 5290: 	    printf(" %lf",param[i][j][k]);
 5291: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5292: 	  }
 5293: 	  else
 5294: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5295: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5296: 	}
 5297: 	fscanf(ficpar,"\n");
 5298: 	numlinepar++;
 5299: 	if(mle==1)
 5300: 	  printf("\n");
 5301: 	fprintf(ficlog,"\n");
 5302: 	fprintf(ficparo,"\n");
 5303:       }
 5304:     }  
 5305:     fflush(ficlog);
 5306: 
 5307:     p=param[1][1];
 5308:     
 5309:     /* Reads comments: lines beginning with '#' */
 5310:     while((c=getc(ficpar))=='#' && c!= EOF){
 5311:       ungetc(c,ficpar);
 5312:       fgets(line, MAXLINE, ficpar);
 5313:       numlinepar++;
 5314:       fputs(line,stdout);
 5315:       fputs(line,ficparo);
 5316:       fputs(line,ficlog);
 5317:     }
 5318:     ungetc(c,ficpar);
 5319: 
 5320:     for(i=1; i <=nlstate; i++){
 5321:       for(j=1; j <=nlstate+ndeath-1; j++){
 5322: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5323: 	if ((i1-i)*(j1-j)!=0){
 5324: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5325: 	  exit(1);
 5326: 	}
 5327: 	printf("%1d%1d",i,j);
 5328: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5329: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5330: 	for(k=1; k<=ncovmodel;k++){
 5331: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5332: 	  printf(" %le",delti3[i][j][k]);
 5333: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5334: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5335: 	}
 5336: 	fscanf(ficpar,"\n");
 5337: 	numlinepar++;
 5338: 	printf("\n");
 5339: 	fprintf(ficparo,"\n");
 5340: 	fprintf(ficlog,"\n");
 5341:       }
 5342:     }
 5343:     fflush(ficlog);
 5344: 
 5345:     delti=delti3[1][1];
 5346: 
 5347: 
 5348:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5349:   
 5350:     /* Reads comments: lines beginning with '#' */
 5351:     while((c=getc(ficpar))=='#' && c!= EOF){
 5352:       ungetc(c,ficpar);
 5353:       fgets(line, MAXLINE, ficpar);
 5354:       numlinepar++;
 5355:       fputs(line,stdout);
 5356:       fputs(line,ficparo);
 5357:       fputs(line,ficlog);
 5358:     }
 5359:     ungetc(c,ficpar);
 5360:   
 5361:     matcov=matrix(1,npar,1,npar);
 5362:     for(i=1; i <=npar; i++)
 5363:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 5364:       
 5365:     for(i=1; i <=npar; i++){
 5366:       fscanf(ficpar,"%s",&str);
 5367:       if(mle==1)
 5368: 	printf("%s",str);
 5369:       fprintf(ficlog,"%s",str);
 5370:       fprintf(ficparo,"%s",str);
 5371:       for(j=1; j <=i; j++){
 5372: 	fscanf(ficpar," %le",&matcov[i][j]);
 5373: 	if(mle==1){
 5374: 	  printf(" %.5le",matcov[i][j]);
 5375: 	}
 5376: 	fprintf(ficlog," %.5le",matcov[i][j]);
 5377: 	fprintf(ficparo," %.5le",matcov[i][j]);
 5378:       }
 5379:       fscanf(ficpar,"\n");
 5380:       numlinepar++;
 5381:       if(mle==1)
 5382: 	printf("\n");
 5383:       fprintf(ficlog,"\n");
 5384:       fprintf(ficparo,"\n");
 5385:     }
 5386:     for(i=1; i <=npar; i++)
 5387:       for(j=i+1;j<=npar;j++)
 5388: 	matcov[i][j]=matcov[j][i];
 5389:     
 5390:     if(mle==1)
 5391:       printf("\n");
 5392:     fprintf(ficlog,"\n");
 5393:     
 5394:     fflush(ficlog);
 5395:     
 5396:     /*-------- Rewriting parameter file ----------*/
 5397:     strcpy(rfileres,"r");    /* "Rparameterfile */
 5398:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 5399:     strcat(rfileres,".");    /* */
 5400:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 5401:     if((ficres =fopen(rfileres,"w"))==NULL) {
 5402:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 5403:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 5404:     }
 5405:     fprintf(ficres,"#%s\n",version);
 5406:   }    /* End of mle != -3 */
 5407: 
 5408: 
 5409:   n= lastobs;
 5410:   num=lvector(1,n);
 5411:   moisnais=vector(1,n);
 5412:   annais=vector(1,n);
 5413:   moisdc=vector(1,n);
 5414:   andc=vector(1,n);
 5415:   agedc=vector(1,n);
 5416:   cod=ivector(1,n);
 5417:   weight=vector(1,n);
 5418:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 5419:   mint=matrix(1,maxwav,1,n);
 5420:   anint=matrix(1,maxwav,1,n);
 5421:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 5422:   tab=ivector(1,NCOVMAX);
 5423:   ncodemax=ivector(1,8); /* hard coded ? */
 5424: 
 5425:   /* Reads data from file datafile */
 5426:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 5427:     goto end;
 5428: 
 5429:   /* Calculation of the number of parameters from char model */
 5430:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 5431: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 5432: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 5433: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 5434: 	k=1 Tvar[1]=2 (from V2)
 5435:     */
 5436:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 5437:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 5438:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 5439:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 5440:   */
 5441:   /* For model-covariate k tells which data-covariate to use but
 5442:     because this model-covariate is a construction we invent a new column
 5443:     ncovcol + k1
 5444:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 5445:     Tvar[3=V1*V4]=4+1 etc */
 5446:   Tprod=ivector(1,15); /* Gives the position of a product */
 5447:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 5448:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 5449:   */
 5450:   Tvaraff=ivector(1,15); 
 5451:   Tvard=imatrix(1,15,1,2); /* n=Tvard[k1][1]  and m=Tvard[k1][2] gives the couple n,m of the k1 th product Vn*Vm
 5452: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 5453: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 5454:   Tage=ivector(1,15); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 5455: 			 4 covariates (3 plus signs)
 5456: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 5457: 		      */  
 5458: 
 5459:   if(decodemodel(model, lastobs) == 1)
 5460:     goto end;
 5461: 
 5462:   if((double)(lastobs-imx)/(double)imx > 1.10){
 5463:     nbwarn++;
 5464:     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); 
 5465:     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); 
 5466:   }
 5467:     /*  if(mle==1){*/
 5468:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 5469:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 5470:   }
 5471: 
 5472:     /*-calculation of age at interview from date of interview and age at death -*/
 5473:   agev=matrix(1,maxwav,1,imx);
 5474: 
 5475:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 5476:     goto end;
 5477: 
 5478: 
 5479:   agegomp=(int)agemin;
 5480:   free_vector(moisnais,1,n);
 5481:   free_vector(annais,1,n);
 5482:   /* free_matrix(mint,1,maxwav,1,n);
 5483:      free_matrix(anint,1,maxwav,1,n);*/
 5484:   free_vector(moisdc,1,n);
 5485:   free_vector(andc,1,n);
 5486: 
 5487:    
 5488:   wav=ivector(1,imx);
 5489:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 5490:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 5491:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 5492:    
 5493:   /* Concatenates waves */
 5494:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 5495: 
 5496:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 5497: 
 5498:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 5499:   ncodemax[1]=1;
 5500:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
 5501:       
 5502:   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
 5503: 				 the estimations*/
 5504:   h=0;
 5505:   m=pow(2,cptcoveff);
 5506:  
 5507:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 5508:     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 */ 
 5509:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 5510: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 5511: 	  h++;
 5512: 	  if (h>m) 
 5513: 	    h=1;
 5514: 	  /**< codtab(h,k)  k
 5515: 	   *     h     1     2     3     4
 5516: 	   *______________________________  
 5517: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 5518: 	   *     2     2     1     1     1
 5519: 	   *     3 i=2 1     2     1     1
 5520: 	   *     4     2     2     1     1
 5521: 	   *     5 i=3 1 i=2 1     2     1
 5522: 	   *     6     2     1     2     1
 5523: 	   *     7 i=4 1     2     2     1
 5524: 	   *     8     2     2     2     1
 5525: 	   *     9 i=5 1 i=3 1 i=2 1     1
 5526: 	   *    10     2     1     1     1
 5527: 	   *    11 i=6 1     2     1     1
 5528: 	   *    12     2     2     1     1
 5529: 	   *    13 i=7 1 i=4 1     2     1    
 5530: 	   *    14     2     1     2     1
 5531: 	   *    15 i=8 1     2     2     1
 5532: 	   *    16     2     2     2     1
 5533: 	   */
 5534: 	  codtab[h][k]=j;
 5535: 	  codtab[h][Tvar[k]]=j;
 5536: 	  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]]);
 5537: 	} 
 5538:       }
 5539:     }
 5540:   } 
 5541:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 5542:      codtab[1][2]=1;codtab[2][2]=2; */
 5543:   /* for(i=1; i <=m ;i++){ 
 5544:      for(k=1; k <=cptcovn; k++){
 5545:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 5546:      }
 5547:      printf("\n");
 5548:      }
 5549:      scanf("%d",i);*/
 5550:     
 5551:   /*------------ gnuplot -------------*/
 5552:   strcpy(optionfilegnuplot,optionfilefiname);
 5553:   if(mle==-3)
 5554:     strcat(optionfilegnuplot,"-mort");
 5555:   strcat(optionfilegnuplot,".gp");
 5556: 
 5557:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 5558:     printf("Problem with file %s",optionfilegnuplot);
 5559:   }
 5560:   else{
 5561:     fprintf(ficgp,"\n# %s\n", version); 
 5562:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 5563:     //fprintf(ficgp,"set missing 'NaNq'\n");
 5564:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 5565:   }
 5566:   /*  fclose(ficgp);*/
 5567:   /*--------- index.htm --------*/
 5568: 
 5569:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 5570:   if(mle==-3)
 5571:     strcat(optionfilehtm,"-mort");
 5572:   strcat(optionfilehtm,".htm");
 5573:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 5574:     printf("Problem with %s \n",optionfilehtm);
 5575:     exit(0);
 5576:   }
 5577: 
 5578:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 5579:   strcat(optionfilehtmcov,"-cov.htm");
 5580:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 5581:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 5582:   }
 5583:   else{
 5584:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5585: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 5586: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 5587: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5588:   }
 5589: 
 5590:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5591: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 5592: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 5593: \n\
 5594: <hr  size=\"2\" color=\"#EC5E5E\">\
 5595:  <ul><li><h4>Parameter files</h4>\n\
 5596:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 5597:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 5598:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 5599:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 5600:  - Date and time at start: %s</ul>\n",\
 5601: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 5602: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 5603: 	  fileres,fileres,\
 5604: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 5605:   fflush(fichtm);
 5606: 
 5607:   strcpy(pathr,path);
 5608:   strcat(pathr,optionfilefiname);
 5609:   chdir(optionfilefiname); /* Move to directory named optionfile */
 5610:   
 5611:   /* Calculates basic frequencies. Computes observed prevalence at single age
 5612:      and prints on file fileres'p'. */
 5613:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 5614: 
 5615:   fprintf(fichtm,"\n");
 5616:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 5617: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 5618: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 5619: 	  imx,agemin,agemax,jmin,jmax,jmean);
 5620:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5621:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5622:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5623:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 5624:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 5625:     
 5626:    
 5627:   /* For Powell, parameters are in a vector p[] starting at p[1]
 5628:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 5629:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 5630: 
 5631:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 5632: 
 5633:   if (mle==-3){
 5634:     ximort=matrix(1,NDIM,1,NDIM); 
 5635: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 5636:     cens=ivector(1,n);
 5637:     ageexmed=vector(1,n);
 5638:     agecens=vector(1,n);
 5639:     dcwave=ivector(1,n);
 5640:  
 5641:     for (i=1; i<=imx; i++){
 5642:       dcwave[i]=-1;
 5643:       for (m=firstpass; m<=lastpass; m++)
 5644: 	if (s[m][i]>nlstate) {
 5645: 	  dcwave[i]=m;
 5646: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 5647: 	  break;
 5648: 	}
 5649:     }
 5650: 
 5651:     for (i=1; i<=imx; i++) {
 5652:       if (wav[i]>0){
 5653: 	ageexmed[i]=agev[mw[1][i]][i];
 5654: 	j=wav[i];
 5655: 	agecens[i]=1.; 
 5656: 
 5657: 	if (ageexmed[i]> 1 && wav[i] > 0){
 5658: 	  agecens[i]=agev[mw[j][i]][i];
 5659: 	  cens[i]= 1;
 5660: 	}else if (ageexmed[i]< 1) 
 5661: 	  cens[i]= -1;
 5662: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 5663: 	  cens[i]=0 ;
 5664:       }
 5665:       else cens[i]=-1;
 5666:     }
 5667:     
 5668:     for (i=1;i<=NDIM;i++) {
 5669:       for (j=1;j<=NDIM;j++)
 5670: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 5671:     }
 5672:     
 5673:     p[1]=0.0268; p[NDIM]=0.083;
 5674:     /*printf("%lf %lf", p[1], p[2]);*/
 5675:     
 5676:     
 5677: #ifdef GSL
 5678:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 5679: #elsedef
 5680:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 5681: #endif
 5682:     strcpy(filerespow,"pow-mort"); 
 5683:     strcat(filerespow,fileres);
 5684:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 5685:       printf("Problem with resultfile: %s\n", filerespow);
 5686:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 5687:     }
 5688: #ifdef GSL
 5689:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 5690: #elsedef
 5691:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 5692: #endif
 5693:     /*  for (i=1;i<=nlstate;i++)
 5694: 	for(j=1;j<=nlstate+ndeath;j++)
 5695: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 5696:     */
 5697:     fprintf(ficrespow,"\n");
 5698: #ifdef GSL
 5699:     /* gsl starts here */ 
 5700:     T = gsl_multimin_fminimizer_nmsimplex;
 5701:     gsl_multimin_fminimizer *sfm = NULL;
 5702:     gsl_vector *ss, *x;
 5703:     gsl_multimin_function minex_func;
 5704: 
 5705:     /* Initial vertex size vector */
 5706:     ss = gsl_vector_alloc (NDIM);
 5707:     
 5708:     if (ss == NULL){
 5709:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 5710:     }
 5711:     /* Set all step sizes to 1 */
 5712:     gsl_vector_set_all (ss, 0.001);
 5713: 
 5714:     /* Starting point */
 5715:     
 5716:     x = gsl_vector_alloc (NDIM);
 5717:     
 5718:     if (x == NULL){
 5719:       gsl_vector_free(ss);
 5720:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 5721:     }
 5722:   
 5723:     /* Initialize method and iterate */
 5724:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 5725: /*     gsl_vector_set(x, 0, 0.0268); */
 5726: /*     gsl_vector_set(x, 1, 0.083); */
 5727:     gsl_vector_set(x, 0, p[1]);
 5728:     gsl_vector_set(x, 1, p[2]);
 5729: 
 5730:     minex_func.f = &gompertz_f;
 5731:     minex_func.n = NDIM;
 5732:     minex_func.params = (void *)&p; /* ??? */
 5733:     
 5734:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 5735:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 5736:     
 5737:     printf("Iterations beginning .....\n\n");
 5738:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 5739: 
 5740:     iteri=0;
 5741:     while (rval == GSL_CONTINUE){
 5742:       iteri++;
 5743:       status = gsl_multimin_fminimizer_iterate(sfm);
 5744:       
 5745:       if (status) printf("error: %s\n", gsl_strerror (status));
 5746:       fflush(0);
 5747:       
 5748:       if (status) 
 5749:         break;
 5750:       
 5751:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 5752:       ssval = gsl_multimin_fminimizer_size (sfm);
 5753:       
 5754:       if (rval == GSL_SUCCESS)
 5755:         printf ("converged to a local maximum at\n");
 5756:       
 5757:       printf("%5d ", iteri);
 5758:       for (it = 0; it < NDIM; it++){
 5759: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 5760:       }
 5761:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 5762:     }
 5763:     
 5764:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 5765:     
 5766:     gsl_vector_free(x); /* initial values */
 5767:     gsl_vector_free(ss); /* inital step size */
 5768:     for (it=0; it<NDIM; it++){
 5769:       p[it+1]=gsl_vector_get(sfm->x,it);
 5770:       fprintf(ficrespow," %.12lf", p[it]);
 5771:     }
 5772:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 5773: #endif
 5774: #ifdef POWELL
 5775:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 5776: #endif  
 5777:     fclose(ficrespow);
 5778:     
 5779:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 5780: 
 5781:     for(i=1; i <=NDIM; i++)
 5782:       for(j=i+1;j<=NDIM;j++)
 5783: 	matcov[i][j]=matcov[j][i];
 5784:     
 5785:     printf("\nCovariance matrix\n ");
 5786:     for(i=1; i <=NDIM; i++) {
 5787:       for(j=1;j<=NDIM;j++){ 
 5788: 	printf("%f ",matcov[i][j]);
 5789:       }
 5790:       printf("\n ");
 5791:     }
 5792:     
 5793:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 5794:     for (i=1;i<=NDIM;i++) 
 5795:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 5796: 
 5797:     lsurv=vector(1,AGESUP);
 5798:     lpop=vector(1,AGESUP);
 5799:     tpop=vector(1,AGESUP);
 5800:     lsurv[agegomp]=100000;
 5801:     
 5802:     for (k=agegomp;k<=AGESUP;k++) {
 5803:       agemortsup=k;
 5804:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 5805:     }
 5806:     
 5807:     for (k=agegomp;k<agemortsup;k++)
 5808:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 5809:     
 5810:     for (k=agegomp;k<agemortsup;k++){
 5811:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 5812:       sumlpop=sumlpop+lpop[k];
 5813:     }
 5814:     
 5815:     tpop[agegomp]=sumlpop;
 5816:     for (k=agegomp;k<(agemortsup-3);k++){
 5817:       /*  tpop[k+1]=2;*/
 5818:       tpop[k+1]=tpop[k]-lpop[k];
 5819:     }
 5820:     
 5821:     
 5822:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 5823:     for (k=agegomp;k<(agemortsup-2);k++) 
 5824:       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]);
 5825:     
 5826:     
 5827:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 5828:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 5829:     
 5830:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 5831: 		     stepm, weightopt,\
 5832: 		     model,imx,p,matcov,agemortsup);
 5833:     
 5834:     free_vector(lsurv,1,AGESUP);
 5835:     free_vector(lpop,1,AGESUP);
 5836:     free_vector(tpop,1,AGESUP);
 5837: #ifdef GSL
 5838:     free_ivector(cens,1,n);
 5839:     free_vector(agecens,1,n);
 5840:     free_ivector(dcwave,1,n);
 5841:     free_matrix(ximort,1,NDIM,1,NDIM);
 5842: #endif
 5843:   } /* Endof if mle==-3 */
 5844:   
 5845:   else{ /* For mle >=1 */
 5846:     globpr=0;/* debug */
 5847:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5848:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5849:     for (k=1; k<=npar;k++)
 5850:       printf(" %d %8.5f",k,p[k]);
 5851:     printf("\n");
 5852:     globpr=1; /* to print the contributions */
 5853:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 5854:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 5855:     for (k=1; k<=npar;k++)
 5856:       printf(" %d %8.5f",k,p[k]);
 5857:     printf("\n");
 5858:     if(mle>=1){ /* Could be 1 or 2 */
 5859:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 5860:     }
 5861:     
 5862:     /*--------- results files --------------*/
 5863:     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);
 5864:     
 5865:     
 5866:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5867:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5868:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5869:     for(i=1,jk=1; i <=nlstate; i++){
 5870:       for(k=1; k <=(nlstate+ndeath); k++){
 5871: 	if (k != i) {
 5872: 	  printf("%d%d ",i,k);
 5873: 	  fprintf(ficlog,"%d%d ",i,k);
 5874: 	  fprintf(ficres,"%1d%1d ",i,k);
 5875: 	  for(j=1; j <=ncovmodel; j++){
 5876: 	    printf("%lf ",p[jk]);
 5877: 	    fprintf(ficlog,"%lf ",p[jk]);
 5878: 	    fprintf(ficres,"%lf ",p[jk]);
 5879: 	    jk++; 
 5880: 	  }
 5881: 	  printf("\n");
 5882: 	  fprintf(ficlog,"\n");
 5883: 	  fprintf(ficres,"\n");
 5884: 	}
 5885:       }
 5886:     }
 5887:     if(mle!=0){
 5888:       /* Computing hessian and covariance matrix */
 5889:       ftolhess=ftol; /* Usually correct */
 5890:       hesscov(matcov, p, npar, delti, ftolhess, func);
 5891:     }
 5892:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 5893:     printf("# Scales (for hessian or gradient estimation)\n");
 5894:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 5895:     for(i=1,jk=1; i <=nlstate; i++){
 5896:       for(j=1; j <=nlstate+ndeath; j++){
 5897: 	if (j!=i) {
 5898: 	  fprintf(ficres,"%1d%1d",i,j);
 5899: 	  printf("%1d%1d",i,j);
 5900: 	  fprintf(ficlog,"%1d%1d",i,j);
 5901: 	  for(k=1; k<=ncovmodel;k++){
 5902: 	    printf(" %.5e",delti[jk]);
 5903: 	    fprintf(ficlog," %.5e",delti[jk]);
 5904: 	    fprintf(ficres," %.5e",delti[jk]);
 5905: 	    jk++;
 5906: 	  }
 5907: 	  printf("\n");
 5908: 	  fprintf(ficlog,"\n");
 5909: 	  fprintf(ficres,"\n");
 5910: 	}
 5911:       }
 5912:     }
 5913:     
 5914:     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");
 5915:     if(mle>=1)
 5916:       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");
 5917:     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");
 5918:     /* # 121 Var(a12)\n\ */
 5919:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5920:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5921:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5922:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5923:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5924:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5925:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5926:     
 5927:     
 5928:     /* Just to have a covariance matrix which will be more understandable
 5929:        even is we still don't want to manage dictionary of variables
 5930:     */
 5931:     for(itimes=1;itimes<=2;itimes++){
 5932:       jj=0;
 5933:       for(i=1; i <=nlstate; i++){
 5934: 	for(j=1; j <=nlstate+ndeath; j++){
 5935: 	  if(j==i) continue;
 5936: 	  for(k=1; k<=ncovmodel;k++){
 5937: 	    jj++;
 5938: 	    ca[0]= k+'a'-1;ca[1]='\0';
 5939: 	    if(itimes==1){
 5940: 	      if(mle>=1)
 5941: 		printf("#%1d%1d%d",i,j,k);
 5942: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 5943: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 5944: 	    }else{
 5945: 	      if(mle>=1)
 5946: 		printf("%1d%1d%d",i,j,k);
 5947: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 5948: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 5949: 	    }
 5950: 	    ll=0;
 5951: 	    for(li=1;li <=nlstate; li++){
 5952: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 5953: 		if(lj==li) continue;
 5954: 		for(lk=1;lk<=ncovmodel;lk++){
 5955: 		  ll++;
 5956: 		  if(ll<=jj){
 5957: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 5958: 		    if(ll<jj){
 5959: 		      if(itimes==1){
 5960: 			if(mle>=1)
 5961: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5962: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5963: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5964: 		      }else{
 5965: 			if(mle>=1)
 5966: 			  printf(" %.5e",matcov[jj][ll]); 
 5967: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5968: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5969: 		      }
 5970: 		    }else{
 5971: 		      if(itimes==1){
 5972: 			if(mle>=1)
 5973: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 5974: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 5975: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 5976: 		      }else{
 5977: 			if(mle>=1)
 5978: 			  printf(" %.5e",matcov[jj][ll]); 
 5979: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 5980: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 5981: 		      }
 5982: 		    }
 5983: 		  }
 5984: 		} /* end lk */
 5985: 	      } /* end lj */
 5986: 	    } /* end li */
 5987: 	    if(mle>=1)
 5988: 	      printf("\n");
 5989: 	    fprintf(ficlog,"\n");
 5990: 	    fprintf(ficres,"\n");
 5991: 	    numlinepar++;
 5992: 	  } /* end k*/
 5993: 	} /*end j */
 5994:       } /* end i */
 5995:     } /* end itimes */
 5996:     
 5997:     fflush(ficlog);
 5998:     fflush(ficres);
 5999:     
 6000:     while((c=getc(ficpar))=='#' && c!= EOF){
 6001:       ungetc(c,ficpar);
 6002:       fgets(line, MAXLINE, ficpar);
 6003:       fputs(line,stdout);
 6004:       fputs(line,ficparo);
 6005:     }
 6006:     ungetc(c,ficpar);
 6007:     
 6008:     estepm=0;
 6009:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6010:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6011:     if (fage <= 2) {
 6012:       bage = ageminpar;
 6013:       fage = agemaxpar;
 6014:     }
 6015:     
 6016:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6017:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6018:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6019:     
 6020:     while((c=getc(ficpar))=='#' && c!= EOF){
 6021:       ungetc(c,ficpar);
 6022:       fgets(line, MAXLINE, ficpar);
 6023:       fputs(line,stdout);
 6024:       fputs(line,ficparo);
 6025:     }
 6026:     ungetc(c,ficpar);
 6027:     
 6028:     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);
 6029:     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);
 6030:     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);
 6031:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6032:     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);
 6033:     
 6034:     while((c=getc(ficpar))=='#' && c!= EOF){
 6035:       ungetc(c,ficpar);
 6036:       fgets(line, MAXLINE, ficpar);
 6037:       fputs(line,stdout);
 6038:       fputs(line,ficparo);
 6039:     }
 6040:     ungetc(c,ficpar);
 6041:     
 6042:     
 6043:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6044:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6045:     
 6046:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6047:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6048:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6049:     
 6050:     while((c=getc(ficpar))=='#' && c!= EOF){
 6051:       ungetc(c,ficpar);
 6052:       fgets(line, MAXLINE, ficpar);
 6053:       fputs(line,stdout);
 6054:       fputs(line,ficparo);
 6055:     }
 6056:     ungetc(c,ficpar);
 6057:     
 6058:     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);
 6059:     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);
 6060:     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);
 6061:     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);
 6062:     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);
 6063:     /* day and month of proj2 are not used but only year anproj2.*/
 6064:     
 6065:     
 6066:     
 6067:     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
 6068:     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 6069:     
 6070:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6071:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6072:     
 6073:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6074: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6075: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6076:       
 6077:    /*------------ free_vector  -------------*/
 6078:    /*  chdir(path); */
 6079:  
 6080:     free_ivector(wav,1,imx);
 6081:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6082:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6083:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6084:     free_lvector(num,1,n);
 6085:     free_vector(agedc,1,n);
 6086:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6087:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6088:     fclose(ficparo);
 6089:     fclose(ficres);
 6090: 
 6091: 
 6092:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6093:   
 6094:     strcpy(filerespl,"pl");
 6095:     strcat(filerespl,fileres);
 6096:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6097:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
 6098:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
 6099:     }
 6100:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6101:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6102:     pstamp(ficrespl);
 6103:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 6104:     fprintf(ficrespl,"#Age ");
 6105:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6106:     fprintf(ficrespl,"\n");
 6107:   
 6108:     prlim=matrix(1,nlstate,1,nlstate);
 6109: 
 6110:     agebase=ageminpar;
 6111:     agelim=agemaxpar;
 6112:     ftolpl=1.e-10;
 6113:     i1=pow(2,cptcoveff);
 6114:     if (cptcovn < 1){i1=1;}
 6115: 
 6116:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6117:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6118: 	k=k+1;
 6119: 	/* to clean */
 6120: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
 6121: 	fprintf(ficrespl,"\n#******");
 6122: 	printf("\n#******");
 6123: 	fprintf(ficlog,"\n#******");
 6124: 	for(j=1;j<=cptcoveff;j++) {
 6125: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6126: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6127: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6128: 	}
 6129: 	fprintf(ficrespl,"******\n");
 6130: 	printf("******\n");
 6131: 	fprintf(ficlog,"******\n");
 6132: 	
 6133: 	for (age=agebase; age<=agelim; age++){
 6134: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6135: 	  fprintf(ficrespl,"%.0f ",age );
 6136: 	  for(j=1;j<=cptcoveff;j++)
 6137: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6138: 	  for(i=1; i<=nlstate;i++)
 6139: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6140: 	  fprintf(ficrespl,"\n");
 6141: 	} /* Age */
 6142: 	/* was end of cptcod */
 6143:     } /* cptcov */
 6144:     fclose(ficrespl);
 6145: 
 6146:     /*------------- h Pij x at various ages ------------*/
 6147:   
 6148:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 6149:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6150:       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
 6151:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
 6152:     }
 6153:     printf("Computing pij: result on file '%s' \n", filerespij);
 6154:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6155:   
 6156:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6157:     /*if (stepm<=24) stepsize=2;*/
 6158: 
 6159:     agelim=AGESUP;
 6160:     hstepm=stepsize*YEARM; /* Every year of age */
 6161:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6162: 
 6163:     /* hstepm=1;   aff par mois*/
 6164:     pstamp(ficrespij);
 6165:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6166:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6167:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6168: 	k=k+1;
 6169: 	fprintf(ficrespij,"\n#****** ");
 6170: 	for(j=1;j<=cptcoveff;j++) 
 6171: 	  fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6172: 	fprintf(ficrespij,"******\n");
 6173: 	
 6174: 	for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6175: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6176: 	  nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6177: 
 6178: 	  /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6179: 
 6180: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6181: 	  oldm=oldms;savm=savms;
 6182: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6183: 	  fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6184: 	  for(i=1; i<=nlstate;i++)
 6185: 	    for(j=1; j<=nlstate+ndeath;j++)
 6186: 	      fprintf(ficrespij," %1d-%1d",i,j);
 6187: 	  fprintf(ficrespij,"\n");
 6188: 	  for (h=0; h<=nhstepm; h++){
 6189: 	    fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
 6190: 	    for(i=1; i<=nlstate;i++)
 6191: 	      for(j=1; j<=nlstate+ndeath;j++)
 6192: 		fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6193: 	    fprintf(ficrespij,"\n");
 6194: 	  }
 6195: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6196: 	  fprintf(ficrespij,"\n");
 6197: 	}
 6198:       }
 6199:     }
 6200: 
 6201:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6202: 
 6203:     fclose(ficrespij);
 6204: 
 6205:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6206:     for(i=1;i<=AGESUP;i++)
 6207:       for(j=1;j<=NCOVMAX;j++)
 6208: 	for(k=1;k<=NCOVMAX;k++)
 6209: 	  probs[i][j][k]=0.;
 6210: 
 6211:     /*---------- Forecasting ------------------*/
 6212:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6213:     if(prevfcast==1){
 6214:       /*    if(stepm ==1){*/
 6215:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6216:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6217:       /*      }  */
 6218:       /*      else{ */
 6219:       /*        erreur=108; */
 6220:       /*        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); */
 6221:       /*        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); */
 6222:       /*      } */
 6223:     }
 6224:   
 6225: 
 6226:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6227: 
 6228:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6229:     /*  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",\
 6230: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6231:     */
 6232: 
 6233:     if (mobilav!=0) {
 6234:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6235:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6236: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6237: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6238:       }
 6239:     }
 6240: 
 6241: 
 6242:     /*---------- Health expectancies, no variances ------------*/
 6243: 
 6244:     strcpy(filerese,"e");
 6245:     strcat(filerese,fileres);
 6246:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6247:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6248:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6249:     }
 6250:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6251:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6252:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6253:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6254: 	k=k+1; 
 6255: 	fprintf(ficreseij,"\n#****** ");
 6256: 	for(j=1;j<=cptcoveff;j++) {
 6257: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6258: 	}
 6259: 	fprintf(ficreseij,"******\n");
 6260: 
 6261: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6262: 	oldm=oldms;savm=savms;
 6263: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6264:       
 6265: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6266:       }
 6267:     }
 6268:     fclose(ficreseij);
 6269: 
 6270: 
 6271:     /*---------- Health expectancies and variances ------------*/
 6272: 
 6273: 
 6274:     strcpy(filerest,"t");
 6275:     strcat(filerest,fileres);
 6276:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6277:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6278:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6279:     }
 6280:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6281:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6282: 
 6283: 
 6284:     strcpy(fileresstde,"stde");
 6285:     strcat(fileresstde,fileres);
 6286:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6287:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6288:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6289:     }
 6290:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6291:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6292: 
 6293:     strcpy(filerescve,"cve");
 6294:     strcat(filerescve,fileres);
 6295:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6296:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6297:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6298:     }
 6299:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6300:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6301: 
 6302:     strcpy(fileresv,"v");
 6303:     strcat(fileresv,fileres);
 6304:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6305:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6306:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6307:     }
 6308:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6309:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6310: 
 6311:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6312:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6313: 	k=k+1; 
 6314: 	fprintf(ficrest,"\n#****** ");
 6315: 	for(j=1;j<=cptcoveff;j++) 
 6316: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6317: 	fprintf(ficrest,"******\n");
 6318: 
 6319: 	fprintf(ficresstdeij,"\n#****** ");
 6320: 	fprintf(ficrescveij,"\n#****** ");
 6321: 	for(j=1;j<=cptcoveff;j++) {
 6322: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6323: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6324: 	}
 6325: 	fprintf(ficresstdeij,"******\n");
 6326: 	fprintf(ficrescveij,"******\n");
 6327: 
 6328: 	fprintf(ficresvij,"\n#****** ");
 6329: 	for(j=1;j<=cptcoveff;j++) 
 6330: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6331: 	fprintf(ficresvij,"******\n");
 6332: 
 6333: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6334: 	oldm=oldms;savm=savms;
 6335: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6336:  
 6337: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6338: 	pstamp(ficrest);
 6339: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6340: 	  oldm=oldms;savm=savms;
 6341: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);	  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 ");
 6342: 	  if(vpopbased==1)
 6343: 	    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);
 6344: 	  else
 6345: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6346: 	  fprintf(ficrest,"# Age e.. (std) ");
 6347: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6348: 	  fprintf(ficrest,"\n");
 6349: 
 6350: 	  epj=vector(1,nlstate+1);
 6351: 	  for(age=bage; age <=fage ;age++){
 6352: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6353: 	    if (vpopbased==1) {
 6354: 	      if(mobilav ==0){
 6355: 		for(i=1; i<=nlstate;i++)
 6356: 		  prlim[i][i]=probs[(int)age][i][k];
 6357: 	      }else{ /* mobilav */ 
 6358: 		for(i=1; i<=nlstate;i++)
 6359: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6360: 	      }
 6361: 	    }
 6362: 	
 6363: 	    fprintf(ficrest," %4.0f",age);
 6364: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6365: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6366: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6367: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6368: 	      }
 6369: 	      epj[nlstate+1] +=epj[j];
 6370: 	    }
 6371: 
 6372: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6373: 	      for(j=1;j <=nlstate;j++)
 6374: 		vepp += vareij[i][j][(int)age];
 6375: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6376: 	    for(j=1;j <=nlstate;j++){
 6377: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6378: 	    }
 6379: 	    fprintf(ficrest,"\n");
 6380: 	  }
 6381: 	}
 6382: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6383: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6384: 	free_vector(epj,1,nlstate+1);
 6385:       }
 6386:     }
 6387:     free_vector(weight,1,n);
 6388:     free_imatrix(Tvard,1,15,1,2);
 6389:     free_imatrix(s,1,maxwav+1,1,n);
 6390:     free_matrix(anint,1,maxwav,1,n); 
 6391:     free_matrix(mint,1,maxwav,1,n);
 6392:     free_ivector(cod,1,n);
 6393:     free_ivector(tab,1,NCOVMAX);
 6394:     fclose(ficresstdeij);
 6395:     fclose(ficrescveij);
 6396:     fclose(ficresvij);
 6397:     fclose(ficrest);
 6398:     fclose(ficpar);
 6399:   
 6400:     /*------- Variance of period (stable) prevalence------*/   
 6401: 
 6402:     strcpy(fileresvpl,"vpl");
 6403:     strcat(fileresvpl,fileres);
 6404:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6405:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6406:       exit(0);
 6407:     }
 6408:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6409: 
 6410:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6411:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6412: 	k=k+1;
 6413: 	fprintf(ficresvpl,"\n#****** ");
 6414: 	for(j=1;j<=cptcoveff;j++) 
 6415: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6416: 	fprintf(ficresvpl,"******\n");
 6417:       
 6418: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6419: 	oldm=oldms;savm=savms;
 6420: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6421: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6422:       }
 6423:     }
 6424: 
 6425:     fclose(ficresvpl);
 6426: 
 6427:     /*---------- End : free ----------------*/
 6428:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6429:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6430:   }  /* mle==-3 arrives here for freeing */
 6431:  endfree:
 6432:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 6433:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6434:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6435:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6436:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6437:     free_matrix(covar,0,NCOVMAX,1,n);
 6438:     free_matrix(matcov,1,npar,1,npar);
 6439:     /*free_vector(delti,1,npar);*/
 6440:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6441:     free_matrix(agev,1,maxwav,1,imx);
 6442:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 6443: 
 6444:     free_ivector(ncodemax,1,8);
 6445:     free_ivector(Tvar,1,15);
 6446:     free_ivector(Tprod,1,15);
 6447:     free_ivector(Tvaraff,1,15);
 6448:     free_ivector(Tage,1,15);
 6449: 
 6450:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 6451:     free_imatrix(codtab,1,100,1,10);
 6452:   fflush(fichtm);
 6453:   fflush(ficgp);
 6454:   
 6455: 
 6456:   if((nberr >0) || (nbwarn>0)){
 6457:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 6458:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 6459:   }else{
 6460:     printf("End of Imach\n");
 6461:     fprintf(ficlog,"End of Imach\n");
 6462:   }
 6463:   printf("See log file on %s\n",filelog);
 6464:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 6465:   (void) gettimeofday(&end_time,&tzp);
 6466:   tm = *localtime(&end_time.tv_sec);
 6467:   tmg = *gmtime(&end_time.tv_sec);
 6468:   strcpy(strtend,asctime(&tm));
 6469:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 6470:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 6471:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 6472: 
 6473:   printf("Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
 6474:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
 6475:   fprintf(ficlog,"Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
 6476:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 6477: /*   if(fileappend(fichtm,optionfilehtm)){ */
 6478:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6479:   fclose(fichtm);
 6480:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6481:   fclose(fichtmcov);
 6482:   fclose(ficgp);
 6483:   fclose(ficlog);
 6484:   /*------ End -----------*/
 6485: 
 6486: 
 6487:    printf("Before Current directory %s!\n",pathcd);
 6488:    if(chdir(pathcd) != 0)
 6489:     printf("Can't move to directory %s!\n",path);
 6490:   if(getcwd(pathcd,MAXLINE) > 0)
 6491:     printf("Current directory %s!\n",pathcd);
 6492:   /*strcat(plotcmd,CHARSEPARATOR);*/
 6493:   sprintf(plotcmd,"gnuplot");
 6494: #ifndef UNIX
 6495:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 6496: #endif
 6497:   if(!stat(plotcmd,&info)){
 6498:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 6499:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 6500:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 6501:     }else
 6502:       strcpy(pplotcmd,plotcmd);
 6503: #ifdef UNIX
 6504:     strcpy(plotcmd,GNUPLOTPROGRAM);
 6505:     if(!stat(plotcmd,&info)){
 6506:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
 6507:     }else
 6508:       strcpy(pplotcmd,plotcmd);
 6509: #endif
 6510:   }else
 6511:     strcpy(pplotcmd,plotcmd);
 6512:   
 6513:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 6514:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
 6515: 
 6516:   if((outcmd=system(plotcmd)) != 0){
 6517:     printf("\n Problem with gnuplot\n");
 6518:   }
 6519:   printf(" Wait...");
 6520:   while (z[0] != 'q') {
 6521:     /* chdir(path); */
 6522:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
 6523:     scanf("%s",z);
 6524: /*     if (z[0] == 'c') system("./imach"); */
 6525:     if (z[0] == 'e') {
 6526:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
 6527:       system(optionfilehtm);
 6528:     }
 6529:     else if (z[0] == 'g') system(plotcmd);
 6530:     else if (z[0] == 'q') exit(0);
 6531:   }
 6532:   end:
 6533:   while (z[0] != 'q') {
 6534:     printf("\nType  q for exiting: ");
 6535:     scanf("%s",z);
 6536:   }
 6537: }
 6538: 
 6539: 
 6540: 

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