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