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

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

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