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