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