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

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

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