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