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