Annotation of imach/src/imach.c, revision 1.128
1.128 ! brouard 1: /* $Id: imach.c,v 1.127 2006/04/28 18:11:50 brouard Exp $
1.126 brouard 2: $State: Exp $
3: $Log: imach.c,v $
1.128 ! brouard 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:
1.127 brouard 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:
1.126 brouard 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:
1.128 ! brouard 386: /* $Id: imach.c,v 1.127 2006/04/28 18:11:50 brouard Exp $ */
1.126 brouard 387: /* $State: Exp $ */
388:
1.128 ! brouard 389: char version[]="Imach version 0.98i, June 2006, INED-EUROREVES-Institut de longevite ";
! 390: char fullversion[]="$Revision: 1.127 $ $Date: 2006/04/28 18:11:50 $";
1.126 brouard 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];
1.128 ! brouard 1347: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1348: }
1.128 ! brouard 1349: /*printf("h=%d ",h);*/
1.126 brouard 1350: } /* end h */
1.128 ! brouard 1351: /* printf("\n H=%d \n",h); */
1.126 brouard 1352: return po;
1353: }
1354:
1355:
1356: /*************** log-likelihood *************/
1357: double func( double *x)
1358: {
1359: int i, ii, j, k, mi, d, kk;
1360: double l, ll[NLSTATEMAX], cov[NCOVMAX];
1361: double **out;
1362: double sw; /* Sum of weights */
1363: double lli; /* Individual log likelihood */
1364: int s1, s2;
1365: double bbh, survp;
1366: long ipmx;
1367: /*extern weight */
1368: /* We are differentiating ll according to initial status */
1369: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1370: /*for(i=1;i<imx;i++)
1371: printf(" %d\n",s[4][i]);
1372: */
1373: cov[1]=1.;
1374:
1375: for(k=1; k<=nlstate; k++) ll[k]=0.;
1376:
1377: if(mle==1){
1378: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1379: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1380: for(mi=1; mi<= wav[i]-1; mi++){
1381: for (ii=1;ii<=nlstate+ndeath;ii++)
1382: for (j=1;j<=nlstate+ndeath;j++){
1383: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1384: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1385: }
1386: for(d=0; d<dh[mi][i]; d++){
1387: newm=savm;
1388: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1389: for (kk=1; kk<=cptcovage;kk++) {
1390: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1391: }
1392: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1393: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1394: savm=oldm;
1395: oldm=newm;
1396: } /* end mult */
1397:
1398: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1399: /* But now since version 0.9 we anticipate for bias at large stepm.
1400: * If stepm is larger than one month (smallest stepm) and if the exact delay
1401: * (in months) between two waves is not a multiple of stepm, we rounded to
1402: * the nearest (and in case of equal distance, to the lowest) interval but now
1403: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1404: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1405: * probability in order to take into account the bias as a fraction of the way
1406: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1407: * -stepm/2 to stepm/2 .
1408: * For stepm=1 the results are the same as for previous versions of Imach.
1409: * For stepm > 1 the results are less biased than in previous versions.
1410: */
1411: s1=s[mw[mi][i]][i];
1412: s2=s[mw[mi+1][i]][i];
1413: bbh=(double)bh[mi][i]/(double)stepm;
1414: /* bias bh is positive if real duration
1415: * is higher than the multiple of stepm and negative otherwise.
1416: */
1417: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1418: if( s2 > nlstate){
1419: /* i.e. if s2 is a death state and if the date of death is known
1420: then the contribution to the likelihood is the probability to
1421: die between last step unit time and current step unit time,
1422: which is also equal to probability to die before dh
1423: minus probability to die before dh-stepm .
1424: In version up to 0.92 likelihood was computed
1425: as if date of death was unknown. Death was treated as any other
1426: health state: the date of the interview describes the actual state
1427: and not the date of a change in health state. The former idea was
1428: to consider that at each interview the state was recorded
1429: (healthy, disable or death) and IMaCh was corrected; but when we
1430: introduced the exact date of death then we should have modified
1431: the contribution of an exact death to the likelihood. This new
1432: contribution is smaller and very dependent of the step unit
1433: stepm. It is no more the probability to die between last interview
1434: and month of death but the probability to survive from last
1435: interview up to one month before death multiplied by the
1436: probability to die within a month. Thanks to Chris
1437: Jackson for correcting this bug. Former versions increased
1438: mortality artificially. The bad side is that we add another loop
1439: which slows down the processing. The difference can be up to 10%
1440: lower mortality.
1441: */
1442: lli=log(out[s1][s2] - savm[s1][s2]);
1443:
1444:
1445: } else if (s2==-2) {
1446: for (j=1,survp=0. ; j<=nlstate; j++)
1447: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1448: /*survp += out[s1][j]; */
1449: lli= log(survp);
1450: }
1451:
1452: else if (s2==-4) {
1453: for (j=3,survp=0. ; j<=nlstate; j++)
1454: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1455: lli= log(survp);
1456: }
1457:
1458: else if (s2==-5) {
1459: for (j=1,survp=0. ; j<=2; j++)
1460: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1461: lli= log(survp);
1462: }
1463:
1464: else{
1465: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1466: /* 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 */
1467: }
1468: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1469: /*if(lli ==000.0)*/
1470: /*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); */
1471: ipmx +=1;
1472: sw += weight[i];
1473: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1474: } /* end of wave */
1475: } /* end of individual */
1476: } else if(mle==2){
1477: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1478: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1479: for(mi=1; mi<= wav[i]-1; mi++){
1480: for (ii=1;ii<=nlstate+ndeath;ii++)
1481: for (j=1;j<=nlstate+ndeath;j++){
1482: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1483: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1484: }
1485: for(d=0; d<=dh[mi][i]; d++){
1486: newm=savm;
1487: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1488: for (kk=1; kk<=cptcovage;kk++) {
1489: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1490: }
1491: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1492: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1493: savm=oldm;
1494: oldm=newm;
1495: } /* end mult */
1496:
1497: s1=s[mw[mi][i]][i];
1498: s2=s[mw[mi+1][i]][i];
1499: bbh=(double)bh[mi][i]/(double)stepm;
1500: 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 */
1501: ipmx +=1;
1502: sw += weight[i];
1503: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1504: } /* end of wave */
1505: } /* end of individual */
1506: } else if(mle==3){ /* exponential inter-extrapolation */
1507: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1508: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1509: for(mi=1; mi<= wav[i]-1; mi++){
1510: for (ii=1;ii<=nlstate+ndeath;ii++)
1511: for (j=1;j<=nlstate+ndeath;j++){
1512: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1513: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1514: }
1515: for(d=0; d<dh[mi][i]; d++){
1516: newm=savm;
1517: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1518: for (kk=1; kk<=cptcovage;kk++) {
1519: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1520: }
1521: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1522: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1523: savm=oldm;
1524: oldm=newm;
1525: } /* end mult */
1526:
1527: s1=s[mw[mi][i]][i];
1528: s2=s[mw[mi+1][i]][i];
1529: bbh=(double)bh[mi][i]/(double)stepm;
1530: 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 */
1531: ipmx +=1;
1532: sw += weight[i];
1533: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1534: } /* end of wave */
1535: } /* end of individual */
1536: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1537: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1538: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1539: for(mi=1; mi<= wav[i]-1; mi++){
1540: for (ii=1;ii<=nlstate+ndeath;ii++)
1541: for (j=1;j<=nlstate+ndeath;j++){
1542: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1543: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1544: }
1545: for(d=0; d<dh[mi][i]; d++){
1546: newm=savm;
1547: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1548: for (kk=1; kk<=cptcovage;kk++) {
1549: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1550: }
1551:
1552: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1553: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1554: savm=oldm;
1555: oldm=newm;
1556: } /* end mult */
1557:
1558: s1=s[mw[mi][i]][i];
1559: s2=s[mw[mi+1][i]][i];
1560: if( s2 > nlstate){
1561: lli=log(out[s1][s2] - savm[s1][s2]);
1562: }else{
1563: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1564: }
1565: ipmx +=1;
1566: sw += weight[i];
1567: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1568: /* 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]); */
1569: } /* end of wave */
1570: } /* end of individual */
1571: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1572: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1573: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1574: for(mi=1; mi<= wav[i]-1; mi++){
1575: for (ii=1;ii<=nlstate+ndeath;ii++)
1576: for (j=1;j<=nlstate+ndeath;j++){
1577: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1578: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1579: }
1580: for(d=0; d<dh[mi][i]; d++){
1581: newm=savm;
1582: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1583: for (kk=1; kk<=cptcovage;kk++) {
1584: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1585: }
1586:
1587: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1588: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1589: savm=oldm;
1590: oldm=newm;
1591: } /* end mult */
1592:
1593: s1=s[mw[mi][i]][i];
1594: s2=s[mw[mi+1][i]][i];
1595: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1596: ipmx +=1;
1597: sw += weight[i];
1598: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1599: /*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]);*/
1600: } /* end of wave */
1601: } /* end of individual */
1602: } /* End of if */
1603: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1604: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1605: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1606: return -l;
1607: }
1608:
1609: /*************** log-likelihood *************/
1610: double funcone( double *x)
1611: {
1612: /* Same as likeli but slower because of a lot of printf and if */
1613: int i, ii, j, k, mi, d, kk;
1614: double l, ll[NLSTATEMAX], cov[NCOVMAX];
1615: double **out;
1616: double lli; /* Individual log likelihood */
1617: double llt;
1618: int s1, s2;
1619: double bbh, survp;
1620: /*extern weight */
1621: /* We are differentiating ll according to initial status */
1622: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1623: /*for(i=1;i<imx;i++)
1624: printf(" %d\n",s[4][i]);
1625: */
1626: cov[1]=1.;
1627:
1628: for(k=1; k<=nlstate; k++) ll[k]=0.;
1629:
1630: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1631: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1632: for(mi=1; mi<= wav[i]-1; mi++){
1633: for (ii=1;ii<=nlstate+ndeath;ii++)
1634: for (j=1;j<=nlstate+ndeath;j++){
1635: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1636: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1637: }
1638: for(d=0; d<dh[mi][i]; d++){
1639: newm=savm;
1640: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1641: for (kk=1; kk<=cptcovage;kk++) {
1642: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1643: }
1644: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1645: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1646: savm=oldm;
1647: oldm=newm;
1648: } /* end mult */
1649:
1650: s1=s[mw[mi][i]][i];
1651: s2=s[mw[mi+1][i]][i];
1652: bbh=(double)bh[mi][i]/(double)stepm;
1653: /* bias is positive if real duration
1654: * is higher than the multiple of stepm and negative otherwise.
1655: */
1656: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1657: lli=log(out[s1][s2] - savm[s1][s2]);
1658: } else if (s2==-2) {
1659: for (j=1,survp=0. ; j<=nlstate; j++)
1660: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1661: lli= log(survp);
1662: }else if (mle==1){
1663: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1664: } else if(mle==2){
1665: 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 */
1666: } else if(mle==3){ /* exponential inter-extrapolation */
1667: 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 */
1668: } else if (mle==4){ /* mle=4 no inter-extrapolation */
1669: lli=log(out[s1][s2]); /* Original formula */
1670: } else{ /* ml>=5 no inter-extrapolation no jackson =0.8a */
1671: lli=log(out[s1][s2]); /* Original formula */
1672: } /* End of if */
1673: ipmx +=1;
1674: sw += weight[i];
1675: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1676: /* 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]); */
1677: if(globpr){
1678: fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1679: %11.6f %11.6f %11.6f ", \
1680: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1681: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
1682: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
1683: llt +=ll[k]*gipmx/gsw;
1684: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1685: }
1686: fprintf(ficresilk," %10.6f\n", -llt);
1687: }
1688: } /* end of wave */
1689: } /* end of individual */
1690: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1691: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1692: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1693: if(globpr==0){ /* First time we count the contributions and weights */
1694: gipmx=ipmx;
1695: gsw=sw;
1696: }
1697: return -l;
1698: }
1699:
1700:
1701: /*************** function likelione ***********/
1702: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
1703: {
1704: /* This routine should help understanding what is done with
1705: the selection of individuals/waves and
1706: to check the exact contribution to the likelihood.
1707: Plotting could be done.
1708: */
1709: int k;
1710:
1711: if(*globpri !=0){ /* Just counts and sums, no printings */
1712: strcpy(fileresilk,"ilk");
1713: strcat(fileresilk,fileres);
1714: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
1715: printf("Problem with resultfile: %s\n", fileresilk);
1716: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
1717: }
1718: 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");
1719: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
1720: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
1721: for(k=1; k<=nlstate; k++)
1722: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1723: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
1724: }
1725:
1726: *fretone=(*funcone)(p);
1727: if(*globpri !=0){
1728: fclose(ficresilk);
1729: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1730: fflush(fichtm);
1731: }
1732: return;
1733: }
1734:
1735:
1736: /*********** Maximum Likelihood Estimation ***************/
1737:
1738: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
1739: {
1740: int i,j, iter;
1741: double **xi;
1742: double fret;
1743: double fretone; /* Only one call to likelihood */
1744: /* char filerespow[FILENAMELENGTH];*/
1745: xi=matrix(1,npar,1,npar);
1746: for (i=1;i<=npar;i++)
1747: for (j=1;j<=npar;j++)
1748: xi[i][j]=(i==j ? 1.0 : 0.0);
1749: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1750: strcpy(filerespow,"pow");
1751: strcat(filerespow,fileres);
1752: if((ficrespow=fopen(filerespow,"w"))==NULL) {
1753: printf("Problem with resultfile: %s\n", filerespow);
1754: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
1755: }
1756: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1757: for (i=1;i<=nlstate;i++)
1758: for(j=1;j<=nlstate+ndeath;j++)
1759: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
1760: fprintf(ficrespow,"\n");
1761:
1762: powell(p,xi,npar,ftol,&iter,&fret,func);
1763:
1764: free_matrix(xi,1,npar,1,npar);
1765: fclose(ficrespow);
1766: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
1767: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
1768: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
1769:
1770: }
1771:
1772: /**** Computes Hessian and covariance matrix ***/
1773: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1774: {
1775: double **a,**y,*x,pd;
1776: double **hess;
1777: int i, j,jk;
1778: int *indx;
1779:
1780: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1781: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
1782: void lubksb(double **a, int npar, int *indx, double b[]) ;
1783: void ludcmp(double **a, int npar, int *indx, double *d) ;
1784: double gompertz(double p[]);
1785: hess=matrix(1,npar,1,npar);
1786:
1787: printf("\nCalculation of the hessian matrix. Wait...\n");
1788: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
1789: for (i=1;i<=npar;i++){
1790: printf("%d",i);fflush(stdout);
1791: fprintf(ficlog,"%d",i);fflush(ficlog);
1792:
1793: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
1794:
1795: /* printf(" %f ",p[i]);
1796: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
1797: }
1798:
1799: for (i=1;i<=npar;i++) {
1800: for (j=1;j<=npar;j++) {
1801: if (j>i) {
1802: printf(".%d%d",i,j);fflush(stdout);
1803: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
1804: hess[i][j]=hessij(p,delti,i,j,func,npar);
1805:
1806: hess[j][i]=hess[i][j];
1807: /*printf(" %lf ",hess[i][j]);*/
1808: }
1809: }
1810: }
1811: printf("\n");
1812: fprintf(ficlog,"\n");
1813:
1814: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
1815: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
1816:
1817: a=matrix(1,npar,1,npar);
1818: y=matrix(1,npar,1,npar);
1819: x=vector(1,npar);
1820: indx=ivector(1,npar);
1821: for (i=1;i<=npar;i++)
1822: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
1823: ludcmp(a,npar,indx,&pd);
1824:
1825: for (j=1;j<=npar;j++) {
1826: for (i=1;i<=npar;i++) x[i]=0;
1827: x[j]=1;
1828: lubksb(a,npar,indx,x);
1829: for (i=1;i<=npar;i++){
1830: matcov[i][j]=x[i];
1831: }
1832: }
1833:
1834: printf("\n#Hessian matrix#\n");
1835: fprintf(ficlog,"\n#Hessian matrix#\n");
1836: for (i=1;i<=npar;i++) {
1837: for (j=1;j<=npar;j++) {
1838: printf("%.3e ",hess[i][j]);
1839: fprintf(ficlog,"%.3e ",hess[i][j]);
1840: }
1841: printf("\n");
1842: fprintf(ficlog,"\n");
1843: }
1844:
1845: /* Recompute Inverse */
1846: for (i=1;i<=npar;i++)
1847: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
1848: ludcmp(a,npar,indx,&pd);
1849:
1850: /* printf("\n#Hessian matrix recomputed#\n");
1851:
1852: for (j=1;j<=npar;j++) {
1853: for (i=1;i<=npar;i++) x[i]=0;
1854: x[j]=1;
1855: lubksb(a,npar,indx,x);
1856: for (i=1;i<=npar;i++){
1857: y[i][j]=x[i];
1858: printf("%.3e ",y[i][j]);
1859: fprintf(ficlog,"%.3e ",y[i][j]);
1860: }
1861: printf("\n");
1862: fprintf(ficlog,"\n");
1863: }
1864: */
1865:
1866: free_matrix(a,1,npar,1,npar);
1867: free_matrix(y,1,npar,1,npar);
1868: free_vector(x,1,npar);
1869: free_ivector(indx,1,npar);
1870: free_matrix(hess,1,npar,1,npar);
1871:
1872:
1873: }
1874:
1875: /*************** hessian matrix ****************/
1876: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1877: {
1878: int i;
1879: int l=1, lmax=20;
1880: double k1,k2;
1881: double p2[NPARMAX+1];
1882: double res;
1883: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
1884: double fx;
1885: int k=0,kmax=10;
1886: double l1;
1887:
1888: fx=func(x);
1889: for (i=1;i<=npar;i++) p2[i]=x[i];
1890: for(l=0 ; l <=lmax; l++){
1891: l1=pow(10,l);
1892: delts=delt;
1893: for(k=1 ; k <kmax; k=k+1){
1894: delt = delta*(l1*k);
1895: p2[theta]=x[theta] +delt;
1896: k1=func(p2)-fx;
1897: p2[theta]=x[theta]-delt;
1898: k2=func(p2)-fx;
1899: /*res= (k1-2.0*fx+k2)/delt/delt; */
1900: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
1901:
1902: #ifdef DEBUG
1903: 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);
1904: 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);
1905: #endif
1906: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
1907: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
1908: k=kmax;
1909: }
1910: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1911: k=kmax; l=lmax*10.;
1912: }
1913: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
1914: delts=delt;
1915: }
1916: }
1917: }
1918: delti[theta]=delts;
1919: return res;
1920:
1921: }
1922:
1923: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1924: {
1925: int i;
1926: int l=1, l1, lmax=20;
1927: double k1,k2,k3,k4,res,fx;
1928: double p2[NPARMAX+1];
1929: int k;
1930:
1931: fx=func(x);
1932: for (k=1; k<=2; k++) {
1933: for (i=1;i<=npar;i++) p2[i]=x[i];
1934: p2[thetai]=x[thetai]+delti[thetai]/k;
1935: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
1936: k1=func(p2)-fx;
1937:
1938: p2[thetai]=x[thetai]+delti[thetai]/k;
1939: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
1940: k2=func(p2)-fx;
1941:
1942: p2[thetai]=x[thetai]-delti[thetai]/k;
1943: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
1944: k3=func(p2)-fx;
1945:
1946: p2[thetai]=x[thetai]-delti[thetai]/k;
1947: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
1948: k4=func(p2)-fx;
1949: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
1950: #ifdef DEBUG
1951: 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);
1952: 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);
1953: #endif
1954: }
1955: return res;
1956: }
1957:
1958: /************** Inverse of matrix **************/
1959: void ludcmp(double **a, int n, int *indx, double *d)
1960: {
1961: int i,imax,j,k;
1962: double big,dum,sum,temp;
1963: double *vv;
1964:
1965: vv=vector(1,n);
1966: *d=1.0;
1967: for (i=1;i<=n;i++) {
1968: big=0.0;
1969: for (j=1;j<=n;j++)
1970: if ((temp=fabs(a[i][j])) > big) big=temp;
1971: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
1972: vv[i]=1.0/big;
1973: }
1974: for (j=1;j<=n;j++) {
1975: for (i=1;i<j;i++) {
1976: sum=a[i][j];
1977: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
1978: a[i][j]=sum;
1979: }
1980: big=0.0;
1981: for (i=j;i<=n;i++) {
1982: sum=a[i][j];
1983: for (k=1;k<j;k++)
1984: sum -= a[i][k]*a[k][j];
1985: a[i][j]=sum;
1986: if ( (dum=vv[i]*fabs(sum)) >= big) {
1987: big=dum;
1988: imax=i;
1989: }
1990: }
1991: if (j != imax) {
1992: for (k=1;k<=n;k++) {
1993: dum=a[imax][k];
1994: a[imax][k]=a[j][k];
1995: a[j][k]=dum;
1996: }
1997: *d = -(*d);
1998: vv[imax]=vv[j];
1999: }
2000: indx[j]=imax;
2001: if (a[j][j] == 0.0) a[j][j]=TINY;
2002: if (j != n) {
2003: dum=1.0/(a[j][j]);
2004: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2005: }
2006: }
2007: free_vector(vv,1,n); /* Doesn't work */
2008: ;
2009: }
2010:
2011: void lubksb(double **a, int n, int *indx, double b[])
2012: {
2013: int i,ii=0,ip,j;
2014: double sum;
2015:
2016: for (i=1;i<=n;i++) {
2017: ip=indx[i];
2018: sum=b[ip];
2019: b[ip]=b[i];
2020: if (ii)
2021: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2022: else if (sum) ii=i;
2023: b[i]=sum;
2024: }
2025: for (i=n;i>=1;i--) {
2026: sum=b[i];
2027: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2028: b[i]=sum/a[i][i];
2029: }
2030: }
2031:
2032: void pstamp(FILE *fichier)
2033: {
2034: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2035: }
2036:
2037: /************ Frequencies ********************/
2038: 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[])
2039: { /* Some frequencies */
2040:
2041: int i, m, jk, k1,i1, j1, bool, z1,z2,j;
2042: int first;
2043: double ***freq; /* Frequencies */
2044: double *pp, **prop;
2045: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2046: char fileresp[FILENAMELENGTH];
2047:
2048: pp=vector(1,nlstate);
2049: prop=matrix(1,nlstate,iagemin,iagemax+3);
2050: strcpy(fileresp,"p");
2051: strcat(fileresp,fileres);
2052: if((ficresp=fopen(fileresp,"w"))==NULL) {
2053: printf("Problem with prevalence resultfile: %s\n", fileresp);
2054: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2055: exit(0);
2056: }
2057: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2058: j1=0;
2059:
2060: j=cptcoveff;
2061: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2062:
2063: first=1;
2064:
2065: for(k1=1; k1<=j;k1++){
2066: for(i1=1; i1<=ncodemax[k1];i1++){
2067: j1++;
2068: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2069: scanf("%d", i);*/
2070: for (i=-5; i<=nlstate+ndeath; i++)
2071: for (jk=-5; jk<=nlstate+ndeath; jk++)
2072: for(m=iagemin; m <= iagemax+3; m++)
2073: freq[i][jk][m]=0;
2074:
2075: for (i=1; i<=nlstate; i++)
2076: for(m=iagemin; m <= iagemax+3; m++)
2077: prop[i][m]=0;
2078:
2079: dateintsum=0;
2080: k2cpt=0;
2081: for (i=1; i<=imx; i++) {
2082: bool=1;
2083: if (cptcovn>0) {
2084: for (z1=1; z1<=cptcoveff; z1++)
2085: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2086: bool=0;
2087: }
2088: if (bool==1){
2089: for(m=firstpass; m<=lastpass; m++){
2090: k2=anint[m][i]+(mint[m][i]/12.);
2091: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2092: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2093: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2094: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2095: if (m<lastpass) {
2096: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2097: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2098: }
2099:
2100: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2101: dateintsum=dateintsum+k2;
2102: k2cpt++;
2103: }
2104: /*}*/
2105: }
2106: }
2107: }
2108:
2109: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2110: pstamp(ficresp);
2111: if (cptcovn>0) {
2112: fprintf(ficresp, "\n#********** Variable ");
2113: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2114: fprintf(ficresp, "**********\n#");
2115: }
2116: for(i=1; i<=nlstate;i++)
2117: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2118: fprintf(ficresp, "\n");
2119:
2120: for(i=iagemin; i <= iagemax+3; i++){
2121: if(i==iagemax+3){
2122: fprintf(ficlog,"Total");
2123: }else{
2124: if(first==1){
2125: first=0;
2126: printf("See log file for details...\n");
2127: }
2128: fprintf(ficlog,"Age %d", i);
2129: }
2130: for(jk=1; jk <=nlstate ; jk++){
2131: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2132: pp[jk] += freq[jk][m][i];
2133: }
2134: for(jk=1; jk <=nlstate ; jk++){
2135: for(m=-1, pos=0; m <=0 ; m++)
2136: pos += freq[jk][m][i];
2137: if(pp[jk]>=1.e-10){
2138: if(first==1){
2139: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2140: }
2141: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2142: }else{
2143: if(first==1)
2144: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2145: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2146: }
2147: }
2148:
2149: for(jk=1; jk <=nlstate ; jk++){
2150: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2151: pp[jk] += freq[jk][m][i];
2152: }
2153: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2154: pos += pp[jk];
2155: posprop += prop[jk][i];
2156: }
2157: for(jk=1; jk <=nlstate ; jk++){
2158: if(pos>=1.e-5){
2159: if(first==1)
2160: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2161: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2162: }else{
2163: if(first==1)
2164: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2165: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2166: }
2167: if( i <= iagemax){
2168: if(pos>=1.e-5){
2169: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2170: /*probs[i][jk][j1]= pp[jk]/pos;*/
2171: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2172: }
2173: else
2174: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2175: }
2176: }
2177:
2178: for(jk=-1; jk <=nlstate+ndeath; jk++)
2179: for(m=-1; m <=nlstate+ndeath; m++)
2180: if(freq[jk][m][i] !=0 ) {
2181: if(first==1)
2182: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2183: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2184: }
2185: if(i <= iagemax)
2186: fprintf(ficresp,"\n");
2187: if(first==1)
2188: printf("Others in log...\n");
2189: fprintf(ficlog,"\n");
2190: }
2191: }
2192: }
2193: dateintmean=dateintsum/k2cpt;
2194:
2195: fclose(ficresp);
2196: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2197: free_vector(pp,1,nlstate);
2198: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2199: /* End of Freq */
2200: }
2201:
2202: /************ Prevalence ********************/
2203: 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)
2204: {
2205: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2206: in each health status at the date of interview (if between dateprev1 and dateprev2).
2207: We still use firstpass and lastpass as another selection.
2208: */
2209:
2210: int i, m, jk, k1, i1, j1, bool, z1,z2,j;
2211: double ***freq; /* Frequencies */
2212: double *pp, **prop;
2213: double pos,posprop;
2214: double y2; /* in fractional years */
2215: int iagemin, iagemax;
2216:
2217: iagemin= (int) agemin;
2218: iagemax= (int) agemax;
2219: /*pp=vector(1,nlstate);*/
2220: prop=matrix(1,nlstate,iagemin,iagemax+3);
2221: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2222: j1=0;
2223:
2224: j=cptcoveff;
2225: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2226:
2227: for(k1=1; k1<=j;k1++){
2228: for(i1=1; i1<=ncodemax[k1];i1++){
2229: j1++;
2230:
2231: for (i=1; i<=nlstate; i++)
2232: for(m=iagemin; m <= iagemax+3; m++)
2233: prop[i][m]=0.0;
2234:
2235: for (i=1; i<=imx; i++) { /* Each individual */
2236: bool=1;
2237: if (cptcovn>0) {
2238: for (z1=1; z1<=cptcoveff; z1++)
2239: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2240: bool=0;
2241: }
2242: if (bool==1) {
2243: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2244: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2245: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2246: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2247: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2248: 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);
2249: if (s[m][i]>0 && s[m][i]<=nlstate) {
2250: /*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]]);*/
2251: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2252: prop[s[m][i]][iagemax+3] += weight[i];
2253: }
2254: }
2255: } /* end selection of waves */
2256: }
2257: }
2258: for(i=iagemin; i <= iagemax+3; i++){
2259:
2260: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2261: posprop += prop[jk][i];
2262: }
2263:
2264: for(jk=1; jk <=nlstate ; jk++){
2265: if( i <= iagemax){
2266: if(posprop>=1.e-5){
2267: probs[i][jk][j1]= prop[jk][i]/posprop;
1.128 ! brouard 2268: } else
! 2269: printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
1.126 brouard 2270: }
2271: }/* end jk */
2272: }/* end i */
2273: } /* end i1 */
2274: } /* end k1 */
2275:
2276: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2277: /*free_vector(pp,1,nlstate);*/
2278: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2279: } /* End of prevalence */
2280:
2281: /************* Waves Concatenation ***************/
2282:
2283: 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)
2284: {
2285: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2286: Death is a valid wave (if date is known).
2287: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2288: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2289: and mw[mi+1][i]. dh depends on stepm.
2290: */
2291:
2292: int i, mi, m;
2293: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2294: double sum=0., jmean=0.;*/
2295: int first;
2296: int j, k=0,jk, ju, jl;
2297: double sum=0.;
2298: first=0;
2299: jmin=1e+5;
2300: jmax=-1;
2301: jmean=0.;
2302: for(i=1; i<=imx; i++){
2303: mi=0;
2304: m=firstpass;
2305: while(s[m][i] <= nlstate){
2306: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2307: mw[++mi][i]=m;
2308: if(m >=lastpass)
2309: break;
2310: else
2311: m++;
2312: }/* end while */
2313: if (s[m][i] > nlstate){
2314: mi++; /* Death is another wave */
2315: /* if(mi==0) never been interviewed correctly before death */
2316: /* Only death is a correct wave */
2317: mw[mi][i]=m;
2318: }
2319:
2320: wav[i]=mi;
2321: if(mi==0){
2322: nbwarn++;
2323: if(first==0){
2324: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2325: first=1;
2326: }
2327: if(first==1){
2328: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2329: }
2330: } /* end mi==0 */
2331: } /* End individuals */
2332:
2333: for(i=1; i<=imx; i++){
2334: for(mi=1; mi<wav[i];mi++){
2335: if (stepm <=0)
2336: dh[mi][i]=1;
2337: else{
2338: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2339: if (agedc[i] < 2*AGESUP) {
2340: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2341: if(j==0) j=1; /* Survives at least one month after exam */
2342: else if(j<0){
2343: nberr++;
2344: 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]);
2345: j=1; /* Temporary Dangerous patch */
2346: 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);
2347: 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]);
2348: 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);
2349: }
2350: k=k+1;
2351: if (j >= jmax){
2352: jmax=j;
2353: ijmax=i;
2354: }
2355: if (j <= jmin){
2356: jmin=j;
2357: ijmin=i;
2358: }
2359: sum=sum+j;
2360: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2361: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2362: }
2363: }
2364: else{
2365: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2366: /* 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]); */
2367:
2368: k=k+1;
2369: if (j >= jmax) {
2370: jmax=j;
2371: ijmax=i;
2372: }
2373: else if (j <= jmin){
2374: jmin=j;
2375: ijmin=i;
2376: }
2377: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2378: /*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]);*/
2379: if(j<0){
2380: nberr++;
2381: 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]);
2382: 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]);
2383: }
2384: sum=sum+j;
2385: }
2386: jk= j/stepm;
2387: jl= j -jk*stepm;
2388: ju= j -(jk+1)*stepm;
2389: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2390: if(jl==0){
2391: dh[mi][i]=jk;
2392: bh[mi][i]=0;
2393: }else{ /* We want a negative bias in order to only have interpolation ie
2394: * at the price of an extra matrix product in likelihood */
2395: dh[mi][i]=jk+1;
2396: bh[mi][i]=ju;
2397: }
2398: }else{
2399: if(jl <= -ju){
2400: dh[mi][i]=jk;
2401: bh[mi][i]=jl; /* bias is positive if real duration
2402: * is higher than the multiple of stepm and negative otherwise.
2403: */
2404: }
2405: else{
2406: dh[mi][i]=jk+1;
2407: bh[mi][i]=ju;
2408: }
2409: if(dh[mi][i]==0){
2410: dh[mi][i]=1; /* At least one step */
2411: bh[mi][i]=ju; /* At least one step */
2412: /* 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);*/
2413: }
2414: } /* end if mle */
2415: }
2416: } /* end wave */
2417: }
2418: jmean=sum/k;
2419: 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);
2420: 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);
2421: }
2422:
2423: /*********** Tricode ****************************/
2424: void tricode(int *Tvar, int **nbcode, int imx)
2425: {
2426:
2427: int Ndum[20],ij=1, k, j, i, maxncov=19;
2428: int cptcode=0;
2429: cptcoveff=0;
2430:
2431: for (k=0; k<maxncov; k++) Ndum[k]=0;
2432: for (k=1; k<=7; k++) ncodemax[k]=0;
2433:
2434: for (j=1; j<=(cptcovn+2*cptcovprod); j++) {
2435: for (i=1; i<=imx; i++) { /*reads the data file to get the maximum
2436: modality*/
2437: ij=(int)(covar[Tvar[j]][i]); /* ij is the modality of this individual*/
2438: Ndum[ij]++; /*store the modality */
2439: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
2440: if (ij > cptcode) cptcode=ij; /* getting the maximum of covariable
2441: Tvar[j]. If V=sex and male is 0 and
2442: female is 1, then cptcode=1.*/
2443: }
2444:
2445: for (i=0; i<=cptcode; i++) {
2446: 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 */
2447: }
2448:
2449: ij=1;
2450: for (i=1; i<=ncodemax[j]; i++) {
2451: for (k=0; k<= maxncov; k++) {
2452: if (Ndum[k] != 0) {
2453: nbcode[Tvar[j]][ij]=k;
2454: /* 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; */
2455:
2456: ij++;
2457: }
2458: if (ij > ncodemax[j]) break;
2459: }
2460: }
2461: }
2462:
2463: for (k=0; k< maxncov; k++) Ndum[k]=0;
2464:
2465: for (i=1; i<=ncovmodel-2; i++) {
2466: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2467: ij=Tvar[i];
2468: Ndum[ij]++;
2469: }
2470:
2471: ij=1;
2472: for (i=1; i<= maxncov; i++) {
2473: if((Ndum[i]!=0) && (i<=ncovcol)){
2474: Tvaraff[ij]=i; /*For printing */
2475: ij++;
2476: }
2477: }
2478:
2479: cptcoveff=ij-1; /*Number of simple covariates*/
2480: }
2481:
2482: /*********** Health Expectancies ****************/
2483:
1.127 brouard 2484: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126 brouard 2485:
2486: {
2487: /* Health expectancies, no variances */
2488: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2489: int nhstepma, nstepma; /* Decreasing with age */
2490: double age, agelim, hf;
2491: double ***p3mat;
2492: double eip;
2493:
2494: pstamp(ficreseij);
2495: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2496: fprintf(ficreseij,"# Age");
2497: for(i=1; i<=nlstate;i++){
2498: for(j=1; j<=nlstate;j++){
2499: fprintf(ficreseij," e%1d%1d ",i,j);
2500: }
2501: fprintf(ficreseij," e%1d. ",i);
2502: }
2503: fprintf(ficreseij,"\n");
2504:
2505:
2506: if(estepm < stepm){
2507: printf ("Problem %d lower than %d\n",estepm, stepm);
2508: }
2509: else hstepm=estepm;
2510: /* We compute the life expectancy from trapezoids spaced every estepm months
2511: * This is mainly to measure the difference between two models: for example
2512: * if stepm=24 months pijx are given only every 2 years and by summing them
2513: * we are calculating an estimate of the Life Expectancy assuming a linear
2514: * progression in between and thus overestimating or underestimating according
2515: * to the curvature of the survival function. If, for the same date, we
2516: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2517: * to compare the new estimate of Life expectancy with the same linear
2518: * hypothesis. A more precise result, taking into account a more precise
2519: * curvature will be obtained if estepm is as small as stepm. */
2520:
2521: /* For example we decided to compute the life expectancy with the smallest unit */
2522: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2523: nhstepm is the number of hstepm from age to agelim
2524: nstepm is the number of stepm from age to agelin.
2525: Look at hpijx to understand the reason of that which relies in memory size
2526: and note for a fixed period like estepm months */
2527: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2528: survival function given by stepm (the optimization length). Unfortunately it
2529: means that if the survival funtion is printed only each two years of age and if
2530: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2531: results. So we changed our mind and took the option of the best precision.
2532: */
2533: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2534:
2535: agelim=AGESUP;
2536: /* If stepm=6 months */
2537: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2538: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2539:
2540: /* nhstepm age range expressed in number of stepm */
2541: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2542: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2543: /* if (stepm >= YEARM) hstepm=1;*/
2544: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2545: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2546:
2547: for (age=bage; age<=fage; age ++){
2548: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2549: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2550: /* if (stepm >= YEARM) hstepm=1;*/
2551: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2552:
2553: /* If stepm=6 months */
2554: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2555: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2556:
2557: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2558:
2559: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2560:
2561: printf("%d|",(int)age);fflush(stdout);
2562: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2563:
2564: /* Computing expectancies */
2565: for(i=1; i<=nlstate;i++)
2566: for(j=1; j<=nlstate;j++)
2567: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2568: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2569:
2570: /* 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]);*/
2571:
2572: }
2573:
2574: fprintf(ficreseij,"%3.0f",age );
2575: for(i=1; i<=nlstate;i++){
2576: eip=0;
2577: for(j=1; j<=nlstate;j++){
2578: eip +=eij[i][j][(int)age];
2579: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2580: }
2581: fprintf(ficreseij,"%9.4f", eip );
2582: }
2583: fprintf(ficreseij,"\n");
2584:
2585: }
2586: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2587: printf("\n");
2588: fprintf(ficlog,"\n");
2589:
2590: }
2591:
1.127 brouard 2592: void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
1.126 brouard 2593:
2594: {
2595: /* Covariances of health expectancies eij and of total life expectancies according
2596: to initial status i, ei. .
2597: */
2598: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
2599: int nhstepma, nstepma; /* Decreasing with age */
2600: double age, agelim, hf;
2601: double ***p3matp, ***p3matm, ***varhe;
2602: double **dnewm,**doldm;
2603: double *xp, *xm;
2604: double **gp, **gm;
2605: double ***gradg, ***trgradg;
2606: int theta;
2607:
2608: double eip, vip;
2609:
2610: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
2611: xp=vector(1,npar);
2612: xm=vector(1,npar);
2613: dnewm=matrix(1,nlstate*nlstate,1,npar);
2614: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
2615:
2616: pstamp(ficresstdeij);
2617: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
2618: fprintf(ficresstdeij,"# Age");
2619: for(i=1; i<=nlstate;i++){
2620: for(j=1; j<=nlstate;j++)
2621: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
2622: fprintf(ficresstdeij," e%1d. ",i);
2623: }
2624: fprintf(ficresstdeij,"\n");
2625:
2626: pstamp(ficrescveij);
2627: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
2628: fprintf(ficrescveij,"# Age");
2629: for(i=1; i<=nlstate;i++)
2630: for(j=1; j<=nlstate;j++){
2631: cptj= (j-1)*nlstate+i;
2632: for(i2=1; i2<=nlstate;i2++)
2633: for(j2=1; j2<=nlstate;j2++){
2634: cptj2= (j2-1)*nlstate+i2;
2635: if(cptj2 <= cptj)
2636: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
2637: }
2638: }
2639: fprintf(ficrescveij,"\n");
2640:
2641: if(estepm < stepm){
2642: printf ("Problem %d lower than %d\n",estepm, stepm);
2643: }
2644: else hstepm=estepm;
2645: /* We compute the life expectancy from trapezoids spaced every estepm months
2646: * This is mainly to measure the difference between two models: for example
2647: * if stepm=24 months pijx are given only every 2 years and by summing them
2648: * we are calculating an estimate of the Life Expectancy assuming a linear
2649: * progression in between and thus overestimating or underestimating according
2650: * to the curvature of the survival function. If, for the same date, we
2651: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2652: * to compare the new estimate of Life expectancy with the same linear
2653: * hypothesis. A more precise result, taking into account a more precise
2654: * curvature will be obtained if estepm is as small as stepm. */
2655:
2656: /* For example we decided to compute the life expectancy with the smallest unit */
2657: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2658: nhstepm is the number of hstepm from age to agelim
2659: nstepm is the number of stepm from age to agelin.
2660: Look at hpijx to understand the reason of that which relies in memory size
2661: and note for a fixed period like estepm months */
2662: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2663: survival function given by stepm (the optimization length). Unfortunately it
2664: means that if the survival funtion is printed only each two years of age and if
2665: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2666: results. So we changed our mind and took the option of the best precision.
2667: */
2668: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2669:
2670: /* If stepm=6 months */
2671: /* nhstepm age range expressed in number of stepm */
2672: agelim=AGESUP;
2673: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
2674: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2675: /* if (stepm >= YEARM) hstepm=1;*/
2676: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2677:
2678: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2679: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2680: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
2681: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
2682: gp=matrix(0,nhstepm,1,nlstate*nlstate);
2683: gm=matrix(0,nhstepm,1,nlstate*nlstate);
2684:
2685: for (age=bage; age<=fage; age ++){
2686: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2687: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2688: /* if (stepm >= YEARM) hstepm=1;*/
2689: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2690:
2691: /* If stepm=6 months */
2692: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2693: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2694:
2695: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2696:
2697: /* Computing Variances of health expectancies */
2698: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
2699: decrease memory allocation */
2700: for(theta=1; theta <=npar; theta++){
2701: for(i=1; i<=npar; i++){
2702: xp[i] = x[i] + (i==theta ?delti[theta]:0);
2703: xm[i] = x[i] - (i==theta ?delti[theta]:0);
2704: }
2705: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
2706: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
2707:
2708: for(j=1; j<= nlstate; j++){
2709: for(i=1; i<=nlstate; i++){
2710: for(h=0; h<=nhstepm-1; h++){
2711: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
2712: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
2713: }
2714: }
2715: }
2716:
2717: for(ij=1; ij<= nlstate*nlstate; ij++)
2718: for(h=0; h<=nhstepm-1; h++){
2719: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
2720: }
2721: }/* End theta */
2722:
2723:
2724: for(h=0; h<=nhstepm-1; h++)
2725: for(j=1; j<=nlstate*nlstate;j++)
2726: for(theta=1; theta <=npar; theta++)
2727: trgradg[h][j][theta]=gradg[h][theta][j];
2728:
2729:
2730: for(ij=1;ij<=nlstate*nlstate;ij++)
2731: for(ji=1;ji<=nlstate*nlstate;ji++)
2732: varhe[ij][ji][(int)age] =0.;
2733:
2734: printf("%d|",(int)age);fflush(stdout);
2735: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2736: for(h=0;h<=nhstepm-1;h++){
2737: for(k=0;k<=nhstepm-1;k++){
2738: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
2739: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
2740: for(ij=1;ij<=nlstate*nlstate;ij++)
2741: for(ji=1;ji<=nlstate*nlstate;ji++)
2742: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
2743: }
2744: }
2745:
2746: /* Computing expectancies */
2747: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2748: for(i=1; i<=nlstate;i++)
2749: for(j=1; j<=nlstate;j++)
2750: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2751: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
2752:
2753: /* 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]);*/
2754:
2755: }
2756:
2757: fprintf(ficresstdeij,"%3.0f",age );
2758: for(i=1; i<=nlstate;i++){
2759: eip=0.;
2760: vip=0.;
2761: for(j=1; j<=nlstate;j++){
2762: eip += eij[i][j][(int)age];
2763: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
2764: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
2765: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
2766: }
2767: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
2768: }
2769: fprintf(ficresstdeij,"\n");
2770:
2771: fprintf(ficrescveij,"%3.0f",age );
2772: for(i=1; i<=nlstate;i++)
2773: for(j=1; j<=nlstate;j++){
2774: cptj= (j-1)*nlstate+i;
2775: for(i2=1; i2<=nlstate;i2++)
2776: for(j2=1; j2<=nlstate;j2++){
2777: cptj2= (j2-1)*nlstate+i2;
2778: if(cptj2 <= cptj)
2779: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
2780: }
2781: }
2782: fprintf(ficrescveij,"\n");
2783:
2784: }
2785: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
2786: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
2787: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
2788: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
2789: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2790: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2791: printf("\n");
2792: fprintf(ficlog,"\n");
2793:
2794: free_vector(xm,1,npar);
2795: free_vector(xp,1,npar);
2796: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
2797: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
2798: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
2799: }
2800:
2801: /************ Variance ******************/
2802: 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[])
2803: {
2804: /* Variance of health expectancies */
2805: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
2806: /* double **newm;*/
2807: double **dnewm,**doldm;
2808: double **dnewmp,**doldmp;
2809: int i, j, nhstepm, hstepm, h, nstepm ;
2810: int k, cptcode;
2811: double *xp;
2812: double **gp, **gm; /* for var eij */
2813: double ***gradg, ***trgradg; /*for var eij */
2814: double **gradgp, **trgradgp; /* for var p point j */
2815: double *gpp, *gmp; /* for var p point j */
2816: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
2817: double ***p3mat;
2818: double age,agelim, hf;
2819: double ***mobaverage;
2820: int theta;
2821: char digit[4];
2822: char digitp[25];
2823:
2824: char fileresprobmorprev[FILENAMELENGTH];
2825:
2826: if(popbased==1){
2827: if(mobilav!=0)
2828: strcpy(digitp,"-populbased-mobilav-");
2829: else strcpy(digitp,"-populbased-nomobil-");
2830: }
2831: else
2832: strcpy(digitp,"-stablbased-");
2833:
2834: if (mobilav!=0) {
2835: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
2836: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
2837: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
2838: printf(" Error in movingaverage mobilav=%d\n",mobilav);
2839: }
2840: }
2841:
2842: strcpy(fileresprobmorprev,"prmorprev");
2843: sprintf(digit,"%-d",ij);
2844: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
2845: strcat(fileresprobmorprev,digit); /* Tvar to be done */
2846: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
2847: strcat(fileresprobmorprev,fileres);
2848: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
2849: printf("Problem with resultfile: %s\n", fileresprobmorprev);
2850: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
2851: }
2852: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
2853:
2854: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
2855: pstamp(ficresprobmorprev);
2856: 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);
2857: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
2858: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
2859: fprintf(ficresprobmorprev," p.%-d SE",j);
2860: for(i=1; i<=nlstate;i++)
2861: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
2862: }
2863: fprintf(ficresprobmorprev,"\n");
2864: fprintf(ficgp,"\n# Routine varevsij");
2865: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
2866: 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");
2867: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
2868: /* } */
2869: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
2870: pstamp(ficresvij);
2871: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
2872: if(popbased==1)
1.128 ! brouard 2873: fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
1.126 brouard 2874: else
2875: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
2876: fprintf(ficresvij,"# Age");
2877: for(i=1; i<=nlstate;i++)
2878: for(j=1; j<=nlstate;j++)
2879: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
2880: fprintf(ficresvij,"\n");
2881:
2882: xp=vector(1,npar);
2883: dnewm=matrix(1,nlstate,1,npar);
2884: doldm=matrix(1,nlstate,1,nlstate);
2885: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
2886: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
2887:
2888: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
2889: gpp=vector(nlstate+1,nlstate+ndeath);
2890: gmp=vector(nlstate+1,nlstate+ndeath);
2891: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
2892:
2893: if(estepm < stepm){
2894: printf ("Problem %d lower than %d\n",estepm, stepm);
2895: }
2896: else hstepm=estepm;
2897: /* For example we decided to compute the life expectancy with the smallest unit */
2898: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2899: nhstepm is the number of hstepm from age to agelim
2900: nstepm is the number of stepm from age to agelin.
1.128 ! brouard 2901: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 2902: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2903: survival function given by stepm (the optimization length). Unfortunately it
2904: means that if the survival funtion is printed every two years of age and if
2905: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2906: results. So we changed our mind and took the option of the best precision.
2907: */
2908: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2909: agelim = AGESUP;
2910: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
2911: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
2912: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2913: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2914: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
2915: gp=matrix(0,nhstepm,1,nlstate);
2916: gm=matrix(0,nhstepm,1,nlstate);
2917:
2918:
2919: for(theta=1; theta <=npar; theta++){
2920: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
2921: xp[i] = x[i] + (i==theta ?delti[theta]:0);
2922: }
2923: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
2924: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
2925:
2926: if (popbased==1) {
2927: if(mobilav ==0){
2928: for(i=1; i<=nlstate;i++)
2929: prlim[i][i]=probs[(int)age][i][ij];
2930: }else{ /* mobilav */
2931: for(i=1; i<=nlstate;i++)
2932: prlim[i][i]=mobaverage[(int)age][i][ij];
2933: }
2934: }
2935:
2936: for(j=1; j<= nlstate; j++){
2937: for(h=0; h<=nhstepm; h++){
2938: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
2939: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
2940: }
2941: }
2942: /* This for computing probability of death (h=1 means
2943: computed over hstepm matrices product = hstepm*stepm months)
2944: as a weighted average of prlim.
2945: */
2946: for(j=nlstate+1;j<=nlstate+ndeath;j++){
2947: for(i=1,gpp[j]=0.; i<= nlstate; i++)
2948: gpp[j] += prlim[i][i]*p3mat[i][j][1];
2949: }
2950: /* end probability of death */
2951:
2952: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
2953: xp[i] = x[i] - (i==theta ?delti[theta]:0);
2954: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
2955: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
2956:
2957: if (popbased==1) {
2958: if(mobilav ==0){
2959: for(i=1; i<=nlstate;i++)
2960: prlim[i][i]=probs[(int)age][i][ij];
2961: }else{ /* mobilav */
2962: for(i=1; i<=nlstate;i++)
2963: prlim[i][i]=mobaverage[(int)age][i][ij];
2964: }
2965: }
2966:
1.128 ! brouard 2967: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 2968: for(h=0; h<=nhstepm; h++){
2969: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
2970: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
2971: }
2972: }
2973: /* This for computing probability of death (h=1 means
2974: computed over hstepm matrices product = hstepm*stepm months)
2975: as a weighted average of prlim.
2976: */
2977: for(j=nlstate+1;j<=nlstate+ndeath;j++){
2978: for(i=1,gmp[j]=0.; i<= nlstate; i++)
2979: gmp[j] += prlim[i][i]*p3mat[i][j][1];
2980: }
2981: /* end probability of death */
2982:
2983: for(j=1; j<= nlstate; j++) /* vareij */
2984: for(h=0; h<=nhstepm; h++){
2985: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
2986: }
2987:
2988: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
2989: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
2990: }
2991:
2992: } /* End theta */
2993:
2994: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
2995:
2996: for(h=0; h<=nhstepm; h++) /* veij */
2997: for(j=1; j<=nlstate;j++)
2998: for(theta=1; theta <=npar; theta++)
2999: trgradg[h][j][theta]=gradg[h][theta][j];
3000:
3001: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3002: for(theta=1; theta <=npar; theta++)
3003: trgradgp[j][theta]=gradgp[theta][j];
3004:
3005:
3006: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3007: for(i=1;i<=nlstate;i++)
3008: for(j=1;j<=nlstate;j++)
3009: vareij[i][j][(int)age] =0.;
3010:
3011: for(h=0;h<=nhstepm;h++){
3012: for(k=0;k<=nhstepm;k++){
3013: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3014: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3015: for(i=1;i<=nlstate;i++)
3016: for(j=1;j<=nlstate;j++)
3017: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3018: }
3019: }
3020:
3021: /* pptj */
3022: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3023: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3024: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3025: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3026: varppt[j][i]=doldmp[j][i];
3027: /* end ppptj */
3028: /* x centered again */
3029: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3030: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3031:
3032: if (popbased==1) {
3033: if(mobilav ==0){
3034: for(i=1; i<=nlstate;i++)
3035: prlim[i][i]=probs[(int)age][i][ij];
3036: }else{ /* mobilav */
3037: for(i=1; i<=nlstate;i++)
3038: prlim[i][i]=mobaverage[(int)age][i][ij];
3039: }
3040: }
3041:
3042: /* This for computing probability of death (h=1 means
3043: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3044: as a weighted average of prlim.
3045: */
3046: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3047: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3048: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3049: }
3050: /* end probability of death */
3051:
3052: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3053: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3054: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3055: for(i=1; i<=nlstate;i++){
3056: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3057: }
3058: }
3059: fprintf(ficresprobmorprev,"\n");
3060:
3061: fprintf(ficresvij,"%.0f ",age );
3062: for(i=1; i<=nlstate;i++)
3063: for(j=1; j<=nlstate;j++){
3064: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3065: }
3066: fprintf(ficresvij,"\n");
3067: free_matrix(gp,0,nhstepm,1,nlstate);
3068: free_matrix(gm,0,nhstepm,1,nlstate);
3069: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3070: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3071: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3072: } /* End age */
3073: free_vector(gpp,nlstate+1,nlstate+ndeath);
3074: free_vector(gmp,nlstate+1,nlstate+ndeath);
3075: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3076: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3077: fprintf(ficgp,"\nset noparametric;set nolabel; set ter png small;set size 0.65, 0.65");
3078: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3079: fprintf(ficgp,"\n set log y; set nolog x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3080: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3081: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3082: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3083: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
3084: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
3085: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
3086: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3087: 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);
3088: /* 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);
3089: */
3090: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3091: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3092:
3093: free_vector(xp,1,npar);
3094: free_matrix(doldm,1,nlstate,1,nlstate);
3095: free_matrix(dnewm,1,nlstate,1,npar);
3096: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3097: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3098: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3099: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3100: fclose(ficresprobmorprev);
3101: fflush(ficgp);
3102: fflush(fichtm);
3103: } /* end varevsij */
3104:
3105: /************ Variance of prevlim ******************/
3106: 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[])
3107: {
3108: /* Variance of prevalence limit */
3109: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3110: double **newm;
3111: double **dnewm,**doldm;
3112: int i, j, nhstepm, hstepm;
3113: int k, cptcode;
3114: double *xp;
3115: double *gp, *gm;
3116: double **gradg, **trgradg;
3117: double age,agelim;
3118: int theta;
3119:
3120: pstamp(ficresvpl);
3121: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3122: fprintf(ficresvpl,"# Age");
3123: for(i=1; i<=nlstate;i++)
3124: fprintf(ficresvpl," %1d-%1d",i,i);
3125: fprintf(ficresvpl,"\n");
3126:
3127: xp=vector(1,npar);
3128: dnewm=matrix(1,nlstate,1,npar);
3129: doldm=matrix(1,nlstate,1,nlstate);
3130:
3131: hstepm=1*YEARM; /* Every year of age */
3132: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3133: agelim = AGESUP;
3134: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3135: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3136: if (stepm >= YEARM) hstepm=1;
3137: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3138: gradg=matrix(1,npar,1,nlstate);
3139: gp=vector(1,nlstate);
3140: gm=vector(1,nlstate);
3141:
3142: for(theta=1; theta <=npar; theta++){
3143: for(i=1; i<=npar; i++){ /* Computes gradient */
3144: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3145: }
3146: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3147: for(i=1;i<=nlstate;i++)
3148: gp[i] = prlim[i][i];
3149:
3150: for(i=1; i<=npar; i++) /* Computes gradient */
3151: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3152: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3153: for(i=1;i<=nlstate;i++)
3154: gm[i] = prlim[i][i];
3155:
3156: for(i=1;i<=nlstate;i++)
3157: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3158: } /* End theta */
3159:
3160: trgradg =matrix(1,nlstate,1,npar);
3161:
3162: for(j=1; j<=nlstate;j++)
3163: for(theta=1; theta <=npar; theta++)
3164: trgradg[j][theta]=gradg[theta][j];
3165:
3166: for(i=1;i<=nlstate;i++)
3167: varpl[i][(int)age] =0.;
3168: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3169: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3170: for(i=1;i<=nlstate;i++)
3171: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3172:
3173: fprintf(ficresvpl,"%.0f ",age );
3174: for(i=1; i<=nlstate;i++)
3175: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3176: fprintf(ficresvpl,"\n");
3177: free_vector(gp,1,nlstate);
3178: free_vector(gm,1,nlstate);
3179: free_matrix(gradg,1,npar,1,nlstate);
3180: free_matrix(trgradg,1,nlstate,1,npar);
3181: } /* End age */
3182:
3183: free_vector(xp,1,npar);
3184: free_matrix(doldm,1,nlstate,1,npar);
3185: free_matrix(dnewm,1,nlstate,1,nlstate);
3186:
3187: }
3188:
3189: /************ Variance of one-step probabilities ******************/
3190: 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[])
3191: {
3192: int i, j=0, i1, k1, l1, t, tj;
3193: int k2, l2, j1, z1;
3194: int k=0,l, cptcode;
3195: int first=1, first1;
3196: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3197: double **dnewm,**doldm;
3198: double *xp;
3199: double *gp, *gm;
3200: double **gradg, **trgradg;
3201: double **mu;
3202: double age,agelim, cov[NCOVMAX];
3203: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3204: int theta;
3205: char fileresprob[FILENAMELENGTH];
3206: char fileresprobcov[FILENAMELENGTH];
3207: char fileresprobcor[FILENAMELENGTH];
3208:
3209: double ***varpij;
3210:
3211: strcpy(fileresprob,"prob");
3212: strcat(fileresprob,fileres);
3213: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3214: printf("Problem with resultfile: %s\n", fileresprob);
3215: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3216: }
3217: strcpy(fileresprobcov,"probcov");
3218: strcat(fileresprobcov,fileres);
3219: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3220: printf("Problem with resultfile: %s\n", fileresprobcov);
3221: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3222: }
3223: strcpy(fileresprobcor,"probcor");
3224: strcat(fileresprobcor,fileres);
3225: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3226: printf("Problem with resultfile: %s\n", fileresprobcor);
3227: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3228: }
3229: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3230: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3231: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3232: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3233: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3234: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3235: pstamp(ficresprob);
3236: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3237: fprintf(ficresprob,"# Age");
3238: pstamp(ficresprobcov);
3239: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3240: fprintf(ficresprobcov,"# Age");
3241: pstamp(ficresprobcor);
3242: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3243: fprintf(ficresprobcor,"# Age");
3244:
3245:
3246: for(i=1; i<=nlstate;i++)
3247: for(j=1; j<=(nlstate+ndeath);j++){
3248: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3249: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3250: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3251: }
3252: /* fprintf(ficresprob,"\n");
3253: fprintf(ficresprobcov,"\n");
3254: fprintf(ficresprobcor,"\n");
3255: */
3256: xp=vector(1,npar);
3257: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3258: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3259: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3260: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3261: first=1;
3262: fprintf(ficgp,"\n# Routine varprob");
3263: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3264: fprintf(fichtm,"\n");
3265:
3266: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3267: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3268: file %s<br>\n",optionfilehtmcov);
3269: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3270: and drawn. It helps understanding how is the covariance between two incidences.\
3271: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3272: 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. \
3273: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3274: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3275: standard deviations wide on each axis. <br>\
3276: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3277: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3278: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3279:
3280: cov[1]=1;
3281: tj=cptcoveff;
3282: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3283: j1=0;
3284: for(t=1; t<=tj;t++){
3285: for(i1=1; i1<=ncodemax[t];i1++){
3286: j1++;
3287: if (cptcovn>0) {
3288: fprintf(ficresprob, "\n#********** Variable ");
3289: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3290: fprintf(ficresprob, "**********\n#\n");
3291: fprintf(ficresprobcov, "\n#********** Variable ");
3292: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3293: fprintf(ficresprobcov, "**********\n#\n");
3294:
3295: fprintf(ficgp, "\n#********** Variable ");
3296: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3297: fprintf(ficgp, "**********\n#\n");
3298:
3299:
3300: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3301: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3302: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3303:
3304: fprintf(ficresprobcor, "\n#********** Variable ");
3305: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3306: fprintf(ficresprobcor, "**********\n#");
3307: }
3308:
3309: for (age=bage; age<=fage; age ++){
3310: cov[2]=age;
3311: for (k=1; k<=cptcovn;k++) {
3312: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
3313: }
3314: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3315: for (k=1; k<=cptcovprod;k++)
3316: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3317:
3318: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3319: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3320: gp=vector(1,(nlstate)*(nlstate+ndeath));
3321: gm=vector(1,(nlstate)*(nlstate+ndeath));
3322:
3323: for(theta=1; theta <=npar; theta++){
3324: for(i=1; i<=npar; i++)
3325: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3326:
3327: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3328:
3329: k=0;
3330: for(i=1; i<= (nlstate); i++){
3331: for(j=1; j<=(nlstate+ndeath);j++){
3332: k=k+1;
3333: gp[k]=pmmij[i][j];
3334: }
3335: }
3336:
3337: for(i=1; i<=npar; i++)
3338: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3339:
3340: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3341: k=0;
3342: for(i=1; i<=(nlstate); i++){
3343: for(j=1; j<=(nlstate+ndeath);j++){
3344: k=k+1;
3345: gm[k]=pmmij[i][j];
3346: }
3347: }
3348:
3349: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3350: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3351: }
3352:
3353: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3354: for(theta=1; theta <=npar; theta++)
3355: trgradg[j][theta]=gradg[theta][j];
3356:
3357: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3358: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3359: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3360: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3361: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3362: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3363:
3364: pmij(pmmij,cov,ncovmodel,x,nlstate);
3365:
3366: k=0;
3367: for(i=1; i<=(nlstate); i++){
3368: for(j=1; j<=(nlstate+ndeath);j++){
3369: k=k+1;
3370: mu[k][(int) age]=pmmij[i][j];
3371: }
3372: }
3373: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3374: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3375: varpij[i][j][(int)age] = doldm[i][j];
3376:
3377: /*printf("\n%d ",(int)age);
3378: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3379: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3380: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3381: }*/
3382:
3383: fprintf(ficresprob,"\n%d ",(int)age);
3384: fprintf(ficresprobcov,"\n%d ",(int)age);
3385: fprintf(ficresprobcor,"\n%d ",(int)age);
3386:
3387: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3388: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3389: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3390: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3391: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3392: }
3393: i=0;
3394: for (k=1; k<=(nlstate);k++){
3395: for (l=1; l<=(nlstate+ndeath);l++){
3396: i=i++;
3397: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3398: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3399: for (j=1; j<=i;j++){
3400: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3401: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3402: }
3403: }
3404: }/* end of loop for state */
3405: } /* end of loop for age */
3406:
3407: /* Confidence intervalle of pij */
3408: /*
3409: fprintf(ficgp,"\nset noparametric;unset label");
3410: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3411: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3412: 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);
3413: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3414: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3415: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3416: */
3417:
3418: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
3419: first1=1;
3420: for (k2=1; k2<=(nlstate);k2++){
3421: for (l2=1; l2<=(nlstate+ndeath);l2++){
3422: if(l2==k2) continue;
3423: j=(k2-1)*(nlstate+ndeath)+l2;
3424: for (k1=1; k1<=(nlstate);k1++){
3425: for (l1=1; l1<=(nlstate+ndeath);l1++){
3426: if(l1==k1) continue;
3427: i=(k1-1)*(nlstate+ndeath)+l1;
3428: if(i<=j) continue;
3429: for (age=bage; age<=fage; age ++){
3430: if ((int)age %5==0){
3431: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3432: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3433: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3434: mu1=mu[i][(int) age]/stepm*YEARM ;
3435: mu2=mu[j][(int) age]/stepm*YEARM;
3436: c12=cv12/sqrt(v1*v2);
3437: /* Computing eigen value of matrix of covariance */
3438: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3439: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3440: /* Eigen vectors */
3441: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3442: /*v21=sqrt(1.-v11*v11); *//* error */
3443: v21=(lc1-v1)/cv12*v11;
3444: v12=-v21;
3445: v22=v11;
3446: tnalp=v21/v11;
3447: if(first1==1){
3448: first1=0;
3449: 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);
3450: }
3451: 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);
3452: /*printf(fignu*/
3453: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3454: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3455: if(first==1){
3456: first=0;
3457: fprintf(ficgp,"\nset parametric;unset label");
3458: 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);
3459: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3460: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3461: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3462: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3463: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3464: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3465: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3466: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3467: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3468: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3469: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3470: 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",\
3471: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3472: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3473: }else{
3474: first=0;
3475: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3476: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3477: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3478: 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",\
3479: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3480: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3481: }/* if first */
3482: } /* age mod 5 */
3483: } /* end loop age */
3484: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3485: first=1;
3486: } /*l12 */
3487: } /* k12 */
3488: } /*l1 */
3489: }/* k1 */
3490: } /* loop covariates */
3491: }
3492: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3493: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3494: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3495: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3496: free_vector(xp,1,npar);
3497: fclose(ficresprob);
3498: fclose(ficresprobcov);
3499: fclose(ficresprobcor);
3500: fflush(ficgp);
3501: fflush(fichtmcov);
3502: }
3503:
3504:
3505: /******************* Printing html file ***********/
3506: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3507: int lastpass, int stepm, int weightopt, char model[],\
3508: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3509: int popforecast, int estepm ,\
3510: double jprev1, double mprev1,double anprev1, \
3511: double jprev2, double mprev2,double anprev2){
3512: int jj1, k1, i1, cpt;
3513:
3514: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3515: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3516: </ul>");
3517: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3518: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3519: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3520: fprintf(fichtm,"\
3521: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3522: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3523: fprintf(fichtm,"\
3524: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3525: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3526: fprintf(fichtm,"\
1.128 ! brouard 3527: - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126 brouard 3528: <a href=\"%s\">%s</a> <br>\n",
3529: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3530: fprintf(fichtm,"\
3531: - Population projections by age and states: \
3532: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3533:
3534: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3535:
3536: m=cptcoveff;
3537: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3538:
3539: jj1=0;
3540: for(k1=1; k1<=m;k1++){
3541: for(i1=1; i1<=ncodemax[k1];i1++){
3542: jj1++;
3543: if (cptcovn > 0) {
3544: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3545: for (cpt=1; cpt<=cptcoveff;cpt++)
3546: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3547: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3548: }
3549: /* Pij */
3550: 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> \
3551: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
3552: /* Quasi-incidences */
3553: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
3554: 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> \
3555: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
3556: /* Period (stable) prevalence in each health state */
3557: for(cpt=1; cpt<nlstate;cpt++){
3558: fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
3559: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
3560: }
3561: for(cpt=1; cpt<=nlstate;cpt++) {
3562: 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> \
3563: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
3564: }
3565: } /* end i1 */
3566: }/* End k1 */
3567: fprintf(fichtm,"</ul>");
3568:
3569:
3570: fprintf(fichtm,"\
3571: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3572: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3573:
3574: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3575: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3576: fprintf(fichtm,"\
3577: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3578: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
3579:
3580: fprintf(fichtm,"\
3581: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3582: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
3583: fprintf(fichtm,"\
3584: - 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): \
3585: <a href=\"%s\">%s</a> <br>\n</li>",
3586: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
3587: fprintf(fichtm,"\
3588: - (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): \
3589: <a href=\"%s\">%s</a> <br>\n</li>",
3590: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
3591: fprintf(fichtm,"\
1.128 ! brouard 3592: - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.126 brouard 3593: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
3594: fprintf(fichtm,"\
1.128 ! brouard 3595: - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
! 3596: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 3597: fprintf(fichtm,"\
3598: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
3599: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
3600:
3601: /* if(popforecast==1) fprintf(fichtm,"\n */
3602: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
3603: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
3604: /* <br>",fileres,fileres,fileres,fileres); */
3605: /* else */
3606: /* 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); */
3607: fflush(fichtm);
3608: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
3609:
3610: m=cptcoveff;
3611: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3612:
3613: jj1=0;
3614: for(k1=1; k1<=m;k1++){
3615: for(i1=1; i1<=ncodemax[k1];i1++){
3616: jj1++;
3617: if (cptcovn > 0) {
3618: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3619: for (cpt=1; cpt<=cptcoveff;cpt++)
3620: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3621: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3622: }
3623: for(cpt=1; cpt<=nlstate;cpt++) {
3624: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
3625: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
3626: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
3627: }
3628: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 ! brouard 3629: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
! 3630: true period expectancies (those weighted with period prevalences are also\
! 3631: drawn in addition to the population based expectancies computed using\
! 3632: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 3633: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
3634: } /* end i1 */
3635: }/* End k1 */
3636: fprintf(fichtm,"</ul>");
3637: fflush(fichtm);
3638: }
3639:
3640: /******************* Gnuplot file **************/
3641: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
3642:
3643: char dirfileres[132],optfileres[132];
3644: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
3645: int ng;
3646: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
3647: /* printf("Problem with file %s",optionfilegnuplot); */
3648: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
3649: /* } */
3650:
3651: /*#ifdef windows */
3652: fprintf(ficgp,"cd \"%s\" \n",pathc);
3653: /*#endif */
3654: m=pow(2,cptcoveff);
3655:
3656: strcpy(dirfileres,optionfilefiname);
3657: strcpy(optfileres,"vpl");
3658: /* 1eme*/
3659: for (cpt=1; cpt<= nlstate ; cpt ++) {
3660: for (k1=1; k1<= m ; k1 ++) {
3661: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
3662: fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
3663: fprintf(ficgp,"set xlabel \"Age\" \n\
3664: set ylabel \"Probability\" \n\
3665: set ter png small\n\
3666: set size 0.65,0.65\n\
3667: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
3668:
3669: for (i=1; i<= nlstate ; i ++) {
3670: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
3671: else fprintf(ficgp," \%%*lf (\%%*lf)");
3672: }
3673: 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);
3674: for (i=1; i<= nlstate ; i ++) {
3675: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
3676: else fprintf(ficgp," \%%*lf (\%%*lf)");
3677: }
3678: 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);
3679: for (i=1; i<= nlstate ; i ++) {
3680: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
3681: else fprintf(ficgp," \%%*lf (\%%*lf)");
3682: }
3683: 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));
3684: }
3685: }
3686: /*2 eme*/
3687:
3688: for (k1=1; k1<= m ; k1 ++) {
3689: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
3690: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
3691:
3692: for (i=1; i<= nlstate+1 ; i ++) {
3693: k=2*i;
3694: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
3695: for (j=1; j<= nlstate+1 ; j ++) {
3696: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
3697: else fprintf(ficgp," \%%*lf (\%%*lf)");
3698: }
3699: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
3700: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
3701: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
3702: for (j=1; j<= nlstate+1 ; j ++) {
3703: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
3704: else fprintf(ficgp," \%%*lf (\%%*lf)");
3705: }
3706: fprintf(ficgp,"\" t\"\" w l 0,");
3707: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
3708: for (j=1; j<= nlstate+1 ; j ++) {
3709: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
3710: else fprintf(ficgp," \%%*lf (\%%*lf)");
3711: }
3712: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
3713: else fprintf(ficgp,"\" t\"\" w l 0,");
3714: }
3715: }
3716:
3717: /*3eme*/
3718:
3719: for (k1=1; k1<= m ; k1 ++) {
3720: for (cpt=1; cpt<= nlstate ; cpt ++) {
3721: /* k=2+nlstate*(2*cpt-2); */
3722: k=2+(nlstate+1)*(cpt-1);
3723: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
3724: fprintf(ficgp,"set ter png small\n\
3725: set size 0.65,0.65\n\
3726: 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);
3727: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
3728: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
3729: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
3730: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
3731: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
3732: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
3733:
3734: */
3735: for (i=1; i< nlstate ; i ++) {
3736: 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);
3737: /* 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);*/
3738:
3739: }
3740: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
3741: }
3742: }
3743:
3744: /* CV preval stable (period) */
3745: for (k1=1; k1<= m ; k1 ++) {
3746: for (cpt=1; cpt<=nlstate ; cpt ++) {
3747: k=3;
3748: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
3749: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
3750: set ter png small\nset size 0.65,0.65\n\
3751: unset log y\n\
3752: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
3753:
3754: for (i=1; i< nlstate ; i ++)
3755: fprintf(ficgp,"+$%d",k+i+1);
3756: fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
3757:
3758: l=3+(nlstate+ndeath)*cpt;
3759: fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
3760: for (i=1; i< nlstate ; i ++) {
3761: l=3+(nlstate+ndeath)*cpt;
3762: fprintf(ficgp,"+$%d",l+i+1);
3763: }
3764: fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);
3765: }
3766: }
3767:
3768: /* proba elementaires */
3769: for(i=1,jk=1; i <=nlstate; i++){
3770: for(k=1; k <=(nlstate+ndeath); k++){
3771: if (k != i) {
3772: for(j=1; j <=ncovmodel; j++){
3773: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
3774: jk++;
3775: fprintf(ficgp,"\n");
3776: }
3777: }
3778: }
3779: }
3780:
3781: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
3782: for(jk=1; jk <=m; jk++) {
3783: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
3784: if (ng==2)
3785: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
3786: else
3787: fprintf(ficgp,"\nset title \"Probability\"\n");
3788: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
3789: i=1;
3790: for(k2=1; k2<=nlstate; k2++) {
3791: k3=i;
3792: for(k=1; k<=(nlstate+ndeath); k++) {
3793: if (k != k2){
3794: if(ng==2)
3795: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
3796: else
3797: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
3798: ij=1;
3799: for(j=3; j <=ncovmodel; j++) {
3800: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
3801: fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
3802: ij++;
3803: }
3804: else
3805: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
3806: }
3807: fprintf(ficgp,")/(1");
3808:
3809: for(k1=1; k1 <=nlstate; k1++){
3810: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
3811: ij=1;
3812: for(j=3; j <=ncovmodel; j++){
3813: if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
3814: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
3815: ij++;
3816: }
3817: else
3818: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
3819: }
3820: fprintf(ficgp,")");
3821: }
3822: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
3823: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
3824: i=i+ncovmodel;
3825: }
3826: } /* end k */
3827: } /* end k2 */
3828: } /* end jk */
3829: } /* end ng */
3830: fflush(ficgp);
3831: } /* end gnuplot */
3832:
3833:
3834: /*************** Moving average **************/
3835: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
3836:
3837: int i, cpt, cptcod;
3838: int modcovmax =1;
3839: int mobilavrange, mob;
3840: double age;
3841:
3842: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
3843: a covariate has 2 modalities */
3844: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
3845:
3846: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
3847: if(mobilav==1) mobilavrange=5; /* default */
3848: else mobilavrange=mobilav;
3849: for (age=bage; age<=fage; age++)
3850: for (i=1; i<=nlstate;i++)
3851: for (cptcod=1;cptcod<=modcovmax;cptcod++)
3852: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
3853: /* We keep the original values on the extreme ages bage, fage and for
3854: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
3855: we use a 5 terms etc. until the borders are no more concerned.
3856: */
3857: for (mob=3;mob <=mobilavrange;mob=mob+2){
3858: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
3859: for (i=1; i<=nlstate;i++){
3860: for (cptcod=1;cptcod<=modcovmax;cptcod++){
3861: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
3862: for (cpt=1;cpt<=(mob-1)/2;cpt++){
3863: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
3864: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
3865: }
3866: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
3867: }
3868: }
3869: }/* end age */
3870: }/* end mob */
3871: }else return -1;
3872: return 0;
3873: }/* End movingaverage */
3874:
3875:
3876: /************** Forecasting ******************/
3877: 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){
3878: /* proj1, year, month, day of starting projection
3879: agemin, agemax range of age
3880: dateprev1 dateprev2 range of dates during which prevalence is computed
3881: anproj2 year of en of projection (same day and month as proj1).
3882: */
3883: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
3884: int *popage;
3885: double agec; /* generic age */
3886: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
3887: double *popeffectif,*popcount;
3888: double ***p3mat;
3889: double ***mobaverage;
3890: char fileresf[FILENAMELENGTH];
3891:
3892: agelim=AGESUP;
3893: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
3894:
3895: strcpy(fileresf,"f");
3896: strcat(fileresf,fileres);
3897: if((ficresf=fopen(fileresf,"w"))==NULL) {
3898: printf("Problem with forecast resultfile: %s\n", fileresf);
3899: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
3900: }
3901: printf("Computing forecasting: result on file '%s' \n", fileresf);
3902: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
3903:
3904: if (cptcoveff==0) ncodemax[cptcoveff]=1;
3905:
3906: if (mobilav!=0) {
3907: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3908: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
3909: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3910: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3911: }
3912: }
3913:
3914: stepsize=(int) (stepm+YEARM-1)/YEARM;
3915: if (stepm<=12) stepsize=1;
3916: if(estepm < stepm){
3917: printf ("Problem %d lower than %d\n",estepm, stepm);
3918: }
3919: else hstepm=estepm;
3920:
3921: hstepm=hstepm/stepm;
3922: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
3923: fractional in yp1 */
3924: anprojmean=yp;
3925: yp2=modf((yp1*12),&yp);
3926: mprojmean=yp;
3927: yp1=modf((yp2*30.5),&yp);
3928: jprojmean=yp;
3929: if(jprojmean==0) jprojmean=1;
3930: if(mprojmean==0) jprojmean=1;
3931:
3932: i1=cptcoveff;
3933: if (cptcovn < 1){i1=1;}
3934:
3935: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
3936:
3937: fprintf(ficresf,"#****** Routine prevforecast **\n");
3938:
3939: /* if (h==(int)(YEARM*yearp)){ */
3940: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
3941: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
3942: k=k+1;
3943: fprintf(ficresf,"\n#******");
3944: for(j=1;j<=cptcoveff;j++) {
3945: 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]]);
3946: }
3947: fprintf(ficresf,"******\n");
3948: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
3949: for(j=1; j<=nlstate+ndeath;j++){
3950: for(i=1; i<=nlstate;i++)
3951: fprintf(ficresf," p%d%d",i,j);
3952: fprintf(ficresf," p.%d",j);
3953: }
3954: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
3955: fprintf(ficresf,"\n");
3956: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
3957:
3958: for (agec=fage; agec>=(ageminpar-1); agec--){
3959: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
3960: nhstepm = nhstepm/hstepm;
3961: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3962: oldm=oldms;savm=savms;
3963: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
3964:
3965: for (h=0; h<=nhstepm; h++){
3966: if (h*hstepm/YEARM*stepm ==yearp) {
3967: fprintf(ficresf,"\n");
3968: for(j=1;j<=cptcoveff;j++)
3969: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
3970: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
3971: }
3972: for(j=1; j<=nlstate+ndeath;j++) {
3973: ppij=0.;
3974: for(i=1; i<=nlstate;i++) {
3975: if (mobilav==1)
3976: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
3977: else {
3978: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
3979: }
3980: if (h*hstepm/YEARM*stepm== yearp) {
3981: fprintf(ficresf," %.3f", p3mat[i][j][h]);
3982: }
3983: } /* end i */
3984: if (h*hstepm/YEARM*stepm==yearp) {
3985: fprintf(ficresf," %.3f", ppij);
3986: }
3987: }/* end j */
3988: } /* end h */
3989: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3990: } /* end agec */
3991: } /* end yearp */
3992: } /* end cptcod */
3993: } /* end cptcov */
3994:
3995: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3996:
3997: fclose(ficresf);
3998: }
3999:
4000: /************** Forecasting *****not tested NB*************/
4001: 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){
4002:
4003: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4004: int *popage;
4005: double calagedatem, agelim, kk1, kk2;
4006: double *popeffectif,*popcount;
4007: double ***p3mat,***tabpop,***tabpopprev;
4008: double ***mobaverage;
4009: char filerespop[FILENAMELENGTH];
4010:
4011: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4012: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4013: agelim=AGESUP;
4014: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4015:
4016: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4017:
4018:
4019: strcpy(filerespop,"pop");
4020: strcat(filerespop,fileres);
4021: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4022: printf("Problem with forecast resultfile: %s\n", filerespop);
4023: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4024: }
4025: printf("Computing forecasting: result on file '%s' \n", filerespop);
4026: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4027:
4028: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4029:
4030: if (mobilav!=0) {
4031: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4032: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4033: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4034: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4035: }
4036: }
4037:
4038: stepsize=(int) (stepm+YEARM-1)/YEARM;
4039: if (stepm<=12) stepsize=1;
4040:
4041: agelim=AGESUP;
4042:
4043: hstepm=1;
4044: hstepm=hstepm/stepm;
4045:
4046: if (popforecast==1) {
4047: if((ficpop=fopen(popfile,"r"))==NULL) {
4048: printf("Problem with population file : %s\n",popfile);exit(0);
4049: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4050: }
4051: popage=ivector(0,AGESUP);
4052: popeffectif=vector(0,AGESUP);
4053: popcount=vector(0,AGESUP);
4054:
4055: i=1;
4056: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4057:
4058: imx=i;
4059: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4060: }
4061:
4062: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4063: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4064: k=k+1;
4065: fprintf(ficrespop,"\n#******");
4066: for(j=1;j<=cptcoveff;j++) {
4067: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4068: }
4069: fprintf(ficrespop,"******\n");
4070: fprintf(ficrespop,"# Age");
4071: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4072: if (popforecast==1) fprintf(ficrespop," [Population]");
4073:
4074: for (cpt=0; cpt<=0;cpt++) {
4075: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4076:
4077: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4078: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4079: nhstepm = nhstepm/hstepm;
4080:
4081: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4082: oldm=oldms;savm=savms;
4083: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4084:
4085: for (h=0; h<=nhstepm; h++){
4086: if (h==(int) (calagedatem+YEARM*cpt)) {
4087: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4088: }
4089: for(j=1; j<=nlstate+ndeath;j++) {
4090: kk1=0.;kk2=0;
4091: for(i=1; i<=nlstate;i++) {
4092: if (mobilav==1)
4093: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4094: else {
4095: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4096: }
4097: }
4098: if (h==(int)(calagedatem+12*cpt)){
4099: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4100: /*fprintf(ficrespop," %.3f", kk1);
4101: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4102: }
4103: }
4104: for(i=1; i<=nlstate;i++){
4105: kk1=0.;
4106: for(j=1; j<=nlstate;j++){
4107: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4108: }
4109: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4110: }
4111:
4112: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4113: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4114: }
4115: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4116: }
4117: }
4118:
4119: /******/
4120:
4121: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4122: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4123: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4124: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4125: nhstepm = nhstepm/hstepm;
4126:
4127: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4128: oldm=oldms;savm=savms;
4129: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4130: for (h=0; h<=nhstepm; h++){
4131: if (h==(int) (calagedatem+YEARM*cpt)) {
4132: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4133: }
4134: for(j=1; j<=nlstate+ndeath;j++) {
4135: kk1=0.;kk2=0;
4136: for(i=1; i<=nlstate;i++) {
4137: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4138: }
4139: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4140: }
4141: }
4142: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4143: }
4144: }
4145: }
4146: }
4147:
4148: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4149:
4150: if (popforecast==1) {
4151: free_ivector(popage,0,AGESUP);
4152: free_vector(popeffectif,0,AGESUP);
4153: free_vector(popcount,0,AGESUP);
4154: }
4155: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4156: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4157: fclose(ficrespop);
4158: } /* End of popforecast */
4159:
4160: int fileappend(FILE *fichier, char *optionfich)
4161: {
4162: if((fichier=fopen(optionfich,"a"))==NULL) {
4163: printf("Problem with file: %s\n", optionfich);
4164: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4165: return (0);
4166: }
4167: fflush(fichier);
4168: return (1);
4169: }
4170:
4171:
4172: /**************** function prwizard **********************/
4173: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4174: {
4175:
4176: /* Wizard to print covariance matrix template */
4177:
4178: char ca[32], cb[32], cc[32];
4179: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4180: int numlinepar;
4181:
4182: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4183: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4184: for(i=1; i <=nlstate; i++){
4185: jj=0;
4186: for(j=1; j <=nlstate+ndeath; j++){
4187: if(j==i) continue;
4188: jj++;
4189: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4190: printf("%1d%1d",i,j);
4191: fprintf(ficparo,"%1d%1d",i,j);
4192: for(k=1; k<=ncovmodel;k++){
4193: /* printf(" %lf",param[i][j][k]); */
4194: /* fprintf(ficparo," %lf",param[i][j][k]); */
4195: printf(" 0.");
4196: fprintf(ficparo," 0.");
4197: }
4198: printf("\n");
4199: fprintf(ficparo,"\n");
4200: }
4201: }
4202: printf("# Scales (for hessian or gradient estimation)\n");
4203: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4204: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4205: for(i=1; i <=nlstate; i++){
4206: jj=0;
4207: for(j=1; j <=nlstate+ndeath; j++){
4208: if(j==i) continue;
4209: jj++;
4210: fprintf(ficparo,"%1d%1d",i,j);
4211: printf("%1d%1d",i,j);
4212: fflush(stdout);
4213: for(k=1; k<=ncovmodel;k++){
4214: /* printf(" %le",delti3[i][j][k]); */
4215: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4216: printf(" 0.");
4217: fprintf(ficparo," 0.");
4218: }
4219: numlinepar++;
4220: printf("\n");
4221: fprintf(ficparo,"\n");
4222: }
4223: }
4224: printf("# Covariance matrix\n");
4225: /* # 121 Var(a12)\n\ */
4226: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4227: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4228: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4229: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4230: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4231: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4232: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4233: fflush(stdout);
4234: fprintf(ficparo,"# Covariance matrix\n");
4235: /* # 121 Var(a12)\n\ */
4236: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4237: /* # ...\n\ */
4238: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4239:
4240: for(itimes=1;itimes<=2;itimes++){
4241: jj=0;
4242: for(i=1; i <=nlstate; i++){
4243: for(j=1; j <=nlstate+ndeath; j++){
4244: if(j==i) continue;
4245: for(k=1; k<=ncovmodel;k++){
4246: jj++;
4247: ca[0]= k+'a'-1;ca[1]='\0';
4248: if(itimes==1){
4249: printf("#%1d%1d%d",i,j,k);
4250: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4251: }else{
4252: printf("%1d%1d%d",i,j,k);
4253: fprintf(ficparo,"%1d%1d%d",i,j,k);
4254: /* printf(" %.5le",matcov[i][j]); */
4255: }
4256: ll=0;
4257: for(li=1;li <=nlstate; li++){
4258: for(lj=1;lj <=nlstate+ndeath; lj++){
4259: if(lj==li) continue;
4260: for(lk=1;lk<=ncovmodel;lk++){
4261: ll++;
4262: if(ll<=jj){
4263: cb[0]= lk +'a'-1;cb[1]='\0';
4264: if(ll<jj){
4265: if(itimes==1){
4266: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4267: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4268: }else{
4269: printf(" 0.");
4270: fprintf(ficparo," 0.");
4271: }
4272: }else{
4273: if(itimes==1){
4274: printf(" Var(%s%1d%1d)",ca,i,j);
4275: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4276: }else{
4277: printf(" 0.");
4278: fprintf(ficparo," 0.");
4279: }
4280: }
4281: }
4282: } /* end lk */
4283: } /* end lj */
4284: } /* end li */
4285: printf("\n");
4286: fprintf(ficparo,"\n");
4287: numlinepar++;
4288: } /* end k*/
4289: } /*end j */
4290: } /* end i */
4291: } /* end itimes */
4292:
4293: } /* end of prwizard */
4294: /******************* Gompertz Likelihood ******************************/
4295: double gompertz(double x[])
4296: {
4297: double A,B,L=0.0,sump=0.,num=0.;
4298: int i,n=0; /* n is the size of the sample */
4299:
4300: for (i=0;i<=imx-1 ; i++) {
4301: sump=sump+weight[i];
4302: /* sump=sump+1;*/
4303: num=num+1;
4304: }
4305:
4306:
4307: /* for (i=0; i<=imx; i++)
4308: 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]);*/
4309:
4310: for (i=1;i<=imx ; i++)
4311: {
4312: if (cens[i] == 1 && wav[i]>1)
4313: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4314:
4315: if (cens[i] == 0 && wav[i]>1)
4316: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4317: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4318:
4319: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4320: if (wav[i] > 1 ) { /* ??? */
4321: L=L+A*weight[i];
4322: /* 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]);*/
4323: }
4324: }
4325:
4326: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4327:
4328: return -2*L*num/sump;
4329: }
4330:
4331: /******************* Printing html file ***********/
4332: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4333: int lastpass, int stepm, int weightopt, char model[],\
4334: int imx, double p[],double **matcov,double agemortsup){
4335: int i,k;
4336:
4337: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4338: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4339: for (i=1;i<=2;i++)
4340: 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]));
4341: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4342: fprintf(fichtm,"</ul>");
4343:
4344: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4345:
4346: 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>");
4347:
4348: for (k=agegomp;k<(agemortsup-2);k++)
4349: 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]);
4350:
4351:
4352: fflush(fichtm);
4353: }
4354:
4355: /******************* Gnuplot file **************/
4356: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4357:
4358: char dirfileres[132],optfileres[132];
4359: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4360: int ng;
4361:
4362:
4363: /*#ifdef windows */
4364: fprintf(ficgp,"cd \"%s\" \n",pathc);
4365: /*#endif */
4366:
4367:
4368: strcpy(dirfileres,optionfilefiname);
4369: strcpy(optfileres,"vpl");
4370: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4371: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
4372: fprintf(ficgp, "set ter png small\n set log y\n");
4373: fprintf(ficgp, "set size 0.65,0.65\n");
4374: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4375:
4376: }
4377:
4378:
4379:
4380:
4381:
4382: /***********************************************/
4383: /**************** Main Program *****************/
4384: /***********************************************/
4385:
4386: int main(int argc, char *argv[])
4387: {
4388: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
4389: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
4390: int linei, month, year,iout;
4391: int jj, ll, li, lj, lk, imk;
4392: int numlinepar=0; /* Current linenumber of parameter file */
4393: int itimes;
4394: int NDIM=2;
1.128 ! brouard 4395: int vpopbased=0;
1.126 brouard 4396:
4397: char ca[32], cb[32], cc[32];
4398: char dummy[]=" ";
4399: /* FILE *fichtm; *//* Html File */
4400: /* FILE *ficgp;*/ /*Gnuplot File */
4401: struct stat info;
4402: double agedeb, agefin,hf;
4403: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
4404:
4405: double fret;
4406: double **xi,tmp,delta;
4407:
4408: double dum; /* Dummy variable */
4409: double ***p3mat;
4410: double ***mobaverage;
4411: int *indx;
4412: char line[MAXLINE], linepar[MAXLINE];
4413: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
4414: char pathr[MAXLINE], pathimach[MAXLINE];
4415: char **bp, *tok, *val; /* pathtot */
4416: int firstobs=1, lastobs=10;
4417: int sdeb, sfin; /* Status at beginning and end */
4418: int c, h , cpt,l;
4419: int ju,jl, mi;
4420: int i1,j1, k1,k2,k3,jk,aa,bb, stepsize, ij;
4421: int jnais,jdc,jint4,jint1,jint2,jint3,**outcome,*tab;
4422: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
4423: int mobilav=0,popforecast=0;
4424: int hstepm, nhstepm;
4425: int agemortsup;
4426: float sumlpop=0.;
4427: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
4428: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
4429:
4430: double bage, fage, age, agelim, agebase;
4431: double ftolpl=FTOL;
4432: double **prlim;
4433: double *severity;
4434: double ***param; /* Matrix of parameters */
4435: double *p;
4436: double **matcov; /* Matrix of covariance */
4437: double ***delti3; /* Scale */
4438: double *delti; /* Scale */
4439: double ***eij, ***vareij;
4440: double **varpl; /* Variances of prevalence limits by age */
4441: double *epj, vepp;
4442: double kk1, kk2;
4443: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
4444: double **ximort;
4445: char *alph[]={"a","a","b","c","d","e"}, str[4];
4446: int *dcwave;
4447:
4448: char z[1]="c", occ;
4449:
4450: char stra[80], strb[80], strc[80], strd[80],stre[80],modelsav[80];
4451: char *strt, strtend[80];
4452: char *stratrunc;
4453: int lstra;
4454:
4455: long total_usecs;
4456:
4457: /* setlocale (LC_ALL, ""); */
4458: /* bindtextdomain (PACKAGE, LOCALEDIR); */
4459: /* textdomain (PACKAGE); */
4460: /* setlocale (LC_CTYPE, ""); */
4461: /* setlocale (LC_MESSAGES, ""); */
4462:
4463: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
4464: (void) gettimeofday(&start_time,&tzp);
4465: curr_time=start_time;
4466: tm = *localtime(&start_time.tv_sec);
4467: tmg = *gmtime(&start_time.tv_sec);
4468: strcpy(strstart,asctime(&tm));
4469:
4470: /* printf("Localtime (at start)=%s",strstart); */
4471: /* tp.tv_sec = tp.tv_sec +86400; */
4472: /* tm = *localtime(&start_time.tv_sec); */
4473: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
4474: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
4475: /* tmg.tm_hour=tmg.tm_hour + 1; */
4476: /* tp.tv_sec = mktime(&tmg); */
4477: /* strt=asctime(&tmg); */
4478: /* printf("Time(after) =%s",strstart); */
4479: /* (void) time (&time_value);
4480: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
4481: * tm = *localtime(&time_value);
4482: * strstart=asctime(&tm);
4483: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
4484: */
4485:
4486: nberr=0; /* Number of errors and warnings */
4487: nbwarn=0;
4488: getcwd(pathcd, size);
4489:
4490: printf("\n%s\n%s",version,fullversion);
4491: if(argc <=1){
4492: printf("\nEnter the parameter file name: ");
4493: fgets(pathr,FILENAMELENGTH,stdin);
4494: i=strlen(pathr);
4495: if(pathr[i-1]=='\n')
4496: pathr[i-1]='\0';
4497: for (tok = pathr; tok != NULL; ){
4498: printf("Pathr |%s|\n",pathr);
4499: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
4500: printf("val= |%s| pathr=%s\n",val,pathr);
4501: strcpy (pathtot, val);
4502: if(pathr[0] == '\0') break; /* Dirty */
4503: }
4504: }
4505: else{
4506: strcpy(pathtot,argv[1]);
4507: }
4508: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
4509: /*cygwin_split_path(pathtot,path,optionfile);
4510: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
4511: /* cutv(path,optionfile,pathtot,'\\');*/
4512:
4513: /* Split argv[0], imach program to get pathimach */
4514: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
4515: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
4516: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
4517: /* strcpy(pathimach,argv[0]); */
4518: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
4519: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
4520: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
4521: chdir(path); /* Can be a relative path */
4522: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
4523: printf("Current directory %s!\n",pathcd);
4524: strcpy(command,"mkdir ");
4525: strcat(command,optionfilefiname);
4526: if((outcmd=system(command)) != 0){
4527: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
4528: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
4529: /* fclose(ficlog); */
4530: /* exit(1); */
4531: }
4532: /* if((imk=mkdir(optionfilefiname))<0){ */
4533: /* perror("mkdir"); */
4534: /* } */
4535:
4536: /*-------- arguments in the command line --------*/
4537:
4538: /* Log file */
4539: strcat(filelog, optionfilefiname);
4540: strcat(filelog,".log"); /* */
4541: if((ficlog=fopen(filelog,"w"))==NULL) {
4542: printf("Problem with logfile %s\n",filelog);
4543: goto end;
4544: }
4545: fprintf(ficlog,"Log filename:%s\n",filelog);
4546: fprintf(ficlog,"\n%s\n%s",version,fullversion);
4547: fprintf(ficlog,"\nEnter the parameter file name: \n");
4548: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
4549: path=%s \n\
4550: optionfile=%s\n\
4551: optionfilext=%s\n\
4552: optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
4553:
4554: printf("Local time (at start):%s",strstart);
4555: fprintf(ficlog,"Local time (at start): %s",strstart);
4556: fflush(ficlog);
4557: /* (void) gettimeofday(&curr_time,&tzp); */
4558: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
4559:
4560: /* */
4561: strcpy(fileres,"r");
4562: strcat(fileres, optionfilefiname);
4563: strcat(fileres,".txt"); /* Other files have txt extension */
4564:
4565: /*---------arguments file --------*/
4566:
4567: if((ficpar=fopen(optionfile,"r"))==NULL) {
4568: printf("Problem with optionfile %s\n",optionfile);
4569: fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
4570: fflush(ficlog);
4571: goto end;
4572: }
4573:
4574:
4575:
4576: strcpy(filereso,"o");
4577: strcat(filereso,fileres);
4578: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
4579: printf("Problem with Output resultfile: %s\n", filereso);
4580: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
4581: fflush(ficlog);
4582: goto end;
4583: }
4584:
4585: /* Reads comments: lines beginning with '#' */
4586: numlinepar=0;
4587: while((c=getc(ficpar))=='#' && c!= EOF){
4588: ungetc(c,ficpar);
4589: fgets(line, MAXLINE, ficpar);
4590: numlinepar++;
4591: puts(line);
4592: fputs(line,ficparo);
4593: fputs(line,ficlog);
4594: }
4595: ungetc(c,ficpar);
4596:
4597: 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);
4598: numlinepar++;
4599: 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);
4600: 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);
4601: 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);
4602: fflush(ficlog);
4603: while((c=getc(ficpar))=='#' && c!= EOF){
4604: ungetc(c,ficpar);
4605: fgets(line, MAXLINE, ficpar);
4606: numlinepar++;
4607: puts(line);
4608: fputs(line,ficparo);
4609: fputs(line,ficlog);
4610: }
4611: ungetc(c,ficpar);
4612:
4613:
4614: covar=matrix(0,NCOVMAX,1,n);
4615: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement*/
4616: if (strlen(model)>1) cptcovn=nbocc(model,'+')+1;
4617:
4618: ncovmodel=2+cptcovn; /*Number of variables = cptcovn + intercept + age */
4619: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
4620: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4621:
4622: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
4623: delti=delti3[1][1];
4624: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
4625: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
4626: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
4627: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
4628: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
4629: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
4630: fclose (ficparo);
4631: fclose (ficlog);
4632: goto end;
4633: exit(0);
4634: }
4635: else if(mle==-3) {
4636: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
4637: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
4638: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
4639: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
4640: matcov=matrix(1,npar,1,npar);
4641: }
4642: else{
4643: /* Read guess parameters */
4644: /* Reads comments: lines beginning with '#' */
4645: while((c=getc(ficpar))=='#' && c!= EOF){
4646: ungetc(c,ficpar);
4647: fgets(line, MAXLINE, ficpar);
4648: numlinepar++;
4649: puts(line);
4650: fputs(line,ficparo);
4651: fputs(line,ficlog);
4652: }
4653: ungetc(c,ficpar);
4654:
4655: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
4656: for(i=1; i <=nlstate; i++){
4657: j=0;
4658: for(jj=1; jj <=nlstate+ndeath; jj++){
4659: if(jj==i) continue;
4660: j++;
4661: fscanf(ficpar,"%1d%1d",&i1,&j1);
4662: if ((i1 != i) && (j1 != j)){
4663: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
4664: It might be a problem of design; if ncovcol and the model are correct\n \
4665: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
4666: exit(1);
4667: }
4668: fprintf(ficparo,"%1d%1d",i1,j1);
4669: if(mle==1)
4670: printf("%1d%1d",i,j);
4671: fprintf(ficlog,"%1d%1d",i,j);
4672: for(k=1; k<=ncovmodel;k++){
4673: fscanf(ficpar," %lf",¶m[i][j][k]);
4674: if(mle==1){
4675: printf(" %lf",param[i][j][k]);
4676: fprintf(ficlog," %lf",param[i][j][k]);
4677: }
4678: else
4679: fprintf(ficlog," %lf",param[i][j][k]);
4680: fprintf(ficparo," %lf",param[i][j][k]);
4681: }
4682: fscanf(ficpar,"\n");
4683: numlinepar++;
4684: if(mle==1)
4685: printf("\n");
4686: fprintf(ficlog,"\n");
4687: fprintf(ficparo,"\n");
4688: }
4689: }
4690: fflush(ficlog);
4691:
4692: p=param[1][1];
4693:
4694: /* Reads comments: lines beginning with '#' */
4695: while((c=getc(ficpar))=='#' && c!= EOF){
4696: ungetc(c,ficpar);
4697: fgets(line, MAXLINE, ficpar);
4698: numlinepar++;
4699: puts(line);
4700: fputs(line,ficparo);
4701: fputs(line,ficlog);
4702: }
4703: ungetc(c,ficpar);
4704:
4705: for(i=1; i <=nlstate; i++){
4706: for(j=1; j <=nlstate+ndeath-1; j++){
4707: fscanf(ficpar,"%1d%1d",&i1,&j1);
4708: if ((i1-i)*(j1-j)!=0){
4709: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
4710: exit(1);
4711: }
4712: printf("%1d%1d",i,j);
4713: fprintf(ficparo,"%1d%1d",i1,j1);
4714: fprintf(ficlog,"%1d%1d",i1,j1);
4715: for(k=1; k<=ncovmodel;k++){
4716: fscanf(ficpar,"%le",&delti3[i][j][k]);
4717: printf(" %le",delti3[i][j][k]);
4718: fprintf(ficparo," %le",delti3[i][j][k]);
4719: fprintf(ficlog," %le",delti3[i][j][k]);
4720: }
4721: fscanf(ficpar,"\n");
4722: numlinepar++;
4723: printf("\n");
4724: fprintf(ficparo,"\n");
4725: fprintf(ficlog,"\n");
4726: }
4727: }
4728: fflush(ficlog);
4729:
4730: delti=delti3[1][1];
4731:
4732:
4733: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
4734:
4735: /* Reads comments: lines beginning with '#' */
4736: while((c=getc(ficpar))=='#' && c!= EOF){
4737: ungetc(c,ficpar);
4738: fgets(line, MAXLINE, ficpar);
4739: numlinepar++;
4740: puts(line);
4741: fputs(line,ficparo);
4742: fputs(line,ficlog);
4743: }
4744: ungetc(c,ficpar);
4745:
4746: matcov=matrix(1,npar,1,npar);
4747: for(i=1; i <=npar; i++){
4748: fscanf(ficpar,"%s",&str);
4749: if(mle==1)
4750: printf("%s",str);
4751: fprintf(ficlog,"%s",str);
4752: fprintf(ficparo,"%s",str);
4753: for(j=1; j <=i; j++){
4754: fscanf(ficpar," %le",&matcov[i][j]);
4755: if(mle==1){
4756: printf(" %.5le",matcov[i][j]);
4757: }
4758: fprintf(ficlog," %.5le",matcov[i][j]);
4759: fprintf(ficparo," %.5le",matcov[i][j]);
4760: }
4761: fscanf(ficpar,"\n");
4762: numlinepar++;
4763: if(mle==1)
4764: printf("\n");
4765: fprintf(ficlog,"\n");
4766: fprintf(ficparo,"\n");
4767: }
4768: for(i=1; i <=npar; i++)
4769: for(j=i+1;j<=npar;j++)
4770: matcov[i][j]=matcov[j][i];
4771:
4772: if(mle==1)
4773: printf("\n");
4774: fprintf(ficlog,"\n");
4775:
4776: fflush(ficlog);
4777:
4778: /*-------- Rewriting parameter file ----------*/
4779: strcpy(rfileres,"r"); /* "Rparameterfile */
4780: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
4781: strcat(rfileres,"."); /* */
4782: strcat(rfileres,optionfilext); /* Other files have txt extension */
4783: if((ficres =fopen(rfileres,"w"))==NULL) {
4784: printf("Problem writing new parameter file: %s\n", fileres);goto end;
4785: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
4786: }
4787: fprintf(ficres,"#%s\n",version);
4788: } /* End of mle != -3 */
4789:
4790: /*-------- data file ----------*/
4791: if((fic=fopen(datafile,"r"))==NULL) {
4792: printf("Problem while opening datafile: %s\n", datafile);goto end;
4793: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);goto end;
4794: }
4795:
4796: n= lastobs;
4797: severity = vector(1,maxwav);
4798: outcome=imatrix(1,maxwav+1,1,n);
4799: num=lvector(1,n);
4800: moisnais=vector(1,n);
4801: annais=vector(1,n);
4802: moisdc=vector(1,n);
4803: andc=vector(1,n);
4804: agedc=vector(1,n);
4805: cod=ivector(1,n);
4806: weight=vector(1,n);
4807: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
4808: mint=matrix(1,maxwav,1,n);
4809: anint=matrix(1,maxwav,1,n);
4810: s=imatrix(1,maxwav+1,1,n);
4811: tab=ivector(1,NCOVMAX);
4812: ncodemax=ivector(1,8);
4813:
4814: i=1;
4815: linei=0;
4816: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4817: linei=linei+1;
4818: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4819: if(line[j] == '\t')
4820: line[j] = ' ';
4821: }
4822: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4823: ;
4824: };
4825: line[j+1]=0; /* Trims blanks at end of line */
4826: if(line[0]=='#'){
4827: fprintf(ficlog,"Comment line\n%s\n",line);
4828: printf("Comment line\n%s\n",line);
4829: continue;
4830: }
4831:
4832: for (j=maxwav;j>=1;j--){
4833: cutv(stra, strb,line,' ');
4834: errno=0;
4835: lval=strtol(strb,&endptr,10);
4836: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4837: if( strb[0]=='\0' || (*endptr != '\0')){
4838: 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);
4839: exit(1);
4840: }
4841: s[j][i]=lval;
4842:
4843: strcpy(line,stra);
4844: cutv(stra, strb,line,' ');
4845: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4846: }
4847: else if(iout=sscanf(strb,"%s.") != 0){
4848: month=99;
4849: year=9999;
4850: }else{
4851: 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);
4852: exit(1);
4853: }
4854: anint[j][i]= (double) year;
4855: mint[j][i]= (double)month;
4856: strcpy(line,stra);
4857: } /* ENd Waves */
4858:
4859: cutv(stra, strb,line,' ');
4860: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4861: }
4862: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4863: month=99;
4864: year=9999;
4865: }else{
4866: 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);
4867: exit(1);
4868: }
4869: andc[i]=(double) year;
4870: moisdc[i]=(double) month;
4871: strcpy(line,stra);
4872:
4873: cutv(stra, strb,line,' ');
4874: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4875: }
4876: else if(iout=sscanf(strb,"%s.") != 0){
4877: month=99;
4878: year=9999;
4879: }else{
4880: 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);
4881: exit(1);
4882: }
4883: annais[i]=(double)(year);
4884: moisnais[i]=(double)(month);
4885: strcpy(line,stra);
4886:
4887: cutv(stra, strb,line,' ');
4888: errno=0;
4889: dval=strtod(strb,&endptr);
4890: if( strb[0]=='\0' || (*endptr != '\0')){
4891: printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4892: exit(1);
4893: }
4894: weight[i]=dval;
4895: strcpy(line,stra);
4896:
4897: for (j=ncovcol;j>=1;j--){
4898: cutv(stra, strb,line,' ');
4899: errno=0;
4900: lval=strtol(strb,&endptr,10);
4901: if( strb[0]=='\0' || (*endptr != '\0')){
4902: 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);
4903: exit(1);
4904: }
4905: if(lval <-1 || lval >1){
4906: printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
4907: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4908: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4909: For example, for multinomial values like 1, 2 and 3,\n \
4910: build V1=0 V2=0 for the reference value (1),\n \
4911: V1=1 V2=0 for (2) \n \
4912: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4913: output of IMaCh is often meaningless.\n \
4914: Exiting.\n",lval,linei, i,line,j);
4915: exit(1);
4916: }
4917: covar[j][i]=(double)(lval);
4918: strcpy(line,stra);
4919: }
4920: lstra=strlen(stra);
4921:
4922: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
4923: stratrunc = &(stra[lstra-9]);
4924: num[i]=atol(stratrunc);
4925: }
4926: else
4927: num[i]=atol(stra);
4928: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
4929: 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;}*/
4930:
4931: i=i+1;
4932: } /* End loop reading data */
4933: fclose(fic);
4934: /* printf("ii=%d", ij);
4935: scanf("%d",i);*/
4936: imx=i-1; /* Number of individuals */
4937:
4938: /* for (i=1; i<=imx; i++){
4939: if ((s[1][i]==3) && (s[2][i]==2)) s[2][i]=3;
4940: if ((s[2][i]==3) && (s[3][i]==2)) s[3][i]=3;
4941: if ((s[3][i]==3) && (s[4][i]==2)) s[4][i]=3;
4942: }*/
4943: /* for (i=1; i<=imx; i++){
4944: if (s[4][i]==9) s[4][i]=-1;
4945: 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]));}*/
4946:
4947: /* for (i=1; i<=imx; i++) */
4948:
4949: /*if ((s[3][i]==3) || (s[4][i]==3)) weight[i]=0.08;
4950: else weight[i]=1;*/
4951:
4952: /* Calculation of the number of parameters from char model */
4953: Tvar=ivector(1,15); /* stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
4954: Tprod=ivector(1,15);
4955: Tvaraff=ivector(1,15);
4956: Tvard=imatrix(1,15,1,2);
4957: Tage=ivector(1,15);
4958:
4959: if (strlen(model) >1){ /* If there is at least 1 covariate */
4960: j=0, j1=0, k1=1, k2=1;
4961: j=nbocc(model,'+'); /* j=Number of '+' */
4962: j1=nbocc(model,'*'); /* j1=Number of '*' */
4963: cptcovn=j+1;
4964: cptcovprod=j1; /*Number of products */
4965:
4966: strcpy(modelsav,model);
4967: if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
4968: printf("Error. Non available option model=%s ",model);
4969: fprintf(ficlog,"Error. Non available option model=%s ",model);
4970: goto end;
4971: }
4972:
4973: /* This loop fills the array Tvar from the string 'model'.*/
4974:
4975: for(i=(j+1); i>=1;i--){
4976: cutv(stra,strb,modelsav,'+'); /* keeps in strb after the last + */
4977: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
4978: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
4979: /*scanf("%d",i);*/
4980: if (strchr(strb,'*')) { /* Model includes a product */
4981: cutv(strd,strc,strb,'*'); /* strd*strc Vm*Vn (if not *age)*/
4982: if (strcmp(strc,"age")==0) { /* Vn*age */
4983: cptcovprod--;
4984: cutv(strb,stre,strd,'V');
4985: Tvar[i]=atoi(stre); /* computes n in Vn and stores in Tvar*/
4986: cptcovage++;
4987: Tage[cptcovage]=i;
4988: /*printf("stre=%s ", stre);*/
4989: }
4990: else if (strcmp(strd,"age")==0) { /* or age*Vn */
4991: cptcovprod--;
4992: cutv(strb,stre,strc,'V');
4993: Tvar[i]=atoi(stre);
4994: cptcovage++;
4995: Tage[cptcovage]=i;
4996: }
4997: else { /* Age is not in the model */
4998: cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n*/
4999: Tvar[i]=ncovcol+k1;
5000: cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
5001: Tprod[k1]=i;
5002: Tvard[k1][1]=atoi(strc); /* m*/
5003: Tvard[k1][2]=atoi(stre); /* n */
5004: Tvar[cptcovn+k2]=Tvard[k1][1];
5005: Tvar[cptcovn+k2+1]=Tvard[k1][2];
5006: for (k=1; k<=lastobs;k++)
5007: covar[ncovcol+k1][k]=covar[atoi(stre)][k]*covar[atoi(strc)][k];
5008: k1++;
5009: k2=k2+2;
5010: }
5011: }
5012: else { /* no more sum */
5013: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5014: /* scanf("%d",i);*/
5015: cutv(strd,strc,strb,'V');
5016: Tvar[i]=atoi(strc);
5017: }
5018: strcpy(modelsav,stra);
5019: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5020: scanf("%d",i);*/
5021: } /* end of loop + */
5022: } /* end model */
5023:
5024: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5025: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5026:
5027: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5028: printf("cptcovprod=%d ", cptcovprod);
5029: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5030:
5031: scanf("%d ",i);*/
5032:
5033: /* if(mle==1){*/
5034: if (weightopt != 1) { /* Maximisation without weights*/
5035: for(i=1;i<=n;i++) weight[i]=1.0;
5036: }
5037: /*-calculation of age at interview from date of interview and age at death -*/
5038: agev=matrix(1,maxwav,1,imx);
5039:
5040: for (i=1; i<=imx; i++) {
5041: for(m=2; (m<= maxwav); m++) {
5042: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5043: anint[m][i]=9999;
5044: s[m][i]=-1;
5045: }
5046: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5047: nberr++;
5048: 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);
5049: 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);
5050: s[m][i]=-1;
5051: }
5052: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5053: nberr++;
5054: 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]);
5055: 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]);
5056: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5057: }
5058: }
5059: }
5060:
5061: for (i=1; i<=imx; i++) {
5062: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5063: for(m=firstpass; (m<= lastpass); m++){
5064: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5065: if (s[m][i] >= nlstate+1) {
5066: if(agedc[i]>0)
5067: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5068: agev[m][i]=agedc[i];
5069: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5070: else {
5071: if ((int)andc[i]!=9999){
5072: nbwarn++;
5073: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5074: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5075: agev[m][i]=-1;
5076: }
5077: }
5078: }
5079: else if(s[m][i] !=9){ /* Standard case, age in fractional
5080: years but with the precision of a month */
5081: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5082: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5083: agev[m][i]=1;
5084: else if(agev[m][i] <agemin){
5085: agemin=agev[m][i];
5086: /*printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], agemin);*/
5087: }
5088: else if(agev[m][i] >agemax){
5089: agemax=agev[m][i];
5090: /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
5091: }
5092: /*agev[m][i]=anint[m][i]-annais[i];*/
5093: /* agev[m][i] = age[i]+2*m;*/
5094: }
5095: else { /* =9 */
5096: agev[m][i]=1;
5097: s[m][i]=-1;
5098: }
5099: }
5100: else /*= 0 Unknown */
5101: agev[m][i]=1;
5102: }
5103:
5104: }
5105: for (i=1; i<=imx; i++) {
5106: for(m=firstpass; (m<=lastpass); m++){
5107: if (s[m][i] > (nlstate+ndeath)) {
5108: nberr++;
5109: 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);
5110: 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);
5111: goto end;
5112: }
5113: }
5114: }
5115:
5116: /*for (i=1; i<=imx; i++){
5117: for (m=firstpass; (m<lastpass); m++){
5118: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5119: }
5120:
5121: }*/
5122:
5123:
5124: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
5125: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
5126:
5127: agegomp=(int)agemin;
5128: free_vector(severity,1,maxwav);
5129: free_imatrix(outcome,1,maxwav+1,1,n);
5130: free_vector(moisnais,1,n);
5131: free_vector(annais,1,n);
5132: /* free_matrix(mint,1,maxwav,1,n);
5133: free_matrix(anint,1,maxwav,1,n);*/
5134: free_vector(moisdc,1,n);
5135: free_vector(andc,1,n);
5136:
5137:
5138: wav=ivector(1,imx);
5139: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5140: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5141: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5142:
5143: /* Concatenates waves */
5144: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
5145:
5146: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5147:
5148: Tcode=ivector(1,100);
5149: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5150: ncodemax[1]=1;
5151: if (cptcovn > 0) tricode(Tvar,nbcode,imx);
5152:
5153: codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of
5154: the estimations*/
5155: h=0;
5156: m=pow(2,cptcoveff);
5157:
5158: for(k=1;k<=cptcoveff; k++){
5159: for(i=1; i <=(m/pow(2,k));i++){
5160: for(j=1; j <= ncodemax[k]; j++){
5161: for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){
5162: h++;
5163: if (h>m) h=1;codtab[h][k]=j;codtab[h][Tvar[k]]=j;
5164: /* printf("h=%d k=%d j=%d codtab[h][k]=%d tvar[k]=%d \n",h, k,j,codtab[h][k],Tvar[k]);*/
5165: }
5166: }
5167: }
5168: }
5169: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5170: codtab[1][2]=1;codtab[2][2]=2; */
5171: /* for(i=1; i <=m ;i++){
5172: for(k=1; k <=cptcovn; k++){
5173: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
5174: }
5175: printf("\n");
5176: }
5177: scanf("%d",i);*/
5178:
5179: /*------------ gnuplot -------------*/
5180: strcpy(optionfilegnuplot,optionfilefiname);
5181: if(mle==-3)
5182: strcat(optionfilegnuplot,"-mort");
5183: strcat(optionfilegnuplot,".gp");
5184:
5185: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5186: printf("Problem with file %s",optionfilegnuplot);
5187: }
5188: else{
5189: fprintf(ficgp,"\n# %s\n", version);
5190: fprintf(ficgp,"# %s\n", optionfilegnuplot);
5191: fprintf(ficgp,"set missing 'NaNq'\n");
5192: }
5193: /* fclose(ficgp);*/
5194: /*--------- index.htm --------*/
5195:
5196: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5197: if(mle==-3)
5198: strcat(optionfilehtm,"-mort");
5199: strcat(optionfilehtm,".htm");
5200: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
5201: printf("Problem with %s \n",optionfilehtm), exit(0);
5202: }
5203:
5204: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5205: strcat(optionfilehtmcov,"-cov.htm");
5206: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5207: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5208: }
5209: else{
5210: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5211: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5212: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5213: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5214: }
5215:
5216: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5217: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5218: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5219: \n\
5220: <hr size=\"2\" color=\"#EC5E5E\">\
5221: <ul><li><h4>Parameter files</h4>\n\
5222: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5223: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5224: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5225: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5226: - Date and time at start: %s</ul>\n",\
5227: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5228: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5229: fileres,fileres,\
5230: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5231: fflush(fichtm);
5232:
5233: strcpy(pathr,path);
5234: strcat(pathr,optionfilefiname);
5235: chdir(optionfilefiname); /* Move to directory named optionfile */
5236:
5237: /* Calculates basic frequencies. Computes observed prevalence at single age
5238: and prints on file fileres'p'. */
5239: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5240:
5241: fprintf(fichtm,"\n");
5242: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5243: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5244: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5245: imx,agemin,agemax,jmin,jmax,jmean);
5246: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5247: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5248: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5249: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5250: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5251:
5252:
5253: /* For Powell, parameters are in a vector p[] starting at p[1]
5254: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5255: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5256:
5257: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5258:
5259: if (mle==-3){
5260: ximort=matrix(1,NDIM,1,NDIM);
5261: cens=ivector(1,n);
5262: ageexmed=vector(1,n);
5263: agecens=vector(1,n);
5264: dcwave=ivector(1,n);
5265:
5266: for (i=1; i<=imx; i++){
5267: dcwave[i]=-1;
5268: for (m=firstpass; m<=lastpass; m++)
5269: if (s[m][i]>nlstate) {
5270: dcwave[i]=m;
5271: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5272: break;
5273: }
5274: }
5275:
5276: for (i=1; i<=imx; i++) {
5277: if (wav[i]>0){
5278: ageexmed[i]=agev[mw[1][i]][i];
5279: j=wav[i];
5280: agecens[i]=1.;
5281:
5282: if (ageexmed[i]> 1 && wav[i] > 0){
5283: agecens[i]=agev[mw[j][i]][i];
5284: cens[i]= 1;
5285: }else if (ageexmed[i]< 1)
5286: cens[i]= -1;
5287: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
5288: cens[i]=0 ;
5289: }
5290: else cens[i]=-1;
5291: }
5292:
5293: for (i=1;i<=NDIM;i++) {
5294: for (j=1;j<=NDIM;j++)
5295: ximort[i][j]=(i == j ? 1.0 : 0.0);
5296: }
5297:
5298: p[1]=0.0268; p[NDIM]=0.083;
5299: /*printf("%lf %lf", p[1], p[2]);*/
5300:
5301:
5302: printf("Powell\n"); fprintf(ficlog,"Powell\n");
5303: strcpy(filerespow,"pow-mort");
5304: strcat(filerespow,fileres);
5305: if((ficrespow=fopen(filerespow,"w"))==NULL) {
5306: printf("Problem with resultfile: %s\n", filerespow);
5307: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
5308: }
5309: fprintf(ficrespow,"# Powell\n# iter -2*LL");
5310: /* for (i=1;i<=nlstate;i++)
5311: for(j=1;j<=nlstate+ndeath;j++)
5312: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
5313: */
5314: fprintf(ficrespow,"\n");
5315:
5316: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
5317: fclose(ficrespow);
5318:
5319: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
5320:
5321: for(i=1; i <=NDIM; i++)
5322: for(j=i+1;j<=NDIM;j++)
5323: matcov[i][j]=matcov[j][i];
5324:
5325: printf("\nCovariance matrix\n ");
5326: for(i=1; i <=NDIM; i++) {
5327: for(j=1;j<=NDIM;j++){
5328: printf("%f ",matcov[i][j]);
5329: }
5330: printf("\n ");
5331: }
5332:
5333: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
5334: for (i=1;i<=NDIM;i++)
5335: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
5336:
5337: lsurv=vector(1,AGESUP);
5338: lpop=vector(1,AGESUP);
5339: tpop=vector(1,AGESUP);
5340: lsurv[agegomp]=100000;
5341:
5342: for (k=agegomp;k<=AGESUP;k++) {
5343: agemortsup=k;
5344: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
5345: }
5346:
5347: for (k=agegomp;k<agemortsup;k++)
5348: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
5349:
5350: for (k=agegomp;k<agemortsup;k++){
5351: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
5352: sumlpop=sumlpop+lpop[k];
5353: }
5354:
5355: tpop[agegomp]=sumlpop;
5356: for (k=agegomp;k<(agemortsup-3);k++){
5357: /* tpop[k+1]=2;*/
5358: tpop[k+1]=tpop[k]-lpop[k];
5359: }
5360:
5361:
5362: printf("\nAge lx qx dx Lx Tx e(x)\n");
5363: for (k=agegomp;k<(agemortsup-2);k++)
5364: 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]);
5365:
5366:
5367: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
5368: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
5369:
5370: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
5371: stepm, weightopt,\
5372: model,imx,p,matcov,agemortsup);
5373:
5374: free_vector(lsurv,1,AGESUP);
5375: free_vector(lpop,1,AGESUP);
5376: free_vector(tpop,1,AGESUP);
5377: } /* Endof if mle==-3 */
5378:
5379: else{ /* For mle >=1 */
5380:
5381: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
5382: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
5383: for (k=1; k<=npar;k++)
5384: printf(" %d %8.5f",k,p[k]);
5385: printf("\n");
5386: globpr=1; /* to print the contributions */
5387: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
5388: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
5389: for (k=1; k<=npar;k++)
5390: printf(" %d %8.5f",k,p[k]);
5391: printf("\n");
5392: if(mle>=1){ /* Could be 1 or 2 */
5393: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
5394: }
5395:
5396: /*--------- results files --------------*/
5397: 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);
5398:
5399:
5400: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5401: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5402: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5403: for(i=1,jk=1; i <=nlstate; i++){
5404: for(k=1; k <=(nlstate+ndeath); k++){
5405: if (k != i) {
5406: printf("%d%d ",i,k);
5407: fprintf(ficlog,"%d%d ",i,k);
5408: fprintf(ficres,"%1d%1d ",i,k);
5409: for(j=1; j <=ncovmodel; j++){
5410: printf("%lf ",p[jk]);
5411: fprintf(ficlog,"%lf ",p[jk]);
5412: fprintf(ficres,"%lf ",p[jk]);
5413: jk++;
5414: }
5415: printf("\n");
5416: fprintf(ficlog,"\n");
5417: fprintf(ficres,"\n");
5418: }
5419: }
5420: }
5421: if(mle!=0){
5422: /* Computing hessian and covariance matrix */
5423: ftolhess=ftol; /* Usually correct */
5424: hesscov(matcov, p, npar, delti, ftolhess, func);
5425: }
5426: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
5427: printf("# Scales (for hessian or gradient estimation)\n");
5428: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
5429: for(i=1,jk=1; i <=nlstate; i++){
5430: for(j=1; j <=nlstate+ndeath; j++){
5431: if (j!=i) {
5432: fprintf(ficres,"%1d%1d",i,j);
5433: printf("%1d%1d",i,j);
5434: fprintf(ficlog,"%1d%1d",i,j);
5435: for(k=1; k<=ncovmodel;k++){
5436: printf(" %.5e",delti[jk]);
5437: fprintf(ficlog," %.5e",delti[jk]);
5438: fprintf(ficres," %.5e",delti[jk]);
5439: jk++;
5440: }
5441: printf("\n");
5442: fprintf(ficlog,"\n");
5443: fprintf(ficres,"\n");
5444: }
5445: }
5446: }
5447:
5448: 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");
5449: if(mle>=1)
5450: 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");
5451: 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");
5452: /* # 121 Var(a12)\n\ */
5453: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5454: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5455: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5456: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5457: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5458: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5459: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5460:
5461:
5462: /* Just to have a covariance matrix which will be more understandable
5463: even is we still don't want to manage dictionary of variables
5464: */
5465: for(itimes=1;itimes<=2;itimes++){
5466: jj=0;
5467: for(i=1; i <=nlstate; i++){
5468: for(j=1; j <=nlstate+ndeath; j++){
5469: if(j==i) continue;
5470: for(k=1; k<=ncovmodel;k++){
5471: jj++;
5472: ca[0]= k+'a'-1;ca[1]='\0';
5473: if(itimes==1){
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: }else{
5479: if(mle>=1)
5480: printf("%1d%1d%d",i,j,k);
5481: fprintf(ficlog,"%1d%1d%d",i,j,k);
5482: fprintf(ficres,"%1d%1d%d",i,j,k);
5483: }
5484: ll=0;
5485: for(li=1;li <=nlstate; li++){
5486: for(lj=1;lj <=nlstate+ndeath; lj++){
5487: if(lj==li) continue;
5488: for(lk=1;lk<=ncovmodel;lk++){
5489: ll++;
5490: if(ll<=jj){
5491: cb[0]= lk +'a'-1;cb[1]='\0';
5492: if(ll<jj){
5493: if(itimes==1){
5494: if(mle>=1)
5495: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5496: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5497: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5498: }else{
5499: if(mle>=1)
5500: printf(" %.5e",matcov[jj][ll]);
5501: fprintf(ficlog," %.5e",matcov[jj][ll]);
5502: fprintf(ficres," %.5e",matcov[jj][ll]);
5503: }
5504: }else{
5505: if(itimes==1){
5506: if(mle>=1)
5507: printf(" Var(%s%1d%1d)",ca,i,j);
5508: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
5509: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
5510: }else{
5511: if(mle>=1)
5512: printf(" %.5e",matcov[jj][ll]);
5513: fprintf(ficlog," %.5e",matcov[jj][ll]);
5514: fprintf(ficres," %.5e",matcov[jj][ll]);
5515: }
5516: }
5517: }
5518: } /* end lk */
5519: } /* end lj */
5520: } /* end li */
5521: if(mle>=1)
5522: printf("\n");
5523: fprintf(ficlog,"\n");
5524: fprintf(ficres,"\n");
5525: numlinepar++;
5526: } /* end k*/
5527: } /*end j */
5528: } /* end i */
5529: } /* end itimes */
5530:
5531: fflush(ficlog);
5532: fflush(ficres);
5533:
5534: while((c=getc(ficpar))=='#' && c!= EOF){
5535: ungetc(c,ficpar);
5536: fgets(line, MAXLINE, ficpar);
5537: puts(line);
5538: fputs(line,ficparo);
5539: }
5540: ungetc(c,ficpar);
5541:
5542: estepm=0;
5543: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
5544: if (estepm==0 || estepm < stepm) estepm=stepm;
5545: if (fage <= 2) {
5546: bage = ageminpar;
5547: fage = agemaxpar;
5548: }
5549:
5550: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
5551: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
5552: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
5553:
5554: while((c=getc(ficpar))=='#' && c!= EOF){
5555: ungetc(c,ficpar);
5556: fgets(line, MAXLINE, ficpar);
5557: puts(line);
5558: fputs(line,ficparo);
5559: }
5560: ungetc(c,ficpar);
5561:
5562: 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);
5563: 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);
5564: 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);
5565: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
5566: 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);
5567:
5568: while((c=getc(ficpar))=='#' && c!= EOF){
5569: ungetc(c,ficpar);
5570: fgets(line, MAXLINE, ficpar);
5571: puts(line);
5572: fputs(line,ficparo);
5573: }
5574: ungetc(c,ficpar);
5575:
5576:
5577: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
5578: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
5579:
5580: fscanf(ficpar,"pop_based=%d\n",&popbased);
5581: fprintf(ficparo,"pop_based=%d\n",popbased);
5582: fprintf(ficres,"pop_based=%d\n",popbased);
5583:
5584: while((c=getc(ficpar))=='#' && c!= EOF){
5585: ungetc(c,ficpar);
5586: fgets(line, MAXLINE, ficpar);
5587: puts(line);
5588: fputs(line,ficparo);
5589: }
5590: ungetc(c,ficpar);
5591:
5592: 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);
5593: 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);
5594: 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);
5595: 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);
5596: 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);
5597: /* day and month of proj2 are not used but only year anproj2.*/
5598:
5599:
5600:
5601: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
5602: /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
5603:
5604: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
5605: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
5606:
5607: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
5608: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
5609: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
5610:
5611: /*------------ free_vector -------------*/
5612: /* chdir(path); */
5613:
5614: free_ivector(wav,1,imx);
5615: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
5616: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
5617: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
5618: free_lvector(num,1,n);
5619: free_vector(agedc,1,n);
5620: /*free_matrix(covar,0,NCOVMAX,1,n);*/
5621: /*free_matrix(covar,1,NCOVMAX,1,n);*/
5622: fclose(ficparo);
5623: fclose(ficres);
5624:
5625:
5626: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5627:
5628: strcpy(filerespl,"pl");
5629: strcat(filerespl,fileres);
5630: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5631: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
5632: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
5633: }
5634: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5635: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5636: pstamp(ficrespl);
5637: fprintf(ficrespl,"# Period (stable) prevalence \n");
5638: fprintf(ficrespl,"#Age ");
5639: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5640: fprintf(ficrespl,"\n");
5641:
5642: prlim=matrix(1,nlstate,1,nlstate);
5643:
5644: agebase=ageminpar;
5645: agelim=agemaxpar;
5646: ftolpl=1.e-10;
5647: i1=cptcoveff;
5648: if (cptcovn < 1){i1=1;}
5649:
5650: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5651: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5652: k=k+1;
5653: /*printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,Tcode[cptcode],codtab[cptcod][cptcov]);*/
5654: fprintf(ficrespl,"\n#******");
5655: printf("\n#******");
5656: fprintf(ficlog,"\n#******");
5657: for(j=1;j<=cptcoveff;j++) {
5658: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5659: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5660: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5661: }
5662: fprintf(ficrespl,"******\n");
5663: printf("******\n");
5664: fprintf(ficlog,"******\n");
5665:
5666: for (age=agebase; age<=agelim; age++){
5667: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5668: fprintf(ficrespl,"%.0f ",age );
5669: for(j=1;j<=cptcoveff;j++)
5670: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5671: for(i=1; i<=nlstate;i++)
5672: fprintf(ficrespl," %.5f", prlim[i][i]);
5673: fprintf(ficrespl,"\n");
5674: }
5675: }
5676: }
5677: fclose(ficrespl);
5678:
5679: /*------------- h Pij x at various ages ------------*/
5680:
5681: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5682: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5683: printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
5684: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
5685: }
5686: printf("Computing pij: result on file '%s' \n", filerespij);
5687: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5688:
5689: stepsize=(int) (stepm+YEARM-1)/YEARM;
5690: /*if (stepm<=24) stepsize=2;*/
5691:
5692: agelim=AGESUP;
5693: hstepm=stepsize*YEARM; /* Every year of age */
5694: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5695:
5696: /* hstepm=1; aff par mois*/
5697: pstamp(ficrespij);
5698: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5699: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5700: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5701: k=k+1;
5702: fprintf(ficrespij,"\n#****** ");
5703: for(j=1;j<=cptcoveff;j++)
5704: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5705: fprintf(ficrespij,"******\n");
5706:
5707: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5708: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5709: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5710:
5711: /* nhstepm=nhstepm*YEARM; aff par mois*/
5712:
5713: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5714: oldm=oldms;savm=savms;
5715: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5716: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5717: for(i=1; i<=nlstate;i++)
5718: for(j=1; j<=nlstate+ndeath;j++)
5719: fprintf(ficrespij," %1d-%1d",i,j);
5720: fprintf(ficrespij,"\n");
5721: for (h=0; h<=nhstepm; h++){
5722: fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
5723: for(i=1; i<=nlstate;i++)
5724: for(j=1; j<=nlstate+ndeath;j++)
5725: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5726: fprintf(ficrespij,"\n");
5727: }
5728: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5729: fprintf(ficrespij,"\n");
5730: }
5731: }
5732: }
5733:
5734: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
5735:
5736: fclose(ficrespij);
5737:
5738: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
5739: for(i=1;i<=AGESUP;i++)
5740: for(j=1;j<=NCOVMAX;j++)
5741: for(k=1;k<=NCOVMAX;k++)
5742: probs[i][j][k]=0.;
5743:
5744: /*---------- Forecasting ------------------*/
5745: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
5746: if(prevfcast==1){
5747: /* if(stepm ==1){*/
5748: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
5749: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
5750: /* } */
5751: /* else{ */
5752: /* erreur=108; */
5753: /* 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); */
5754: /* 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); */
5755: /* } */
5756: }
5757:
5758:
1.127 brouard 5759: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
5760:
5761: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5762: /* 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",\
5763: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
5764: */
1.126 brouard 5765:
1.127 brouard 5766: if (mobilav!=0) {
5767: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5768: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
5769: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5770: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5771: }
1.126 brouard 5772: }
5773:
5774:
1.127 brouard 5775: /*---------- Health expectancies, no variances ------------*/
5776:
1.126 brouard 5777: strcpy(filerese,"e");
5778: strcat(filerese,fileres);
5779: if((ficreseij=fopen(filerese,"w"))==NULL) {
5780: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
5781: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
5782: }
5783: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
5784: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.127 brouard 5785: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5786: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5787: k=k+1;
5788: fprintf(ficreseij,"\n#****** ");
5789: for(j=1;j<=cptcoveff;j++) {
5790: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5791: }
5792: fprintf(ficreseij,"******\n");
5793:
5794: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
5795: oldm=oldms;savm=savms;
5796: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
5797:
5798: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
5799: }
5800: }
5801: fclose(ficreseij);
5802:
5803:
5804: /*---------- Health expectancies and variances ------------*/
5805:
5806:
5807: strcpy(filerest,"t");
5808: strcat(filerest,fileres);
5809: if((ficrest=fopen(filerest,"w"))==NULL) {
5810: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
5811: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
5812: }
5813: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
5814: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
5815:
1.126 brouard 5816:
5817: strcpy(fileresstde,"stde");
5818: strcat(fileresstde,fileres);
5819: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
5820: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
5821: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
5822: }
5823: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
5824: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
5825:
5826: strcpy(filerescve,"cve");
5827: strcat(filerescve,fileres);
5828: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
5829: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
5830: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
5831: }
5832: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
5833: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
5834:
5835: strcpy(fileresv,"v");
5836: strcat(fileresv,fileres);
5837: if((ficresvij=fopen(fileresv,"w"))==NULL) {
5838: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
5839: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
5840: }
5841: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
5842: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
5843:
5844: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5845: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5846: k=k+1;
5847: fprintf(ficrest,"\n#****** ");
5848: for(j=1;j<=cptcoveff;j++)
5849: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5850: fprintf(ficrest,"******\n");
5851:
5852: fprintf(ficresstdeij,"\n#****** ");
5853: fprintf(ficrescveij,"\n#****** ");
5854: for(j=1;j<=cptcoveff;j++) {
5855: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5856: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5857: }
5858: fprintf(ficresstdeij,"******\n");
5859: fprintf(ficrescveij,"******\n");
5860:
5861: fprintf(ficresvij,"\n#****** ");
5862: for(j=1;j<=cptcoveff;j++)
5863: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5864: fprintf(ficresvij,"******\n");
5865:
5866: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
5867: oldm=oldms;savm=savms;
1.127 brouard 5868: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.126 brouard 5869:
5870: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
5871: pstamp(ficrest);
1.128 ! brouard 5872: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
! 5873: oldm=oldms;savm=savms;
! 5874: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n# (weighted average of eij where weights are ");
! 5875: if(vpopbased==1)
! 5876: fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
! 5877: else
! 5878: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
! 5879: fprintf(ficrest,"# Age e.. (std) ");
! 5880: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
! 5881: fprintf(ficrest,"\n");
1.126 brouard 5882:
1.128 ! brouard 5883: epj=vector(1,nlstate+1);
! 5884: for(age=bage; age <=fage ;age++){
! 5885: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
! 5886: if (vpopbased==1) {
! 5887: if(mobilav ==0){
! 5888: for(i=1; i<=nlstate;i++)
! 5889: prlim[i][i]=probs[(int)age][i][k];
! 5890: }else{ /* mobilav */
! 5891: for(i=1; i<=nlstate;i++)
! 5892: prlim[i][i]=mobaverage[(int)age][i][k];
! 5893: }
1.126 brouard 5894: }
5895:
1.128 ! brouard 5896: fprintf(ficrest," %4.0f",age);
! 5897: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
! 5898: for(i=1, epj[j]=0.;i <=nlstate;i++) {
! 5899: epj[j] += prlim[i][i]*eij[i][j][(int)age];
! 5900: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
! 5901: }
! 5902: epj[nlstate+1] +=epj[j];
1.126 brouard 5903: }
5904:
1.128 ! brouard 5905: for(i=1, vepp=0.;i <=nlstate;i++)
! 5906: for(j=1;j <=nlstate;j++)
! 5907: vepp += vareij[i][j][(int)age];
! 5908: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
! 5909: for(j=1;j <=nlstate;j++){
! 5910: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
! 5911: }
! 5912: fprintf(ficrest,"\n");
1.126 brouard 5913: }
5914: }
5915: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
5916: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
5917: free_vector(epj,1,nlstate+1);
5918: }
5919: }
5920: free_vector(weight,1,n);
5921: free_imatrix(Tvard,1,15,1,2);
5922: free_imatrix(s,1,maxwav+1,1,n);
5923: free_matrix(anint,1,maxwav,1,n);
5924: free_matrix(mint,1,maxwav,1,n);
5925: free_ivector(cod,1,n);
5926: free_ivector(tab,1,NCOVMAX);
5927: fclose(ficresstdeij);
5928: fclose(ficrescveij);
5929: fclose(ficresvij);
5930: fclose(ficrest);
5931: fclose(ficpar);
5932:
5933: /*------- Variance of period (stable) prevalence------*/
5934:
5935: strcpy(fileresvpl,"vpl");
5936: strcat(fileresvpl,fileres);
5937: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
5938: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
5939: exit(0);
5940: }
5941: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
5942:
5943: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5944: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5945: k=k+1;
5946: fprintf(ficresvpl,"\n#****** ");
5947: for(j=1;j<=cptcoveff;j++)
5948: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5949: fprintf(ficresvpl,"******\n");
5950:
5951: varpl=matrix(1,nlstate,(int) bage, (int) fage);
5952: oldm=oldms;savm=savms;
5953: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
5954: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
5955: }
5956: }
5957:
5958: fclose(ficresvpl);
5959:
5960: /*---------- End : free ----------------*/
5961: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5962: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
5963:
5964: } /* mle==-3 arrives here for freeing */
5965: free_matrix(prlim,1,nlstate,1,nlstate);
5966: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
5967: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
5968: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
5969: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
5970: free_matrix(covar,0,NCOVMAX,1,n);
5971: free_matrix(matcov,1,npar,1,npar);
5972: /*free_vector(delti,1,npar);*/
5973: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5974: free_matrix(agev,1,maxwav,1,imx);
5975: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5976:
5977: free_ivector(ncodemax,1,8);
5978: free_ivector(Tvar,1,15);
5979: free_ivector(Tprod,1,15);
5980: free_ivector(Tvaraff,1,15);
5981: free_ivector(Tage,1,15);
5982: free_ivector(Tcode,1,100);
5983:
5984: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
5985: free_imatrix(codtab,1,100,1,10);
5986: fflush(fichtm);
5987: fflush(ficgp);
5988:
5989:
5990: if((nberr >0) || (nbwarn>0)){
5991: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
5992: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
5993: }else{
5994: printf("End of Imach\n");
5995: fprintf(ficlog,"End of Imach\n");
5996: }
5997: printf("See log file on %s\n",filelog);
5998: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
5999: (void) gettimeofday(&end_time,&tzp);
6000: tm = *localtime(&end_time.tv_sec);
6001: tmg = *gmtime(&end_time.tv_sec);
6002: strcpy(strtend,asctime(&tm));
6003: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6004: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
6005: printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
6006:
6007: printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
6008: fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
6009: fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
6010: /* printf("Total time was %d uSec.\n", total_usecs);*/
6011: /* if(fileappend(fichtm,optionfilehtm)){ */
6012: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6013: fclose(fichtm);
6014: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6015: fclose(fichtmcov);
6016: fclose(ficgp);
6017: fclose(ficlog);
6018: /*------ End -----------*/
6019:
6020:
6021: printf("Before Current directory %s!\n",pathcd);
6022: if(chdir(pathcd) != 0)
6023: printf("Can't move to directory %s!\n",path);
6024: if(getcwd(pathcd,MAXLINE) > 0)
6025: printf("Current directory %s!\n",pathcd);
6026: /*strcat(plotcmd,CHARSEPARATOR);*/
6027: sprintf(plotcmd,"gnuplot");
6028: #ifndef UNIX
6029: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6030: #endif
6031: if(!stat(plotcmd,&info)){
6032: printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
6033: if(!stat(getenv("GNUPLOTBIN"),&info)){
6034: printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
6035: }else
6036: strcpy(pplotcmd,plotcmd);
6037: #ifdef UNIX
6038: strcpy(plotcmd,GNUPLOTPROGRAM);
6039: if(!stat(plotcmd,&info)){
6040: printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
6041: }else
6042: strcpy(pplotcmd,plotcmd);
6043: #endif
6044: }else
6045: strcpy(pplotcmd,plotcmd);
6046:
6047: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
6048: printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
6049:
6050: if((outcmd=system(plotcmd)) != 0){
6051: printf("\n Problem with gnuplot\n");
6052: }
6053: printf(" Wait...");
6054: while (z[0] != 'q') {
6055: /* chdir(path); */
6056: printf("\nType e to edit output files, g to graph again and q for exiting: ");
6057: scanf("%s",z);
6058: /* if (z[0] == 'c') system("./imach"); */
6059: if (z[0] == 'e') {
6060: printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
6061: system(optionfilehtm);
6062: }
6063: else if (z[0] == 'g') system(plotcmd);
6064: else if (z[0] == 'q') exit(0);
6065: }
6066: end:
6067: while (z[0] != 'q') {
6068: printf("\nType q for exiting: ");
6069: scanf("%s",z);
6070: }
6071: }
6072:
6073:
6074:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>