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