Annotation of imach/src/imach.c, revision 1.119

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

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