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