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