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