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