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

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

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