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