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

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

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