File:  [Local Repository] / imach / src / imach.c
Revision 1.121: download - view: text, annotated - select for diffs
Thu Mar 16 17:45:01 2006 UTC (18 years, 3 months ago) by lievre
Branches: MAIN
CVS tags: HEAD
* imach.c (Module): Comments concerning covariates added

* imach.c (Module): refinements in the computation of lli if
status=-2 in order to have more reliable computation if stepm is
not 1 month. Version 0.98f

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

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