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