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