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

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

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