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