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