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