File:  [Local Repository] / imach / src / imach.c
Revision 1.126: download - view: text, annotated - select for diffs
Fri Apr 28 17:23:28 2006 UTC (18 years, 1 month ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Yes the sum of survivors was wrong since
imach-114 because nhstepm was no more computed in the age
loop. Now we define nhstepma in the age loop.
Version 0.98h

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

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