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