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