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