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