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