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

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

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