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