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