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