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