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