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