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