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

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

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