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