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