File:  [Local Repository] / imach / src / imach.c
Revision 1.133: download - view: text, annotated - select for diffs
Mon Jul 6 10:21:25 2009 UTC (14 years, 11 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
just nforces

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

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