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