Annotation of imach/src/imach.c, revision 1.158
1.158 ! brouard 1: /* $Id: imach.c,v 1.157 2014/08/27 16:26:55 brouard Exp $
1.126 brouard 2: $State: Exp $
3: $Log: imach.c,v $
1.158 ! brouard 4: Revision 1.157 2014/08/27 16:26:55 brouard
! 5: Summary: Preparing windows Visual studio version
! 6: Author: Brouard
! 7:
! 8: In order to compile on Visual studio, time.h is now correct and time_t
! 9: and tm struct should be used. difftime should be used but sometimes I
! 10: just make the differences in raw time format (time(&now).
! 11: Trying to suppress #ifdef LINUX
! 12: Add xdg-open for __linux in order to open default browser.
! 13:
1.157 brouard 14: Revision 1.156 2014/08/25 20:10:10 brouard
15: *** empty log message ***
16:
1.156 brouard 17: Revision 1.155 2014/08/25 18:32:34 brouard
18: Summary: New compile, minor changes
19: Author: Brouard
20:
1.155 brouard 21: Revision 1.154 2014/06/20 17:32:08 brouard
22: Summary: Outputs now all graphs of convergence to period prevalence
23:
1.154 brouard 24: Revision 1.153 2014/06/20 16:45:46 brouard
25: Summary: If 3 live state, convergence to period prevalence on same graph
26: Author: Brouard
27:
1.153 brouard 28: Revision 1.152 2014/06/18 17:54:09 brouard
29: Summary: open browser, use gnuplot on same dir than imach if not found in the path
30:
1.152 brouard 31: Revision 1.151 2014/06/18 16:43:30 brouard
32: *** empty log message ***
33:
1.151 brouard 34: Revision 1.150 2014/06/18 16:42:35 brouard
35: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
36: Author: brouard
37:
1.150 brouard 38: Revision 1.149 2014/06/18 15:51:14 brouard
39: Summary: Some fixes in parameter files errors
40: Author: Nicolas Brouard
41:
1.149 brouard 42: Revision 1.148 2014/06/17 17:38:48 brouard
43: Summary: Nothing new
44: Author: Brouard
45:
46: Just a new packaging for OS/X version 0.98nS
47:
1.148 brouard 48: Revision 1.147 2014/06/16 10:33:11 brouard
49: *** empty log message ***
50:
1.147 brouard 51: Revision 1.146 2014/06/16 10:20:28 brouard
52: Summary: Merge
53: Author: Brouard
54:
55: Merge, before building revised version.
56:
1.146 brouard 57: Revision 1.145 2014/06/10 21:23:15 brouard
58: Summary: Debugging with valgrind
59: Author: Nicolas Brouard
60:
61: Lot of changes in order to output the results with some covariates
62: After the Edimburgh REVES conference 2014, it seems mandatory to
63: improve the code.
64: No more memory valgrind error but a lot has to be done in order to
65: continue the work of splitting the code into subroutines.
66: Also, decodemodel has been improved. Tricode is still not
67: optimal. nbcode should be improved. Documentation has been added in
68: the source code.
69:
1.144 brouard 70: Revision 1.143 2014/01/26 09:45:38 brouard
71: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
72:
73: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
74: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
75:
1.143 brouard 76: Revision 1.142 2014/01/26 03:57:36 brouard
77: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
78:
79: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
80:
1.142 brouard 81: Revision 1.141 2014/01/26 02:42:01 brouard
82: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
83:
1.141 brouard 84: Revision 1.140 2011/09/02 10:37:54 brouard
85: Summary: times.h is ok with mingw32 now.
86:
1.140 brouard 87: Revision 1.139 2010/06/14 07:50:17 brouard
88: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
89: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
90:
1.139 brouard 91: Revision 1.138 2010/04/30 18:19:40 brouard
92: *** empty log message ***
93:
1.138 brouard 94: Revision 1.137 2010/04/29 18:11:38 brouard
95: (Module): Checking covariates for more complex models
96: than V1+V2. A lot of change to be done. Unstable.
97:
1.137 brouard 98: Revision 1.136 2010/04/26 20:30:53 brouard
99: (Module): merging some libgsl code. Fixing computation
100: of likelione (using inter/intrapolation if mle = 0) in order to
101: get same likelihood as if mle=1.
102: Some cleaning of code and comments added.
103:
1.136 brouard 104: Revision 1.135 2009/10/29 15:33:14 brouard
105: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
106:
1.135 brouard 107: Revision 1.134 2009/10/29 13:18:53 brouard
108: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
109:
1.134 brouard 110: Revision 1.133 2009/07/06 10:21:25 brouard
111: just nforces
112:
1.133 brouard 113: Revision 1.132 2009/07/06 08:22:05 brouard
114: Many tings
115:
1.132 brouard 116: Revision 1.131 2009/06/20 16:22:47 brouard
117: Some dimensions resccaled
118:
1.131 brouard 119: Revision 1.130 2009/05/26 06:44:34 brouard
120: (Module): Max Covariate is now set to 20 instead of 8. A
121: lot of cleaning with variables initialized to 0. Trying to make
122: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
123:
1.130 brouard 124: Revision 1.129 2007/08/31 13:49:27 lievre
125: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
126:
1.129 lievre 127: Revision 1.128 2006/06/30 13:02:05 brouard
128: (Module): Clarifications on computing e.j
129:
1.128 brouard 130: Revision 1.127 2006/04/28 18:11:50 brouard
131: (Module): Yes the sum of survivors was wrong since
132: imach-114 because nhstepm was no more computed in the age
133: loop. Now we define nhstepma in the age loop.
134: (Module): In order to speed up (in case of numerous covariates) we
135: compute health expectancies (without variances) in a first step
136: and then all the health expectancies with variances or standard
137: deviation (needs data from the Hessian matrices) which slows the
138: computation.
139: In the future we should be able to stop the program is only health
140: expectancies and graph are needed without standard deviations.
141:
1.127 brouard 142: Revision 1.126 2006/04/28 17:23:28 brouard
143: (Module): Yes the sum of survivors was wrong since
144: imach-114 because nhstepm was no more computed in the age
145: loop. Now we define nhstepma in the age loop.
146: Version 0.98h
147:
1.126 brouard 148: Revision 1.125 2006/04/04 15:20:31 lievre
149: Errors in calculation of health expectancies. Age was not initialized.
150: Forecasting file added.
151:
152: Revision 1.124 2006/03/22 17:13:53 lievre
153: Parameters are printed with %lf instead of %f (more numbers after the comma).
154: The log-likelihood is printed in the log file
155:
156: Revision 1.123 2006/03/20 10:52:43 brouard
157: * imach.c (Module): <title> changed, corresponds to .htm file
158: name. <head> headers where missing.
159:
160: * imach.c (Module): Weights can have a decimal point as for
161: English (a comma might work with a correct LC_NUMERIC environment,
162: otherwise the weight is truncated).
163: Modification of warning when the covariates values are not 0 or
164: 1.
165: Version 0.98g
166:
167: Revision 1.122 2006/03/20 09:45:41 brouard
168: (Module): Weights can have a decimal point as for
169: English (a comma might work with a correct LC_NUMERIC environment,
170: otherwise the weight is truncated).
171: Modification of warning when the covariates values are not 0 or
172: 1.
173: Version 0.98g
174:
175: Revision 1.121 2006/03/16 17:45:01 lievre
176: * imach.c (Module): Comments concerning covariates added
177:
178: * imach.c (Module): refinements in the computation of lli if
179: status=-2 in order to have more reliable computation if stepm is
180: not 1 month. Version 0.98f
181:
182: Revision 1.120 2006/03/16 15:10:38 lievre
183: (Module): refinements in the computation of lli if
184: status=-2 in order to have more reliable computation if stepm is
185: not 1 month. Version 0.98f
186:
187: Revision 1.119 2006/03/15 17:42:26 brouard
188: (Module): Bug if status = -2, the loglikelihood was
189: computed as likelihood omitting the logarithm. Version O.98e
190:
191: Revision 1.118 2006/03/14 18:20:07 brouard
192: (Module): varevsij Comments added explaining the second
193: table of variances if popbased=1 .
194: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
195: (Module): Function pstamp added
196: (Module): Version 0.98d
197:
198: Revision 1.117 2006/03/14 17:16:22 brouard
199: (Module): varevsij Comments added explaining the second
200: table of variances if popbased=1 .
201: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
202: (Module): Function pstamp added
203: (Module): Version 0.98d
204:
205: Revision 1.116 2006/03/06 10:29:27 brouard
206: (Module): Variance-covariance wrong links and
207: varian-covariance of ej. is needed (Saito).
208:
209: Revision 1.115 2006/02/27 12:17:45 brouard
210: (Module): One freematrix added in mlikeli! 0.98c
211:
212: Revision 1.114 2006/02/26 12:57:58 brouard
213: (Module): Some improvements in processing parameter
214: filename with strsep.
215:
216: Revision 1.113 2006/02/24 14:20:24 brouard
217: (Module): Memory leaks checks with valgrind and:
218: datafile was not closed, some imatrix were not freed and on matrix
219: allocation too.
220:
221: Revision 1.112 2006/01/30 09:55:26 brouard
222: (Module): Back to gnuplot.exe instead of wgnuplot.exe
223:
224: Revision 1.111 2006/01/25 20:38:18 brouard
225: (Module): Lots of cleaning and bugs added (Gompertz)
226: (Module): Comments can be added in data file. Missing date values
227: can be a simple dot '.'.
228:
229: Revision 1.110 2006/01/25 00:51:50 brouard
230: (Module): Lots of cleaning and bugs added (Gompertz)
231:
232: Revision 1.109 2006/01/24 19:37:15 brouard
233: (Module): Comments (lines starting with a #) are allowed in data.
234:
235: Revision 1.108 2006/01/19 18:05:42 lievre
236: Gnuplot problem appeared...
237: To be fixed
238:
239: Revision 1.107 2006/01/19 16:20:37 brouard
240: Test existence of gnuplot in imach path
241:
242: Revision 1.106 2006/01/19 13:24:36 brouard
243: Some cleaning and links added in html output
244:
245: Revision 1.105 2006/01/05 20:23:19 lievre
246: *** empty log message ***
247:
248: Revision 1.104 2005/09/30 16:11:43 lievre
249: (Module): sump fixed, loop imx fixed, and simplifications.
250: (Module): If the status is missing at the last wave but we know
251: that the person is alive, then we can code his/her status as -2
252: (instead of missing=-1 in earlier versions) and his/her
253: contributions to the likelihood is 1 - Prob of dying from last
254: health status (= 1-p13= p11+p12 in the easiest case of somebody in
255: the healthy state at last known wave). Version is 0.98
256:
257: Revision 1.103 2005/09/30 15:54:49 lievre
258: (Module): sump fixed, loop imx fixed, and simplifications.
259:
260: Revision 1.102 2004/09/15 17:31:30 brouard
261: Add the possibility to read data file including tab characters.
262:
263: Revision 1.101 2004/09/15 10:38:38 brouard
264: Fix on curr_time
265:
266: Revision 1.100 2004/07/12 18:29:06 brouard
267: Add version for Mac OS X. Just define UNIX in Makefile
268:
269: Revision 1.99 2004/06/05 08:57:40 brouard
270: *** empty log message ***
271:
272: Revision 1.98 2004/05/16 15:05:56 brouard
273: New version 0.97 . First attempt to estimate force of mortality
274: directly from the data i.e. without the need of knowing the health
275: state at each age, but using a Gompertz model: log u =a + b*age .
276: This is the basic analysis of mortality and should be done before any
277: other analysis, in order to test if the mortality estimated from the
278: cross-longitudinal survey is different from the mortality estimated
279: from other sources like vital statistic data.
280:
281: The same imach parameter file can be used but the option for mle should be -3.
282:
1.133 brouard 283: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 284: former routines in order to include the new code within the former code.
285:
286: The output is very simple: only an estimate of the intercept and of
287: the slope with 95% confident intervals.
288:
289: Current limitations:
290: A) Even if you enter covariates, i.e. with the
291: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
292: B) There is no computation of Life Expectancy nor Life Table.
293:
294: Revision 1.97 2004/02/20 13:25:42 lievre
295: Version 0.96d. Population forecasting command line is (temporarily)
296: suppressed.
297:
298: Revision 1.96 2003/07/15 15:38:55 brouard
299: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
300: rewritten within the same printf. Workaround: many printfs.
301:
302: Revision 1.95 2003/07/08 07:54:34 brouard
303: * imach.c (Repository):
304: (Repository): Using imachwizard code to output a more meaningful covariance
305: matrix (cov(a12,c31) instead of numbers.
306:
307: Revision 1.94 2003/06/27 13:00:02 brouard
308: Just cleaning
309:
310: Revision 1.93 2003/06/25 16:33:55 brouard
311: (Module): On windows (cygwin) function asctime_r doesn't
312: exist so I changed back to asctime which exists.
313: (Module): Version 0.96b
314:
315: Revision 1.92 2003/06/25 16:30:45 brouard
316: (Module): On windows (cygwin) function asctime_r doesn't
317: exist so I changed back to asctime which exists.
318:
319: Revision 1.91 2003/06/25 15:30:29 brouard
320: * imach.c (Repository): Duplicated warning errors corrected.
321: (Repository): Elapsed time after each iteration is now output. It
322: helps to forecast when convergence will be reached. Elapsed time
323: is stamped in powell. We created a new html file for the graphs
324: concerning matrix of covariance. It has extension -cov.htm.
325:
326: Revision 1.90 2003/06/24 12:34:15 brouard
327: (Module): Some bugs corrected for windows. Also, when
328: mle=-1 a template is output in file "or"mypar.txt with the design
329: of the covariance matrix to be input.
330:
331: Revision 1.89 2003/06/24 12:30:52 brouard
332: (Module): Some bugs corrected for windows. Also, when
333: mle=-1 a template is output in file "or"mypar.txt with the design
334: of the covariance matrix to be input.
335:
336: Revision 1.88 2003/06/23 17:54:56 brouard
337: * 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.
338:
339: Revision 1.87 2003/06/18 12:26:01 brouard
340: Version 0.96
341:
342: Revision 1.86 2003/06/17 20:04:08 brouard
343: (Module): Change position of html and gnuplot routines and added
344: routine fileappend.
345:
346: Revision 1.85 2003/06/17 13:12:43 brouard
347: * imach.c (Repository): Check when date of death was earlier that
348: current date of interview. It may happen when the death was just
349: prior to the death. In this case, dh was negative and likelihood
350: was wrong (infinity). We still send an "Error" but patch by
351: assuming that the date of death was just one stepm after the
352: interview.
353: (Repository): Because some people have very long ID (first column)
354: we changed int to long in num[] and we added a new lvector for
355: memory allocation. But we also truncated to 8 characters (left
356: truncation)
357: (Repository): No more line truncation errors.
358:
359: Revision 1.84 2003/06/13 21:44:43 brouard
360: * imach.c (Repository): Replace "freqsummary" at a correct
361: place. It differs from routine "prevalence" which may be called
362: many times. Probs is memory consuming and must be used with
363: parcimony.
364: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
365:
366: Revision 1.83 2003/06/10 13:39:11 lievre
367: *** empty log message ***
368:
369: Revision 1.82 2003/06/05 15:57:20 brouard
370: Add log in imach.c and fullversion number is now printed.
371:
372: */
373: /*
374: Interpolated Markov Chain
375:
376: Short summary of the programme:
377:
378: This program computes Healthy Life Expectancies from
379: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
380: first survey ("cross") where individuals from different ages are
381: interviewed on their health status or degree of disability (in the
382: case of a health survey which is our main interest) -2- at least a
383: second wave of interviews ("longitudinal") which measure each change
384: (if any) in individual health status. Health expectancies are
385: computed from the time spent in each health state according to a
386: model. More health states you consider, more time is necessary to reach the
387: Maximum Likelihood of the parameters involved in the model. The
388: simplest model is the multinomial logistic model where pij is the
389: probability to be observed in state j at the second wave
390: conditional to be observed in state i at the first wave. Therefore
391: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
392: 'age' is age and 'sex' is a covariate. If you want to have a more
393: complex model than "constant and age", you should modify the program
394: where the markup *Covariates have to be included here again* invites
395: you to do it. More covariates you add, slower the
396: convergence.
397:
398: The advantage of this computer programme, compared to a simple
399: multinomial logistic model, is clear when the delay between waves is not
400: identical for each individual. Also, if a individual missed an
401: intermediate interview, the information is lost, but taken into
402: account using an interpolation or extrapolation.
403:
404: hPijx is the probability to be observed in state i at age x+h
405: conditional to the observed state i at age x. The delay 'h' can be
406: split into an exact number (nh*stepm) of unobserved intermediate
407: states. This elementary transition (by month, quarter,
408: semester or year) is modelled as a multinomial logistic. The hPx
409: matrix is simply the matrix product of nh*stepm elementary matrices
410: and the contribution of each individual to the likelihood is simply
411: hPijx.
412:
413: Also this programme outputs the covariance matrix of the parameters but also
414: of the life expectancies. It also computes the period (stable) prevalence.
415:
1.133 brouard 416: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
417: Institut national d'études démographiques, Paris.
1.126 brouard 418: This software have been partly granted by Euro-REVES, a concerted action
419: from the European Union.
420: It is copyrighted identically to a GNU software product, ie programme and
421: software can be distributed freely for non commercial use. Latest version
422: can be accessed at http://euroreves.ined.fr/imach .
423:
424: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
425: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
426:
427: **********************************************************************/
428: /*
429: main
430: read parameterfile
431: read datafile
432: concatwav
433: freqsummary
434: if (mle >= 1)
435: mlikeli
436: print results files
437: if mle==1
438: computes hessian
439: read end of parameter file: agemin, agemax, bage, fage, estepm
440: begin-prev-date,...
441: open gnuplot file
442: open html file
1.145 brouard 443: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
444: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
445: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
446: freexexit2 possible for memory heap.
447:
448: h Pij x | pij_nom ficrestpij
449: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
450: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
451: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
452:
453: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
454: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
455: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
456: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
457: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
458:
1.126 brouard 459: forecasting if prevfcast==1 prevforecast call prevalence()
460: health expectancies
461: Variance-covariance of DFLE
462: prevalence()
463: movingaverage()
464: varevsij()
465: if popbased==1 varevsij(,popbased)
466: total life expectancies
467: Variance of period (stable) prevalence
468: end
469: */
470:
471:
472:
473:
474: #include <math.h>
475: #include <stdio.h>
476: #include <stdlib.h>
477: #include <string.h>
478: #include <unistd.h>
479:
480: #include <limits.h>
481: #include <sys/types.h>
482: #include <sys/stat.h>
483: #include <errno.h>
484: extern int errno;
485:
1.157 brouard 486: /* #ifdef LINUX */
487: /* #include <time.h> */
488: /* #include "timeval.h" */
489: /* #else */
490: /* #include <sys/time.h> */
491: /* #endif */
492:
1.126 brouard 493: #include <time.h>
494:
1.136 brouard 495: #ifdef GSL
496: #include <gsl/gsl_errno.h>
497: #include <gsl/gsl_multimin.h>
498: #endif
499:
1.126 brouard 500: /* #include <libintl.h> */
501: /* #define _(String) gettext (String) */
502:
1.141 brouard 503: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 504:
505: #define GNUPLOTPROGRAM "gnuplot"
506: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
507: #define FILENAMELENGTH 132
508:
509: #define GLOCK_ERROR_NOPATH -1 /* empty path */
510: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
511:
1.144 brouard 512: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
513: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 514:
515: #define NINTERVMAX 8
1.144 brouard 516: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
517: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
518: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 519: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 520: #define MAXN 20000
1.144 brouard 521: #define YEARM 12. /**< Number of months per year */
1.126 brouard 522: #define AGESUP 130
523: #define AGEBASE 40
1.144 brouard 524: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.157 brouard 525: #ifdef _WIN32
526: #define DIRSEPARATOR '\\'
527: #define CHARSEPARATOR "\\"
528: #define ODIRSEPARATOR '/'
529: #else
1.126 brouard 530: #define DIRSEPARATOR '/'
531: #define CHARSEPARATOR "/"
532: #define ODIRSEPARATOR '\\'
533: #endif
534:
1.158 ! brouard 535: /* $Id: imach.c,v 1.157 2014/08/27 16:26:55 brouard Exp $ */
1.126 brouard 536: /* $State: Exp $ */
537:
1.157 brouard 538: char version[]="Imach version 0.98nX, August 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.158 ! brouard 539: char fullversion[]="$Revision: 1.157 $ $Date: 2014/08/27 16:26:55 $";
1.126 brouard 540: char strstart[80];
541: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 542: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 543: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 544: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
545: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
546: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
547: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
548: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
549: int cptcovprodnoage=0; /**< Number of covariate products without age */
550: int cptcoveff=0; /* Total number of covariates to vary for printing results */
551: int cptcov=0; /* Working variable */
1.126 brouard 552: int npar=NPARMAX;
553: int nlstate=2; /* Number of live states */
554: int ndeath=1; /* Number of dead states */
1.130 brouard 555: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 556: int popbased=0;
557:
558: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 559: int maxwav=0; /* Maxim number of waves */
560: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
561: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
562: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 563: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 564: int mle=1, weightopt=0;
1.126 brouard 565: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
566: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
567: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
568: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130 brouard 569: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 570: double **matprod2(); /* test */
1.126 brouard 571: double **oldm, **newm, **savm; /* Working pointers to matrices */
572: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 573: /*FILE *fic ; */ /* Used in readdata only */
574: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 575: FILE *ficlog, *ficrespow;
1.130 brouard 576: int globpr=0; /* Global variable for printing or not */
1.126 brouard 577: double fretone; /* Only one call to likelihood */
1.130 brouard 578: long ipmx=0; /* Number of contributions */
1.126 brouard 579: double sw; /* Sum of weights */
580: char filerespow[FILENAMELENGTH];
581: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
582: FILE *ficresilk;
583: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
584: FILE *ficresprobmorprev;
585: FILE *fichtm, *fichtmcov; /* Html File */
586: FILE *ficreseij;
587: char filerese[FILENAMELENGTH];
588: FILE *ficresstdeij;
589: char fileresstde[FILENAMELENGTH];
590: FILE *ficrescveij;
591: char filerescve[FILENAMELENGTH];
592: FILE *ficresvij;
593: char fileresv[FILENAMELENGTH];
594: FILE *ficresvpl;
595: char fileresvpl[FILENAMELENGTH];
596: char title[MAXLINE];
597: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
598: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
599: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
600: char command[FILENAMELENGTH];
601: int outcmd=0;
602:
603: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
604:
605: char filelog[FILENAMELENGTH]; /* Log file */
606: char filerest[FILENAMELENGTH];
607: char fileregp[FILENAMELENGTH];
608: char popfile[FILENAMELENGTH];
609:
610: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
611:
1.157 brouard 612: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
613: /* struct timezone tzp; */
614: /* extern int gettimeofday(); */
615: struct tm tml, *gmtime(), *localtime();
616:
617: extern time_t time();
618:
619: struct tm start_time, end_time, curr_time, last_time, forecast_time;
620: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
621: struct tm tm;
622:
1.126 brouard 623: char strcurr[80], strfor[80];
624:
625: char *endptr;
626: long lval;
627: double dval;
628:
629: #define NR_END 1
630: #define FREE_ARG char*
631: #define FTOL 1.0e-10
632:
633: #define NRANSI
634: #define ITMAX 200
635:
636: #define TOL 2.0e-4
637:
638: #define CGOLD 0.3819660
639: #define ZEPS 1.0e-10
640: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
641:
642: #define GOLD 1.618034
643: #define GLIMIT 100.0
644: #define TINY 1.0e-20
645:
646: static double maxarg1,maxarg2;
647: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
648: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
649:
650: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
651: #define rint(a) floor(a+0.5)
652:
653: static double sqrarg;
654: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
655: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
656: int agegomp= AGEGOMP;
657:
658: int imx;
659: int stepm=1;
660: /* Stepm, step in month: minimum step interpolation*/
661:
662: int estepm;
663: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
664:
665: int m,nb;
666: long *num;
667: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
668: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
669: double **pmmij, ***probs;
670: double *ageexmed,*agecens;
671: double dateintmean=0;
672:
673: double *weight;
674: int **s; /* Status */
1.141 brouard 675: double *agedc;
1.145 brouard 676: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 677: * covar=matrix(0,NCOVMAX,1,n);
678: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
679: double idx;
680: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 681: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 682: int **codtab; /**< codtab=imatrix(1,100,1,10); */
683: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 684: double *lsurv, *lpop, *tpop;
685:
1.143 brouard 686: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
687: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 688:
689: /**************** split *************************/
690: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
691: {
692: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
693: the name of the file (name), its extension only (ext) and its first part of the name (finame)
694: */
695: char *ss; /* pointer */
696: int l1, l2; /* length counters */
697:
698: l1 = strlen(path ); /* length of path */
699: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
700: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
701: if ( ss == NULL ) { /* no directory, so determine current directory */
702: strcpy( name, path ); /* we got the fullname name because no directory */
703: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
704: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
705: /* get current working directory */
706: /* extern char* getcwd ( char *buf , int len);*/
707: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
708: return( GLOCK_ERROR_GETCWD );
709: }
710: /* got dirc from getcwd*/
711: printf(" DIRC = %s \n",dirc);
712: } else { /* strip direcotry from path */
713: ss++; /* after this, the filename */
714: l2 = strlen( ss ); /* length of filename */
715: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
716: strcpy( name, ss ); /* save file name */
717: strncpy( dirc, path, l1 - l2 ); /* now the directory */
718: dirc[l1-l2] = 0; /* add zero */
719: printf(" DIRC2 = %s \n",dirc);
720: }
721: /* We add a separator at the end of dirc if not exists */
722: l1 = strlen( dirc ); /* length of directory */
723: if( dirc[l1-1] != DIRSEPARATOR ){
724: dirc[l1] = DIRSEPARATOR;
725: dirc[l1+1] = 0;
726: printf(" DIRC3 = %s \n",dirc);
727: }
728: ss = strrchr( name, '.' ); /* find last / */
729: if (ss >0){
730: ss++;
731: strcpy(ext,ss); /* save extension */
732: l1= strlen( name);
733: l2= strlen(ss)+1;
734: strncpy( finame, name, l1-l2);
735: finame[l1-l2]= 0;
736: }
737:
738: return( 0 ); /* we're done */
739: }
740:
741:
742: /******************************************/
743:
744: void replace_back_to_slash(char *s, char*t)
745: {
746: int i;
747: int lg=0;
748: i=0;
749: lg=strlen(t);
750: for(i=0; i<= lg; i++) {
751: (s[i] = t[i]);
752: if (t[i]== '\\') s[i]='/';
753: }
754: }
755:
1.132 brouard 756: char *trimbb(char *out, char *in)
1.137 brouard 757: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 758: char *s;
759: s=out;
760: while (*in != '\0'){
1.137 brouard 761: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 762: in++;
763: }
764: *out++ = *in++;
765: }
766: *out='\0';
767: return s;
768: }
769:
1.145 brouard 770: char *cutl(char *blocc, char *alocc, char *in, char occ)
771: {
772: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
773: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
774: gives blocc="abcdef2ghi" and alocc="j".
775: If occ is not found blocc is null and alocc is equal to in. Returns blocc
776: */
777: char *s, *t, *bl;
778: t=in;s=in;
779: while ((*in != occ) && (*in != '\0')){
780: *alocc++ = *in++;
781: }
782: if( *in == occ){
783: *(alocc)='\0';
784: s=++in;
785: }
786:
787: if (s == t) {/* occ not found */
788: *(alocc-(in-s))='\0';
789: in=s;
790: }
791: while ( *in != '\0'){
792: *blocc++ = *in++;
793: }
794:
795: *blocc='\0';
796: return t;
797: }
1.137 brouard 798: char *cutv(char *blocc, char *alocc, char *in, char occ)
799: {
800: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
801: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
802: gives blocc="abcdef2ghi" and alocc="j".
803: If occ is not found blocc is null and alocc is equal to in. Returns alocc
804: */
805: char *s, *t;
806: t=in;s=in;
807: while (*in != '\0'){
808: while( *in == occ){
809: *blocc++ = *in++;
810: s=in;
811: }
812: *blocc++ = *in++;
813: }
814: if (s == t) /* occ not found */
815: *(blocc-(in-s))='\0';
816: else
817: *(blocc-(in-s)-1)='\0';
818: in=s;
819: while ( *in != '\0'){
820: *alocc++ = *in++;
821: }
822:
823: *alocc='\0';
824: return s;
825: }
826:
1.126 brouard 827: int nbocc(char *s, char occ)
828: {
829: int i,j=0;
830: int lg=20;
831: i=0;
832: lg=strlen(s);
833: for(i=0; i<= lg; i++) {
834: if (s[i] == occ ) j++;
835: }
836: return j;
837: }
838:
1.137 brouard 839: /* void cutv(char *u,char *v, char*t, char occ) */
840: /* { */
841: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
842: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
843: /* gives u="abcdef2ghi" and v="j" *\/ */
844: /* int i,lg,j,p=0; */
845: /* i=0; */
846: /* lg=strlen(t); */
847: /* for(j=0; j<=lg-1; j++) { */
848: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
849: /* } */
1.126 brouard 850:
1.137 brouard 851: /* for(j=0; j<p; j++) { */
852: /* (u[j] = t[j]); */
853: /* } */
854: /* u[p]='\0'; */
1.126 brouard 855:
1.137 brouard 856: /* for(j=0; j<= lg; j++) { */
857: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
858: /* } */
859: /* } */
1.126 brouard 860:
861: /********************** nrerror ********************/
862:
863: void nrerror(char error_text[])
864: {
865: fprintf(stderr,"ERREUR ...\n");
866: fprintf(stderr,"%s\n",error_text);
867: exit(EXIT_FAILURE);
868: }
869: /*********************** vector *******************/
870: double *vector(int nl, int nh)
871: {
872: double *v;
873: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
874: if (!v) nrerror("allocation failure in vector");
875: return v-nl+NR_END;
876: }
877:
878: /************************ free vector ******************/
879: void free_vector(double*v, int nl, int nh)
880: {
881: free((FREE_ARG)(v+nl-NR_END));
882: }
883:
884: /************************ivector *******************************/
885: int *ivector(long nl,long nh)
886: {
887: int *v;
888: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
889: if (!v) nrerror("allocation failure in ivector");
890: return v-nl+NR_END;
891: }
892:
893: /******************free ivector **************************/
894: void free_ivector(int *v, long nl, long nh)
895: {
896: free((FREE_ARG)(v+nl-NR_END));
897: }
898:
899: /************************lvector *******************************/
900: long *lvector(long nl,long nh)
901: {
902: long *v;
903: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
904: if (!v) nrerror("allocation failure in ivector");
905: return v-nl+NR_END;
906: }
907:
908: /******************free lvector **************************/
909: void free_lvector(long *v, long nl, long nh)
910: {
911: free((FREE_ARG)(v+nl-NR_END));
912: }
913:
914: /******************* imatrix *******************************/
915: int **imatrix(long nrl, long nrh, long ncl, long nch)
916: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
917: {
918: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
919: int **m;
920:
921: /* allocate pointers to rows */
922: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
923: if (!m) nrerror("allocation failure 1 in matrix()");
924: m += NR_END;
925: m -= nrl;
926:
927:
928: /* allocate rows and set pointers to them */
929: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
930: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
931: m[nrl] += NR_END;
932: m[nrl] -= ncl;
933:
934: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
935:
936: /* return pointer to array of pointers to rows */
937: return m;
938: }
939:
940: /****************** free_imatrix *************************/
941: void free_imatrix(m,nrl,nrh,ncl,nch)
942: int **m;
943: long nch,ncl,nrh,nrl;
944: /* free an int matrix allocated by imatrix() */
945: {
946: free((FREE_ARG) (m[nrl]+ncl-NR_END));
947: free((FREE_ARG) (m+nrl-NR_END));
948: }
949:
950: /******************* matrix *******************************/
951: double **matrix(long nrl, long nrh, long ncl, long nch)
952: {
953: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
954: double **m;
955:
956: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
957: if (!m) nrerror("allocation failure 1 in matrix()");
958: m += NR_END;
959: m -= nrl;
960:
961: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
962: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
963: m[nrl] += NR_END;
964: m[nrl] -= ncl;
965:
966: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
967: return m;
1.145 brouard 968: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
969: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
970: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 971: */
972: }
973:
974: /*************************free matrix ************************/
975: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
976: {
977: free((FREE_ARG)(m[nrl]+ncl-NR_END));
978: free((FREE_ARG)(m+nrl-NR_END));
979: }
980:
981: /******************* ma3x *******************************/
982: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
983: {
984: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
985: double ***m;
986:
987: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
988: if (!m) nrerror("allocation failure 1 in matrix()");
989: m += NR_END;
990: m -= nrl;
991:
992: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
993: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
994: m[nrl] += NR_END;
995: m[nrl] -= ncl;
996:
997: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
998:
999: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1000: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1001: m[nrl][ncl] += NR_END;
1002: m[nrl][ncl] -= nll;
1003: for (j=ncl+1; j<=nch; j++)
1004: m[nrl][j]=m[nrl][j-1]+nlay;
1005:
1006: for (i=nrl+1; i<=nrh; i++) {
1007: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1008: for (j=ncl+1; j<=nch; j++)
1009: m[i][j]=m[i][j-1]+nlay;
1010: }
1011: return m;
1012: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1013: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1014: */
1015: }
1016:
1017: /*************************free ma3x ************************/
1018: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1019: {
1020: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1021: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1022: free((FREE_ARG)(m+nrl-NR_END));
1023: }
1024:
1025: /*************** function subdirf ***********/
1026: char *subdirf(char fileres[])
1027: {
1028: /* Caution optionfilefiname is hidden */
1029: strcpy(tmpout,optionfilefiname);
1030: strcat(tmpout,"/"); /* Add to the right */
1031: strcat(tmpout,fileres);
1032: return tmpout;
1033: }
1034:
1035: /*************** function subdirf2 ***********/
1036: char *subdirf2(char fileres[], char *preop)
1037: {
1038:
1039: /* Caution optionfilefiname is hidden */
1040: strcpy(tmpout,optionfilefiname);
1041: strcat(tmpout,"/");
1042: strcat(tmpout,preop);
1043: strcat(tmpout,fileres);
1044: return tmpout;
1045: }
1046:
1047: /*************** function subdirf3 ***********/
1048: char *subdirf3(char fileres[], char *preop, char *preop2)
1049: {
1050:
1051: /* Caution optionfilefiname is hidden */
1052: strcpy(tmpout,optionfilefiname);
1053: strcat(tmpout,"/");
1054: strcat(tmpout,preop);
1055: strcat(tmpout,preop2);
1056: strcat(tmpout,fileres);
1057: return tmpout;
1058: }
1059:
1060: /***************** f1dim *************************/
1061: extern int ncom;
1062: extern double *pcom,*xicom;
1063: extern double (*nrfunc)(double []);
1064:
1065: double f1dim(double x)
1066: {
1067: int j;
1068: double f;
1069: double *xt;
1070:
1071: xt=vector(1,ncom);
1072: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1073: f=(*nrfunc)(xt);
1074: free_vector(xt,1,ncom);
1075: return f;
1076: }
1077:
1078: /*****************brent *************************/
1079: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1080: {
1081: int iter;
1082: double a,b,d,etemp;
1083: double fu,fv,fw,fx;
1084: double ftemp;
1085: double p,q,r,tol1,tol2,u,v,w,x,xm;
1086: double e=0.0;
1087:
1088: a=(ax < cx ? ax : cx);
1089: b=(ax > cx ? ax : cx);
1090: x=w=v=bx;
1091: fw=fv=fx=(*f)(x);
1092: for (iter=1;iter<=ITMAX;iter++) {
1093: xm=0.5*(a+b);
1094: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1095: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1096: printf(".");fflush(stdout);
1097: fprintf(ficlog,".");fflush(ficlog);
1098: #ifdef DEBUG
1099: 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);
1100: 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);
1101: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1102: #endif
1103: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1104: *xmin=x;
1105: return fx;
1106: }
1107: ftemp=fu;
1108: if (fabs(e) > tol1) {
1109: r=(x-w)*(fx-fv);
1110: q=(x-v)*(fx-fw);
1111: p=(x-v)*q-(x-w)*r;
1112: q=2.0*(q-r);
1113: if (q > 0.0) p = -p;
1114: q=fabs(q);
1115: etemp=e;
1116: e=d;
1117: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1118: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1119: else {
1120: d=p/q;
1121: u=x+d;
1122: if (u-a < tol2 || b-u < tol2)
1123: d=SIGN(tol1,xm-x);
1124: }
1125: } else {
1126: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1127: }
1128: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1129: fu=(*f)(u);
1130: if (fu <= fx) {
1131: if (u >= x) a=x; else b=x;
1132: SHFT(v,w,x,u)
1133: SHFT(fv,fw,fx,fu)
1134: } else {
1135: if (u < x) a=u; else b=u;
1136: if (fu <= fw || w == x) {
1137: v=w;
1138: w=u;
1139: fv=fw;
1140: fw=fu;
1141: } else if (fu <= fv || v == x || v == w) {
1142: v=u;
1143: fv=fu;
1144: }
1145: }
1146: }
1147: nrerror("Too many iterations in brent");
1148: *xmin=x;
1149: return fx;
1150: }
1151:
1152: /****************** mnbrak ***********************/
1153:
1154: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1155: double (*func)(double))
1156: {
1157: double ulim,u,r,q, dum;
1158: double fu;
1159:
1160: *fa=(*func)(*ax);
1161: *fb=(*func)(*bx);
1162: if (*fb > *fa) {
1163: SHFT(dum,*ax,*bx,dum)
1164: SHFT(dum,*fb,*fa,dum)
1165: }
1166: *cx=(*bx)+GOLD*(*bx-*ax);
1167: *fc=(*func)(*cx);
1168: while (*fb > *fc) {
1169: r=(*bx-*ax)*(*fb-*fc);
1170: q=(*bx-*cx)*(*fb-*fa);
1171: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1172: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
1173: ulim=(*bx)+GLIMIT*(*cx-*bx);
1174: if ((*bx-u)*(u-*cx) > 0.0) {
1175: fu=(*func)(u);
1176: } else if ((*cx-u)*(u-ulim) > 0.0) {
1177: fu=(*func)(u);
1178: if (fu < *fc) {
1179: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1180: SHFT(*fb,*fc,fu,(*func)(u))
1181: }
1182: } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
1183: u=ulim;
1184: fu=(*func)(u);
1185: } else {
1186: u=(*cx)+GOLD*(*cx-*bx);
1187: fu=(*func)(u);
1188: }
1189: SHFT(*ax,*bx,*cx,u)
1190: SHFT(*fa,*fb,*fc,fu)
1191: }
1192: }
1193:
1194: /*************** linmin ************************/
1195:
1196: int ncom;
1197: double *pcom,*xicom;
1198: double (*nrfunc)(double []);
1199:
1200: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1201: {
1202: double brent(double ax, double bx, double cx,
1203: double (*f)(double), double tol, double *xmin);
1204: double f1dim(double x);
1205: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1206: double *fc, double (*func)(double));
1207: int j;
1208: double xx,xmin,bx,ax;
1209: double fx,fb,fa;
1210:
1211: ncom=n;
1212: pcom=vector(1,n);
1213: xicom=vector(1,n);
1214: nrfunc=func;
1215: for (j=1;j<=n;j++) {
1216: pcom[j]=p[j];
1217: xicom[j]=xi[j];
1218: }
1219: ax=0.0;
1220: xx=1.0;
1221: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
1222: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
1223: #ifdef DEBUG
1224: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1225: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1226: #endif
1227: for (j=1;j<=n;j++) {
1228: xi[j] *= xmin;
1229: p[j] += xi[j];
1230: }
1231: free_vector(xicom,1,n);
1232: free_vector(pcom,1,n);
1233: }
1234:
1235: char *asc_diff_time(long time_sec, char ascdiff[])
1236: {
1237: long sec_left, days, hours, minutes;
1238: days = (time_sec) / (60*60*24);
1239: sec_left = (time_sec) % (60*60*24);
1240: hours = (sec_left) / (60*60) ;
1241: sec_left = (sec_left) %(60*60);
1242: minutes = (sec_left) /60;
1243: sec_left = (sec_left) % (60);
1.141 brouard 1244: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1.126 brouard 1245: return ascdiff;
1246: }
1247:
1248: /*************** powell ************************/
1249: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1250: double (*func)(double []))
1251: {
1252: void linmin(double p[], double xi[], int n, double *fret,
1253: double (*func)(double []));
1254: int i,ibig,j;
1255: double del,t,*pt,*ptt,*xit;
1256: double fp,fptt;
1257: double *xits;
1258: int niterf, itmp;
1259:
1260: pt=vector(1,n);
1261: ptt=vector(1,n);
1262: xit=vector(1,n);
1263: xits=vector(1,n);
1264: *fret=(*func)(p);
1265: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1266: rcurr_time = time(NULL);
1.126 brouard 1267: for (*iter=1;;++(*iter)) {
1268: fp=(*fret);
1269: ibig=0;
1270: del=0.0;
1.157 brouard 1271: rlast_time=rcurr_time;
1272: /* (void) gettimeofday(&curr_time,&tzp); */
1273: rcurr_time = time(NULL);
1274: curr_time = *localtime(&rcurr_time);
1275: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1276: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1277: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1278: for (i=1;i<=n;i++) {
1279: printf(" %d %.12f",i, p[i]);
1280: fprintf(ficlog," %d %.12lf",i, p[i]);
1281: fprintf(ficrespow," %.12lf", p[i]);
1282: }
1283: printf("\n");
1284: fprintf(ficlog,"\n");
1285: fprintf(ficrespow,"\n");fflush(ficrespow);
1286: if(*iter <=3){
1.157 brouard 1287: tml = *localtime(&rcurr_time);
1288: strcpy(strcurr,asctime(&tml));
1.126 brouard 1289: /* asctime_r(&tm,strcurr); */
1.157 brouard 1290: rforecast_time=rcurr_time;
1.126 brouard 1291: itmp = strlen(strcurr);
1292: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1293: strcurr[itmp-1]='\0';
1.157 brouard 1294: printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1295: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1296: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1297: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1298: forecast_time = *localtime(&rforecast_time);
1.126 brouard 1299: /* asctime_r(&tmf,strfor); */
1.157 brouard 1300: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1301: itmp = strlen(strfor);
1302: if(strfor[itmp-1]=='\n')
1303: strfor[itmp-1]='\0';
1.157 brouard 1304: 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(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1305: 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(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126 brouard 1306: }
1307: }
1308: for (i=1;i<=n;i++) {
1309: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1310: fptt=(*fret);
1311: #ifdef DEBUG
1312: printf("fret=%lf \n",*fret);
1313: fprintf(ficlog,"fret=%lf \n",*fret);
1314: #endif
1315: printf("%d",i);fflush(stdout);
1316: fprintf(ficlog,"%d",i);fflush(ficlog);
1317: linmin(p,xit,n,fret,func);
1318: if (fabs(fptt-(*fret)) > del) {
1319: del=fabs(fptt-(*fret));
1320: ibig=i;
1321: }
1322: #ifdef DEBUG
1323: printf("%d %.12e",i,(*fret));
1324: fprintf(ficlog,"%d %.12e",i,(*fret));
1325: for (j=1;j<=n;j++) {
1326: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1327: printf(" x(%d)=%.12e",j,xit[j]);
1328: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1329: }
1330: for(j=1;j<=n;j++) {
1331: printf(" p=%.12e",p[j]);
1332: fprintf(ficlog," p=%.12e",p[j]);
1333: }
1334: printf("\n");
1335: fprintf(ficlog,"\n");
1336: #endif
1337: }
1338: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1339: #ifdef DEBUG
1340: int k[2],l;
1341: k[0]=1;
1342: k[1]=-1;
1343: printf("Max: %.12e",(*func)(p));
1344: fprintf(ficlog,"Max: %.12e",(*func)(p));
1345: for (j=1;j<=n;j++) {
1346: printf(" %.12e",p[j]);
1347: fprintf(ficlog," %.12e",p[j]);
1348: }
1349: printf("\n");
1350: fprintf(ficlog,"\n");
1351: for(l=0;l<=1;l++) {
1352: for (j=1;j<=n;j++) {
1353: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1354: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1355: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1356: }
1357: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1358: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1359: }
1360: #endif
1361:
1362:
1363: free_vector(xit,1,n);
1364: free_vector(xits,1,n);
1365: free_vector(ptt,1,n);
1366: free_vector(pt,1,n);
1367: return;
1368: }
1369: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1370: for (j=1;j<=n;j++) {
1371: ptt[j]=2.0*p[j]-pt[j];
1372: xit[j]=p[j]-pt[j];
1373: pt[j]=p[j];
1374: }
1375: fptt=(*func)(ptt);
1376: if (fptt < fp) {
1377: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
1378: if (t < 0.0) {
1379: linmin(p,xit,n,fret,func);
1380: for (j=1;j<=n;j++) {
1381: xi[j][ibig]=xi[j][n];
1382: xi[j][n]=xit[j];
1383: }
1384: #ifdef DEBUG
1385: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1386: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1387: for(j=1;j<=n;j++){
1388: printf(" %.12e",xit[j]);
1389: fprintf(ficlog," %.12e",xit[j]);
1390: }
1391: printf("\n");
1392: fprintf(ficlog,"\n");
1393: #endif
1394: }
1395: }
1396: }
1397: }
1398:
1399: /**** Prevalence limit (stable or period prevalence) ****************/
1400:
1401: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1402: {
1403: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1404: matrix by transitions matrix until convergence is reached */
1405:
1406: int i, ii,j,k;
1407: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1408: /* double **matprod2(); */ /* test */
1.131 brouard 1409: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1410: double **newm;
1411: double agefin, delaymax=50 ; /* Max number of years to converge */
1412:
1413: for (ii=1;ii<=nlstate+ndeath;ii++)
1414: for (j=1;j<=nlstate+ndeath;j++){
1415: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1416: }
1417:
1418: cov[1]=1.;
1419:
1420: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1421: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1422: newm=savm;
1423: /* Covariates have to be included here again */
1.138 brouard 1424: cov[2]=agefin;
1425:
1426: for (k=1; k<=cptcovn;k++) {
1427: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1428: /*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 1429: }
1.145 brouard 1430: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1431: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1432: /* 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 1433:
1434: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1435: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1436: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1437: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1438: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1439: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1440:
1.126 brouard 1441: savm=oldm;
1442: oldm=newm;
1443: maxmax=0.;
1444: for(j=1;j<=nlstate;j++){
1445: min=1.;
1446: max=0.;
1447: for(i=1; i<=nlstate; i++) {
1448: sumnew=0;
1449: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1450: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1451: /*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 1452: max=FMAX(max,prlim[i][j]);
1453: min=FMIN(min,prlim[i][j]);
1454: }
1455: maxmin=max-min;
1456: maxmax=FMAX(maxmax,maxmin);
1457: }
1458: if(maxmax < ftolpl){
1459: return prlim;
1460: }
1461: }
1462: }
1463:
1464: /*************** transition probabilities ***************/
1465:
1466: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1467: {
1.138 brouard 1468: /* According to parameters values stored in x and the covariate's values stored in cov,
1469: computes the probability to be observed in state j being in state i by appying the
1470: model to the ncovmodel covariates (including constant and age).
1471: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1472: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1473: ncth covariate in the global vector x is given by the formula:
1474: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1475: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1476: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1477: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1478: Outputs ps[i][j] the probability to be observed in j being in j according to
1479: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1480: */
1481: double s1, lnpijopii;
1.126 brouard 1482: /*double t34;*/
1483: int i,j,j1, nc, ii, jj;
1484:
1485: for(i=1; i<= nlstate; i++){
1486: for(j=1; j<i;j++){
1.138 brouard 1487: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1488: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1489: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1490: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1491: }
1.138 brouard 1492: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1493: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1494: }
1495: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1496: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1497: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1498: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1499: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1500: }
1.138 brouard 1501: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1502: }
1503: }
1504:
1505: for(i=1; i<= nlstate; i++){
1506: s1=0;
1.131 brouard 1507: for(j=1; j<i; j++){
1.138 brouard 1508: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1509: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1510: }
1511: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1512: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1513: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1514: }
1.138 brouard 1515: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1516: ps[i][i]=1./(s1+1.);
1.138 brouard 1517: /* Computing other pijs */
1.126 brouard 1518: for(j=1; j<i; j++)
1519: ps[i][j]= exp(ps[i][j])*ps[i][i];
1520: for(j=i+1; j<=nlstate+ndeath; j++)
1521: ps[i][j]= exp(ps[i][j])*ps[i][i];
1522: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1523: } /* end i */
1524:
1525: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1526: for(jj=1; jj<= nlstate+ndeath; jj++){
1527: ps[ii][jj]=0;
1528: ps[ii][ii]=1;
1529: }
1530: }
1531:
1.145 brouard 1532:
1533: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1534: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1535: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1536: /* } */
1537: /* printf("\n "); */
1538: /* } */
1539: /* printf("\n ");printf("%lf ",cov[2]);*/
1540: /*
1.126 brouard 1541: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1542: goto end;*/
1543: return ps;
1544: }
1545:
1546: /**************** Product of 2 matrices ******************/
1547:
1.145 brouard 1548: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1549: {
1550: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1551: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1552: /* in, b, out are matrice of pointers which should have been initialized
1553: before: only the contents of out is modified. The function returns
1554: a pointer to pointers identical to out */
1.145 brouard 1555: int i, j, k;
1.126 brouard 1556: for(i=nrl; i<= nrh; i++)
1.145 brouard 1557: for(k=ncolol; k<=ncoloh; k++){
1558: out[i][k]=0.;
1559: for(j=ncl; j<=nch; j++)
1560: out[i][k] +=in[i][j]*b[j][k];
1561: }
1.126 brouard 1562: return out;
1563: }
1564:
1565:
1566: /************* Higher Matrix Product ***************/
1567:
1568: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1569: {
1570: /* Computes the transition matrix starting at age 'age' over
1571: 'nhstepm*hstepm*stepm' months (i.e. until
1572: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1573: nhstepm*hstepm matrices.
1574: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1575: (typically every 2 years instead of every month which is too big
1576: for the memory).
1577: Model is determined by parameters x and covariates have to be
1578: included manually here.
1579:
1580: */
1581:
1582: int i, j, d, h, k;
1.131 brouard 1583: double **out, cov[NCOVMAX+1];
1.126 brouard 1584: double **newm;
1585:
1586: /* Hstepm could be zero and should return the unit matrix */
1587: for (i=1;i<=nlstate+ndeath;i++)
1588: for (j=1;j<=nlstate+ndeath;j++){
1589: oldm[i][j]=(i==j ? 1.0 : 0.0);
1590: po[i][j][0]=(i==j ? 1.0 : 0.0);
1591: }
1592: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1593: for(h=1; h <=nhstepm; h++){
1594: for(d=1; d <=hstepm; d++){
1595: newm=savm;
1596: /* Covariates have to be included here again */
1597: cov[1]=1.;
1598: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1599: for (k=1; k<=cptcovn;k++)
1600: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1601: for (k=1; k<=cptcovage;k++)
1602: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1603: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1604: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1605:
1606:
1607: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1608: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1609: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1610: pmij(pmmij,cov,ncovmodel,x,nlstate));
1611: savm=oldm;
1612: oldm=newm;
1613: }
1614: for(i=1; i<=nlstate+ndeath; i++)
1615: for(j=1;j<=nlstate+ndeath;j++) {
1616: po[i][j][h]=newm[i][j];
1.128 brouard 1617: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1618: }
1.128 brouard 1619: /*printf("h=%d ",h);*/
1.126 brouard 1620: } /* end h */
1.128 brouard 1621: /* printf("\n H=%d \n",h); */
1.126 brouard 1622: return po;
1623: }
1624:
1625:
1626: /*************** log-likelihood *************/
1627: double func( double *x)
1628: {
1629: int i, ii, j, k, mi, d, kk;
1.131 brouard 1630: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1631: double **out;
1632: double sw; /* Sum of weights */
1633: double lli; /* Individual log likelihood */
1634: int s1, s2;
1635: double bbh, survp;
1636: long ipmx;
1637: /*extern weight */
1638: /* We are differentiating ll according to initial status */
1639: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1640: /*for(i=1;i<imx;i++)
1641: printf(" %d\n",s[4][i]);
1642: */
1643: cov[1]=1.;
1644:
1645: for(k=1; k<=nlstate; k++) ll[k]=0.;
1646:
1647: if(mle==1){
1648: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1649: /* Computes the values of the ncovmodel covariates of the model
1650: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1651: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1652: to be observed in j being in i according to the model.
1653: */
1.145 brouard 1654: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1655: cov[2+k]=covar[Tvar[k]][i];
1656: }
1.137 brouard 1657: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1658: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1659: has been calculated etc */
1.126 brouard 1660: for(mi=1; mi<= wav[i]-1; mi++){
1661: for (ii=1;ii<=nlstate+ndeath;ii++)
1662: for (j=1;j<=nlstate+ndeath;j++){
1663: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1664: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1665: }
1666: for(d=0; d<dh[mi][i]; d++){
1667: newm=savm;
1668: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1669: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1670: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1671: }
1672: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1673: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1674: savm=oldm;
1675: oldm=newm;
1676: } /* end mult */
1677:
1678: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1679: /* But now since version 0.9 we anticipate for bias at large stepm.
1680: * If stepm is larger than one month (smallest stepm) and if the exact delay
1681: * (in months) between two waves is not a multiple of stepm, we rounded to
1682: * the nearest (and in case of equal distance, to the lowest) interval but now
1683: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1684: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1685: * probability in order to take into account the bias as a fraction of the way
1686: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1687: * -stepm/2 to stepm/2 .
1688: * For stepm=1 the results are the same as for previous versions of Imach.
1689: * For stepm > 1 the results are less biased than in previous versions.
1690: */
1691: s1=s[mw[mi][i]][i];
1692: s2=s[mw[mi+1][i]][i];
1693: bbh=(double)bh[mi][i]/(double)stepm;
1694: /* bias bh is positive if real duration
1695: * is higher than the multiple of stepm and negative otherwise.
1696: */
1697: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1698: if( s2 > nlstate){
1699: /* i.e. if s2 is a death state and if the date of death is known
1700: then the contribution to the likelihood is the probability to
1701: die between last step unit time and current step unit time,
1702: which is also equal to probability to die before dh
1703: minus probability to die before dh-stepm .
1704: In version up to 0.92 likelihood was computed
1705: as if date of death was unknown. Death was treated as any other
1706: health state: the date of the interview describes the actual state
1707: and not the date of a change in health state. The former idea was
1708: to consider that at each interview the state was recorded
1709: (healthy, disable or death) and IMaCh was corrected; but when we
1710: introduced the exact date of death then we should have modified
1711: the contribution of an exact death to the likelihood. This new
1712: contribution is smaller and very dependent of the step unit
1713: stepm. It is no more the probability to die between last interview
1714: and month of death but the probability to survive from last
1715: interview up to one month before death multiplied by the
1716: probability to die within a month. Thanks to Chris
1717: Jackson for correcting this bug. Former versions increased
1718: mortality artificially. The bad side is that we add another loop
1719: which slows down the processing. The difference can be up to 10%
1720: lower mortality.
1721: */
1722: lli=log(out[s1][s2] - savm[s1][s2]);
1723:
1724:
1725: } else if (s2==-2) {
1726: for (j=1,survp=0. ; j<=nlstate; j++)
1727: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1728: /*survp += out[s1][j]; */
1729: lli= log(survp);
1730: }
1731:
1732: else if (s2==-4) {
1733: for (j=3,survp=0. ; j<=nlstate; j++)
1734: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1735: lli= log(survp);
1736: }
1737:
1738: else if (s2==-5) {
1739: for (j=1,survp=0. ; j<=2; j++)
1740: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1741: lli= log(survp);
1742: }
1743:
1744: else{
1745: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1746: /* lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2]));*/ /* linear interpolation */
1747: }
1748: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1749: /*if(lli ==000.0)*/
1750: /*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); */
1751: ipmx +=1;
1752: sw += weight[i];
1753: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1754: } /* end of wave */
1755: } /* end of individual */
1756: } else if(mle==2){
1757: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1758: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1759: for(mi=1; mi<= wav[i]-1; mi++){
1760: for (ii=1;ii<=nlstate+ndeath;ii++)
1761: for (j=1;j<=nlstate+ndeath;j++){
1762: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1763: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1764: }
1765: for(d=0; d<=dh[mi][i]; d++){
1766: newm=savm;
1767: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1768: for (kk=1; kk<=cptcovage;kk++) {
1769: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1770: }
1771: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1772: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1773: savm=oldm;
1774: oldm=newm;
1775: } /* end mult */
1776:
1777: s1=s[mw[mi][i]][i];
1778: s2=s[mw[mi+1][i]][i];
1779: bbh=(double)bh[mi][i]/(double)stepm;
1780: 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 */
1781: ipmx +=1;
1782: sw += weight[i];
1783: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1784: } /* end of wave */
1785: } /* end of individual */
1786: } else if(mle==3){ /* exponential inter-extrapolation */
1787: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1788: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1789: for(mi=1; mi<= wav[i]-1; mi++){
1790: for (ii=1;ii<=nlstate+ndeath;ii++)
1791: for (j=1;j<=nlstate+ndeath;j++){
1792: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1793: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1794: }
1795: for(d=0; d<dh[mi][i]; d++){
1796: newm=savm;
1797: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1798: for (kk=1; kk<=cptcovage;kk++) {
1799: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1800: }
1801: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1802: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1803: savm=oldm;
1804: oldm=newm;
1805: } /* end mult */
1806:
1807: s1=s[mw[mi][i]][i];
1808: s2=s[mw[mi+1][i]][i];
1809: bbh=(double)bh[mi][i]/(double)stepm;
1810: 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 */
1811: ipmx +=1;
1812: sw += weight[i];
1813: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1814: } /* end of wave */
1815: } /* end of individual */
1816: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1817: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1818: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1819: for(mi=1; mi<= wav[i]-1; mi++){
1820: for (ii=1;ii<=nlstate+ndeath;ii++)
1821: for (j=1;j<=nlstate+ndeath;j++){
1822: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1823: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1824: }
1825: for(d=0; d<dh[mi][i]; d++){
1826: newm=savm;
1827: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1828: for (kk=1; kk<=cptcovage;kk++) {
1829: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1830: }
1831:
1832: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1833: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1834: savm=oldm;
1835: oldm=newm;
1836: } /* end mult */
1837:
1838: s1=s[mw[mi][i]][i];
1839: s2=s[mw[mi+1][i]][i];
1840: if( s2 > nlstate){
1841: lli=log(out[s1][s2] - savm[s1][s2]);
1842: }else{
1843: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1844: }
1845: ipmx +=1;
1846: sw += weight[i];
1847: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1848: /* 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]); */
1849: } /* end of wave */
1850: } /* end of individual */
1851: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1852: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1853: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1854: for(mi=1; mi<= wav[i]-1; mi++){
1855: for (ii=1;ii<=nlstate+ndeath;ii++)
1856: for (j=1;j<=nlstate+ndeath;j++){
1857: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1858: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1859: }
1860: for(d=0; d<dh[mi][i]; d++){
1861: newm=savm;
1862: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1863: for (kk=1; kk<=cptcovage;kk++) {
1864: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1865: }
1866:
1867: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1868: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1869: savm=oldm;
1870: oldm=newm;
1871: } /* end mult */
1872:
1873: s1=s[mw[mi][i]][i];
1874: s2=s[mw[mi+1][i]][i];
1875: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1876: ipmx +=1;
1877: sw += weight[i];
1878: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1879: /*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]);*/
1880: } /* end of wave */
1881: } /* end of individual */
1882: } /* End of if */
1883: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1884: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1885: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1886: return -l;
1887: }
1888:
1889: /*************** log-likelihood *************/
1890: double funcone( double *x)
1891: {
1892: /* Same as likeli but slower because of a lot of printf and if */
1893: int i, ii, j, k, mi, d, kk;
1.131 brouard 1894: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1895: double **out;
1896: double lli; /* Individual log likelihood */
1897: double llt;
1898: int s1, s2;
1899: double bbh, survp;
1900: /*extern weight */
1901: /* We are differentiating ll according to initial status */
1902: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1903: /*for(i=1;i<imx;i++)
1904: printf(" %d\n",s[4][i]);
1905: */
1906: cov[1]=1.;
1907:
1908: for(k=1; k<=nlstate; k++) ll[k]=0.;
1909:
1910: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1911: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1912: for(mi=1; mi<= wav[i]-1; mi++){
1913: for (ii=1;ii<=nlstate+ndeath;ii++)
1914: for (j=1;j<=nlstate+ndeath;j++){
1915: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1916: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1917: }
1918: for(d=0; d<dh[mi][i]; d++){
1919: newm=savm;
1920: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1921: for (kk=1; kk<=cptcovage;kk++) {
1922: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1923: }
1.145 brouard 1924: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 1925: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1926: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 1927: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
1928: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 1929: savm=oldm;
1930: oldm=newm;
1931: } /* end mult */
1932:
1933: s1=s[mw[mi][i]][i];
1934: s2=s[mw[mi+1][i]][i];
1935: bbh=(double)bh[mi][i]/(double)stepm;
1936: /* bias is positive if real duration
1937: * is higher than the multiple of stepm and negative otherwise.
1938: */
1939: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1940: lli=log(out[s1][s2] - savm[s1][s2]);
1941: } else if (s2==-2) {
1942: for (j=1,survp=0. ; j<=nlstate; j++)
1943: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1944: lli= log(survp);
1945: }else if (mle==1){
1946: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1947: } else if(mle==2){
1948: 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 */
1949: } else if(mle==3){ /* exponential inter-extrapolation */
1950: 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 */
1951: } else if (mle==4){ /* mle=4 no inter-extrapolation */
1952: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 1953: } else{ /* mle=0 back to 1 */
1954: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1955: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 1956: } /* End of if */
1957: ipmx +=1;
1958: sw += weight[i];
1959: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 1960: /*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 1961: if(globpr){
1.141 brouard 1962: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 1963: %11.6f %11.6f %11.6f ", \
1964: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1965: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
1966: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
1967: llt +=ll[k]*gipmx/gsw;
1968: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1969: }
1970: fprintf(ficresilk," %10.6f\n", -llt);
1971: }
1972: } /* end of wave */
1973: } /* end of individual */
1974: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1975: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1976: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1977: if(globpr==0){ /* First time we count the contributions and weights */
1978: gipmx=ipmx;
1979: gsw=sw;
1980: }
1981: return -l;
1982: }
1983:
1984:
1985: /*************** function likelione ***********/
1986: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
1987: {
1988: /* This routine should help understanding what is done with
1989: the selection of individuals/waves and
1990: to check the exact contribution to the likelihood.
1991: Plotting could be done.
1992: */
1993: int k;
1994:
1995: if(*globpri !=0){ /* Just counts and sums, no printings */
1996: strcpy(fileresilk,"ilk");
1997: strcat(fileresilk,fileres);
1998: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
1999: printf("Problem with resultfile: %s\n", fileresilk);
2000: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2001: }
2002: 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");
2003: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2004: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2005: for(k=1; k<=nlstate; k++)
2006: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2007: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2008: }
2009:
2010: *fretone=(*funcone)(p);
2011: if(*globpri !=0){
2012: fclose(ficresilk);
2013: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2014: fflush(fichtm);
2015: }
2016: return;
2017: }
2018:
2019:
2020: /*********** Maximum Likelihood Estimation ***************/
2021:
2022: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2023: {
2024: int i,j, iter;
2025: double **xi;
2026: double fret;
2027: double fretone; /* Only one call to likelihood */
2028: /* char filerespow[FILENAMELENGTH];*/
2029: xi=matrix(1,npar,1,npar);
2030: for (i=1;i<=npar;i++)
2031: for (j=1;j<=npar;j++)
2032: xi[i][j]=(i==j ? 1.0 : 0.0);
2033: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2034: strcpy(filerespow,"pow");
2035: strcat(filerespow,fileres);
2036: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2037: printf("Problem with resultfile: %s\n", filerespow);
2038: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2039: }
2040: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2041: for (i=1;i<=nlstate;i++)
2042: for(j=1;j<=nlstate+ndeath;j++)
2043: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2044: fprintf(ficrespow,"\n");
2045:
2046: powell(p,xi,npar,ftol,&iter,&fret,func);
2047:
2048: free_matrix(xi,1,npar,1,npar);
2049: fclose(ficrespow);
2050: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
2051: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2052: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2053:
2054: }
2055:
2056: /**** Computes Hessian and covariance matrix ***/
2057: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2058: {
2059: double **a,**y,*x,pd;
2060: double **hess;
2061: int i, j,jk;
2062: int *indx;
2063:
2064: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2065: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2066: void lubksb(double **a, int npar, int *indx, double b[]) ;
2067: void ludcmp(double **a, int npar, int *indx, double *d) ;
2068: double gompertz(double p[]);
2069: hess=matrix(1,npar,1,npar);
2070:
2071: printf("\nCalculation of the hessian matrix. Wait...\n");
2072: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2073: for (i=1;i<=npar;i++){
2074: printf("%d",i);fflush(stdout);
2075: fprintf(ficlog,"%d",i);fflush(ficlog);
2076:
2077: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2078:
2079: /* printf(" %f ",p[i]);
2080: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2081: }
2082:
2083: for (i=1;i<=npar;i++) {
2084: for (j=1;j<=npar;j++) {
2085: if (j>i) {
2086: printf(".%d%d",i,j);fflush(stdout);
2087: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2088: hess[i][j]=hessij(p,delti,i,j,func,npar);
2089:
2090: hess[j][i]=hess[i][j];
2091: /*printf(" %lf ",hess[i][j]);*/
2092: }
2093: }
2094: }
2095: printf("\n");
2096: fprintf(ficlog,"\n");
2097:
2098: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2099: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2100:
2101: a=matrix(1,npar,1,npar);
2102: y=matrix(1,npar,1,npar);
2103: x=vector(1,npar);
2104: indx=ivector(1,npar);
2105: for (i=1;i<=npar;i++)
2106: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2107: ludcmp(a,npar,indx,&pd);
2108:
2109: for (j=1;j<=npar;j++) {
2110: for (i=1;i<=npar;i++) x[i]=0;
2111: x[j]=1;
2112: lubksb(a,npar,indx,x);
2113: for (i=1;i<=npar;i++){
2114: matcov[i][j]=x[i];
2115: }
2116: }
2117:
2118: printf("\n#Hessian matrix#\n");
2119: fprintf(ficlog,"\n#Hessian matrix#\n");
2120: for (i=1;i<=npar;i++) {
2121: for (j=1;j<=npar;j++) {
2122: printf("%.3e ",hess[i][j]);
2123: fprintf(ficlog,"%.3e ",hess[i][j]);
2124: }
2125: printf("\n");
2126: fprintf(ficlog,"\n");
2127: }
2128:
2129: /* Recompute Inverse */
2130: for (i=1;i<=npar;i++)
2131: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2132: ludcmp(a,npar,indx,&pd);
2133:
2134: /* printf("\n#Hessian matrix recomputed#\n");
2135:
2136: for (j=1;j<=npar;j++) {
2137: for (i=1;i<=npar;i++) x[i]=0;
2138: x[j]=1;
2139: lubksb(a,npar,indx,x);
2140: for (i=1;i<=npar;i++){
2141: y[i][j]=x[i];
2142: printf("%.3e ",y[i][j]);
2143: fprintf(ficlog,"%.3e ",y[i][j]);
2144: }
2145: printf("\n");
2146: fprintf(ficlog,"\n");
2147: }
2148: */
2149:
2150: free_matrix(a,1,npar,1,npar);
2151: free_matrix(y,1,npar,1,npar);
2152: free_vector(x,1,npar);
2153: free_ivector(indx,1,npar);
2154: free_matrix(hess,1,npar,1,npar);
2155:
2156:
2157: }
2158:
2159: /*************** hessian matrix ****************/
2160: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2161: {
2162: int i;
2163: int l=1, lmax=20;
2164: double k1,k2;
1.132 brouard 2165: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2166: double res;
2167: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2168: double fx;
2169: int k=0,kmax=10;
2170: double l1;
2171:
2172: fx=func(x);
2173: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2174: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2175: l1=pow(10,l);
2176: delts=delt;
2177: for(k=1 ; k <kmax; k=k+1){
2178: delt = delta*(l1*k);
2179: p2[theta]=x[theta] +delt;
1.145 brouard 2180: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2181: p2[theta]=x[theta]-delt;
2182: k2=func(p2)-fx;
2183: /*res= (k1-2.0*fx+k2)/delt/delt; */
2184: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2185:
1.132 brouard 2186: #ifdef DEBUGHESS
1.126 brouard 2187: 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);
2188: 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);
2189: #endif
2190: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2191: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2192: k=kmax;
2193: }
2194: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2195: k=kmax; l=lmax*10.;
2196: }
2197: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2198: delts=delt;
2199: }
2200: }
2201: }
2202: delti[theta]=delts;
2203: return res;
2204:
2205: }
2206:
2207: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2208: {
2209: int i;
2210: int l=1, l1, lmax=20;
2211: double k1,k2,k3,k4,res,fx;
1.132 brouard 2212: double p2[MAXPARM+1];
1.126 brouard 2213: int k;
2214:
2215: fx=func(x);
2216: for (k=1; k<=2; k++) {
2217: for (i=1;i<=npar;i++) p2[i]=x[i];
2218: p2[thetai]=x[thetai]+delti[thetai]/k;
2219: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2220: k1=func(p2)-fx;
2221:
2222: p2[thetai]=x[thetai]+delti[thetai]/k;
2223: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2224: k2=func(p2)-fx;
2225:
2226: p2[thetai]=x[thetai]-delti[thetai]/k;
2227: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2228: k3=func(p2)-fx;
2229:
2230: p2[thetai]=x[thetai]-delti[thetai]/k;
2231: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2232: k4=func(p2)-fx;
2233: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2234: #ifdef DEBUG
2235: 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);
2236: 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);
2237: #endif
2238: }
2239: return res;
2240: }
2241:
2242: /************** Inverse of matrix **************/
2243: void ludcmp(double **a, int n, int *indx, double *d)
2244: {
2245: int i,imax,j,k;
2246: double big,dum,sum,temp;
2247: double *vv;
2248:
2249: vv=vector(1,n);
2250: *d=1.0;
2251: for (i=1;i<=n;i++) {
2252: big=0.0;
2253: for (j=1;j<=n;j++)
2254: if ((temp=fabs(a[i][j])) > big) big=temp;
2255: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2256: vv[i]=1.0/big;
2257: }
2258: for (j=1;j<=n;j++) {
2259: for (i=1;i<j;i++) {
2260: sum=a[i][j];
2261: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2262: a[i][j]=sum;
2263: }
2264: big=0.0;
2265: for (i=j;i<=n;i++) {
2266: sum=a[i][j];
2267: for (k=1;k<j;k++)
2268: sum -= a[i][k]*a[k][j];
2269: a[i][j]=sum;
2270: if ( (dum=vv[i]*fabs(sum)) >= big) {
2271: big=dum;
2272: imax=i;
2273: }
2274: }
2275: if (j != imax) {
2276: for (k=1;k<=n;k++) {
2277: dum=a[imax][k];
2278: a[imax][k]=a[j][k];
2279: a[j][k]=dum;
2280: }
2281: *d = -(*d);
2282: vv[imax]=vv[j];
2283: }
2284: indx[j]=imax;
2285: if (a[j][j] == 0.0) a[j][j]=TINY;
2286: if (j != n) {
2287: dum=1.0/(a[j][j]);
2288: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2289: }
2290: }
2291: free_vector(vv,1,n); /* Doesn't work */
2292: ;
2293: }
2294:
2295: void lubksb(double **a, int n, int *indx, double b[])
2296: {
2297: int i,ii=0,ip,j;
2298: double sum;
2299:
2300: for (i=1;i<=n;i++) {
2301: ip=indx[i];
2302: sum=b[ip];
2303: b[ip]=b[i];
2304: if (ii)
2305: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2306: else if (sum) ii=i;
2307: b[i]=sum;
2308: }
2309: for (i=n;i>=1;i--) {
2310: sum=b[i];
2311: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2312: b[i]=sum/a[i][i];
2313: }
2314: }
2315:
2316: void pstamp(FILE *fichier)
2317: {
2318: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2319: }
2320:
2321: /************ Frequencies ********************/
2322: 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[])
2323: { /* Some frequencies */
2324:
1.130 brouard 2325: int i, m, jk, k1,i1, j1, bool, z1,j;
1.126 brouard 2326: int first;
2327: double ***freq; /* Frequencies */
2328: double *pp, **prop;
2329: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2330: char fileresp[FILENAMELENGTH];
2331:
2332: pp=vector(1,nlstate);
2333: prop=matrix(1,nlstate,iagemin,iagemax+3);
2334: strcpy(fileresp,"p");
2335: strcat(fileresp,fileres);
2336: if((ficresp=fopen(fileresp,"w"))==NULL) {
2337: printf("Problem with prevalence resultfile: %s\n", fileresp);
2338: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2339: exit(0);
2340: }
2341: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2342: j1=0;
2343:
2344: j=cptcoveff;
2345: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2346:
2347: first=1;
2348:
1.145 brouard 2349: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2350: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2351: /* j1++;
2352: */
2353: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2354: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2355: scanf("%d", i);*/
2356: for (i=-5; i<=nlstate+ndeath; i++)
2357: for (jk=-5; jk<=nlstate+ndeath; jk++)
2358: for(m=iagemin; m <= iagemax+3; m++)
2359: freq[i][jk][m]=0;
1.143 brouard 2360:
2361: for (i=1; i<=nlstate; i++)
2362: for(m=iagemin; m <= iagemax+3; m++)
2363: prop[i][m]=0;
1.126 brouard 2364:
2365: dateintsum=0;
2366: k2cpt=0;
2367: for (i=1; i<=imx; i++) {
2368: bool=1;
1.144 brouard 2369: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2370: for (z1=1; z1<=cptcoveff; z1++)
2371: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2372: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2373: bool=0;
1.145 brouard 2374: /* 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",
2375: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2376: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2377: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2378: }
1.126 brouard 2379: }
1.144 brouard 2380:
1.126 brouard 2381: if (bool==1){
2382: for(m=firstpass; m<=lastpass; m++){
2383: k2=anint[m][i]+(mint[m][i]/12.);
2384: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2385: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2386: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2387: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2388: if (m<lastpass) {
2389: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2390: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2391: }
2392:
2393: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2394: dateintsum=dateintsum+k2;
2395: k2cpt++;
2396: }
2397: /*}*/
2398: }
2399: }
1.145 brouard 2400: } /* end i */
1.126 brouard 2401:
2402: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2403: pstamp(ficresp);
2404: if (cptcovn>0) {
2405: fprintf(ficresp, "\n#********** Variable ");
2406: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2407: fprintf(ficresp, "**********\n#");
1.143 brouard 2408: fprintf(ficlog, "\n#********** Variable ");
2409: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2410: fprintf(ficlog, "**********\n#");
1.126 brouard 2411: }
2412: for(i=1; i<=nlstate;i++)
2413: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2414: fprintf(ficresp, "\n");
2415:
2416: for(i=iagemin; i <= iagemax+3; i++){
2417: if(i==iagemax+3){
2418: fprintf(ficlog,"Total");
2419: }else{
2420: if(first==1){
2421: first=0;
2422: printf("See log file for details...\n");
2423: }
2424: fprintf(ficlog,"Age %d", i);
2425: }
2426: for(jk=1; jk <=nlstate ; jk++){
2427: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2428: pp[jk] += freq[jk][m][i];
2429: }
2430: for(jk=1; jk <=nlstate ; jk++){
2431: for(m=-1, pos=0; m <=0 ; m++)
2432: pos += freq[jk][m][i];
2433: if(pp[jk]>=1.e-10){
2434: if(first==1){
1.132 brouard 2435: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2436: }
2437: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2438: }else{
2439: if(first==1)
2440: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2441: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2442: }
2443: }
2444:
2445: for(jk=1; jk <=nlstate ; jk++){
2446: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2447: pp[jk] += freq[jk][m][i];
2448: }
2449: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2450: pos += pp[jk];
2451: posprop += prop[jk][i];
2452: }
2453: for(jk=1; jk <=nlstate ; jk++){
2454: if(pos>=1.e-5){
2455: if(first==1)
2456: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2457: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2458: }else{
2459: if(first==1)
2460: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2461: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2462: }
2463: if( i <= iagemax){
2464: if(pos>=1.e-5){
2465: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2466: /*probs[i][jk][j1]= pp[jk]/pos;*/
2467: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2468: }
2469: else
2470: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2471: }
2472: }
2473:
2474: for(jk=-1; jk <=nlstate+ndeath; jk++)
2475: for(m=-1; m <=nlstate+ndeath; m++)
2476: if(freq[jk][m][i] !=0 ) {
2477: if(first==1)
2478: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2479: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2480: }
2481: if(i <= iagemax)
2482: fprintf(ficresp,"\n");
2483: if(first==1)
2484: printf("Others in log...\n");
2485: fprintf(ficlog,"\n");
2486: }
1.145 brouard 2487: /*}*/
1.126 brouard 2488: }
2489: dateintmean=dateintsum/k2cpt;
2490:
2491: fclose(ficresp);
2492: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2493: free_vector(pp,1,nlstate);
2494: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2495: /* End of Freq */
2496: }
2497:
2498: /************ Prevalence ********************/
2499: 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)
2500: {
2501: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2502: in each health status at the date of interview (if between dateprev1 and dateprev2).
2503: We still use firstpass and lastpass as another selection.
2504: */
2505:
1.130 brouard 2506: int i, m, jk, k1, i1, j1, bool, z1,j;
1.126 brouard 2507: double ***freq; /* Frequencies */
2508: double *pp, **prop;
2509: double pos,posprop;
2510: double y2; /* in fractional years */
2511: int iagemin, iagemax;
1.145 brouard 2512: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2513:
2514: iagemin= (int) agemin;
2515: iagemax= (int) agemax;
2516: /*pp=vector(1,nlstate);*/
2517: prop=matrix(1,nlstate,iagemin,iagemax+3);
2518: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2519: j1=0;
2520:
1.145 brouard 2521: /*j=cptcoveff;*/
1.126 brouard 2522: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2523:
1.145 brouard 2524: first=1;
2525: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2526: /*for(i1=1; i1<=ncodemax[k1];i1++){
2527: j1++;*/
1.126 brouard 2528:
2529: for (i=1; i<=nlstate; i++)
2530: for(m=iagemin; m <= iagemax+3; m++)
2531: prop[i][m]=0.0;
2532:
2533: for (i=1; i<=imx; i++) { /* Each individual */
2534: bool=1;
2535: if (cptcovn>0) {
2536: for (z1=1; z1<=cptcoveff; z1++)
2537: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2538: bool=0;
2539: }
2540: if (bool==1) {
2541: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2542: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2543: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2544: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2545: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2546: 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);
2547: if (s[m][i]>0 && s[m][i]<=nlstate) {
2548: /*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]]);*/
2549: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2550: prop[s[m][i]][iagemax+3] += weight[i];
2551: }
2552: }
2553: } /* end selection of waves */
2554: }
2555: }
2556: for(i=iagemin; i <= iagemax+3; i++){
2557: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2558: posprop += prop[jk][i];
2559: }
1.145 brouard 2560:
1.126 brouard 2561: for(jk=1; jk <=nlstate ; jk++){
2562: if( i <= iagemax){
2563: if(posprop>=1.e-5){
2564: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2565: } else{
2566: if(first==1){
2567: first=0;
2568: 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]);
2569: }
2570: }
1.126 brouard 2571: }
2572: }/* end jk */
2573: }/* end i */
1.145 brouard 2574: /*} *//* end i1 */
2575: } /* end j1 */
1.126 brouard 2576:
2577: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2578: /*free_vector(pp,1,nlstate);*/
2579: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2580: } /* End of prevalence */
2581:
2582: /************* Waves Concatenation ***************/
2583:
2584: 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)
2585: {
2586: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2587: Death is a valid wave (if date is known).
2588: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2589: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2590: and mw[mi+1][i]. dh depends on stepm.
2591: */
2592:
2593: int i, mi, m;
2594: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2595: double sum=0., jmean=0.;*/
2596: int first;
2597: int j, k=0,jk, ju, jl;
2598: double sum=0.;
2599: first=0;
2600: jmin=1e+5;
2601: jmax=-1;
2602: jmean=0.;
2603: for(i=1; i<=imx; i++){
2604: mi=0;
2605: m=firstpass;
2606: while(s[m][i] <= nlstate){
2607: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2608: mw[++mi][i]=m;
2609: if(m >=lastpass)
2610: break;
2611: else
2612: m++;
2613: }/* end while */
2614: if (s[m][i] > nlstate){
2615: mi++; /* Death is another wave */
2616: /* if(mi==0) never been interviewed correctly before death */
2617: /* Only death is a correct wave */
2618: mw[mi][i]=m;
2619: }
2620:
2621: wav[i]=mi;
2622: if(mi==0){
2623: nbwarn++;
2624: if(first==0){
2625: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2626: first=1;
2627: }
2628: if(first==1){
2629: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2630: }
2631: } /* end mi==0 */
2632: } /* End individuals */
2633:
2634: for(i=1; i<=imx; i++){
2635: for(mi=1; mi<wav[i];mi++){
2636: if (stepm <=0)
2637: dh[mi][i]=1;
2638: else{
2639: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2640: if (agedc[i] < 2*AGESUP) {
2641: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2642: if(j==0) j=1; /* Survives at least one month after exam */
2643: else if(j<0){
2644: nberr++;
2645: 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]);
2646: j=1; /* Temporary Dangerous patch */
2647: 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);
2648: 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]);
2649: 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);
2650: }
2651: k=k+1;
2652: if (j >= jmax){
2653: jmax=j;
2654: ijmax=i;
2655: }
2656: if (j <= jmin){
2657: jmin=j;
2658: ijmin=i;
2659: }
2660: sum=sum+j;
2661: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2662: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2663: }
2664: }
2665: else{
2666: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2667: /* 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]); */
2668:
2669: k=k+1;
2670: if (j >= jmax) {
2671: jmax=j;
2672: ijmax=i;
2673: }
2674: else if (j <= jmin){
2675: jmin=j;
2676: ijmin=i;
2677: }
2678: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2679: /*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]);*/
2680: if(j<0){
2681: nberr++;
2682: 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]);
2683: 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]);
2684: }
2685: sum=sum+j;
2686: }
2687: jk= j/stepm;
2688: jl= j -jk*stepm;
2689: ju= j -(jk+1)*stepm;
2690: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2691: if(jl==0){
2692: dh[mi][i]=jk;
2693: bh[mi][i]=0;
2694: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2695: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2696: dh[mi][i]=jk+1;
2697: bh[mi][i]=ju;
2698: }
2699: }else{
2700: if(jl <= -ju){
2701: dh[mi][i]=jk;
2702: bh[mi][i]=jl; /* bias is positive if real duration
2703: * is higher than the multiple of stepm and negative otherwise.
2704: */
2705: }
2706: else{
2707: dh[mi][i]=jk+1;
2708: bh[mi][i]=ju;
2709: }
2710: if(dh[mi][i]==0){
2711: dh[mi][i]=1; /* At least one step */
2712: bh[mi][i]=ju; /* At least one step */
2713: /* 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);*/
2714: }
2715: } /* end if mle */
2716: }
2717: } /* end wave */
2718: }
2719: jmean=sum/k;
2720: 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 2721: 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 2722: }
2723:
2724: /*********** Tricode ****************************/
1.145 brouard 2725: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2726: {
1.144 brouard 2727: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2728: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2729: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2730: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2731: /* nbcode[Tvar[j]][1]=
1.144 brouard 2732: */
1.130 brouard 2733:
1.145 brouard 2734: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2735: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2736: int cptcode=0; /* Modality max of covariates j */
2737: int modmincovj=0; /* Modality min of covariates j */
2738:
2739:
1.126 brouard 2740: cptcoveff=0;
2741:
1.145 brouard 2742: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2743: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2744:
1.145 brouard 2745: /* Loop on covariates without age and products */
2746: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2747: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2748: modality of this covariate Vj*/
1.145 brouard 2749: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2750: * If product of Vn*Vm, still boolean *:
2751: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2752: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2753: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2754: modality of the nth covariate of individual i. */
1.145 brouard 2755: if (ij > modmaxcovj)
2756: modmaxcovj=ij;
2757: else if (ij < modmincovj)
2758: modmincovj=ij;
2759: if ((ij < -1) && (ij > NCOVMAX)){
2760: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2761: exit(1);
2762: }else
1.136 brouard 2763: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2764: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2765: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2766: /* getting the maximum value of the modality of the covariate
2767: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2768: female is 1, then modmaxcovj=1.*/
1.126 brouard 2769: }
1.145 brouard 2770: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2771: cptcode=modmaxcovj;
1.137 brouard 2772: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2773: /*for (i=0; i<=cptcode; i++) {*/
2774: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2775: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2776: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2777: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2778: }
2779: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2780: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2781: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2782:
1.136 brouard 2783: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2784: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2785: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2786: modmincovj=3; modmaxcovj = 7;
2787: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2788: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2789: variables V1_1 and V1_2.
2790: nbcode[Tvar[j]][ij]=k;
2791: nbcode[Tvar[j]][1]=0;
2792: nbcode[Tvar[j]][2]=1;
2793: nbcode[Tvar[j]][3]=2;
2794: */
2795: ij=1; /* ij is similar to i but can jumps over null modalities */
2796: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2797: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2798: /*recode from 0 */
1.131 brouard 2799: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2800: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2801: k is a modality. If we have model=V1+V1*sex
2802: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2803: ij++;
2804: }
2805: if (ij > ncodemax[j]) break;
1.137 brouard 2806: } /* end of loop on */
2807: } /* end of loop on modality */
2808: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2809:
1.145 brouard 2810: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2811:
1.145 brouard 2812: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2813: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2814: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2815: Ndum[ij]++;
2816: }
1.126 brouard 2817:
2818: ij=1;
1.145 brouard 2819: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2820: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2821: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2822: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2823: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2824: ij++;
1.145 brouard 2825: }else
2826: Tvaraff[ij]=0;
1.126 brouard 2827: }
1.131 brouard 2828: ij--;
1.144 brouard 2829: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2830:
1.126 brouard 2831: }
2832:
1.145 brouard 2833:
1.126 brouard 2834: /*********** Health Expectancies ****************/
2835:
1.127 brouard 2836: 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 2837:
2838: {
2839: /* Health expectancies, no variances */
2840: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2841: int nhstepma, nstepma; /* Decreasing with age */
2842: double age, agelim, hf;
2843: double ***p3mat;
2844: double eip;
2845:
2846: pstamp(ficreseij);
2847: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2848: fprintf(ficreseij,"# Age");
2849: for(i=1; i<=nlstate;i++){
2850: for(j=1; j<=nlstate;j++){
2851: fprintf(ficreseij," e%1d%1d ",i,j);
2852: }
2853: fprintf(ficreseij," e%1d. ",i);
2854: }
2855: fprintf(ficreseij,"\n");
2856:
2857:
2858: if(estepm < stepm){
2859: printf ("Problem %d lower than %d\n",estepm, stepm);
2860: }
2861: else hstepm=estepm;
2862: /* We compute the life expectancy from trapezoids spaced every estepm months
2863: * This is mainly to measure the difference between two models: for example
2864: * if stepm=24 months pijx are given only every 2 years and by summing them
2865: * we are calculating an estimate of the Life Expectancy assuming a linear
2866: * progression in between and thus overestimating or underestimating according
2867: * to the curvature of the survival function. If, for the same date, we
2868: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2869: * to compare the new estimate of Life expectancy with the same linear
2870: * hypothesis. A more precise result, taking into account a more precise
2871: * curvature will be obtained if estepm is as small as stepm. */
2872:
2873: /* For example we decided to compute the life expectancy with the smallest unit */
2874: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2875: nhstepm is the number of hstepm from age to agelim
2876: nstepm is the number of stepm from age to agelin.
2877: Look at hpijx to understand the reason of that which relies in memory size
2878: and note for a fixed period like estepm months */
2879: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2880: survival function given by stepm (the optimization length). Unfortunately it
2881: means that if the survival funtion is printed only each two years of age and if
2882: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2883: results. So we changed our mind and took the option of the best precision.
2884: */
2885: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2886:
2887: agelim=AGESUP;
2888: /* If stepm=6 months */
2889: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2890: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2891:
2892: /* nhstepm age range expressed in number of stepm */
2893: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2894: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2895: /* if (stepm >= YEARM) hstepm=1;*/
2896: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2897: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2898:
2899: for (age=bage; age<=fage; age ++){
2900: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2901: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2902: /* if (stepm >= YEARM) hstepm=1;*/
2903: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2904:
2905: /* If stepm=6 months */
2906: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2907: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2908:
2909: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2910:
2911: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2912:
2913: printf("%d|",(int)age);fflush(stdout);
2914: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2915:
2916: /* Computing expectancies */
2917: for(i=1; i<=nlstate;i++)
2918: for(j=1; j<=nlstate;j++)
2919: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2920: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2921:
2922: /* 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]);*/
2923:
2924: }
2925:
2926: fprintf(ficreseij,"%3.0f",age );
2927: for(i=1; i<=nlstate;i++){
2928: eip=0;
2929: for(j=1; j<=nlstate;j++){
2930: eip +=eij[i][j][(int)age];
2931: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2932: }
2933: fprintf(ficreseij,"%9.4f", eip );
2934: }
2935: fprintf(ficreseij,"\n");
2936:
2937: }
2938: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2939: printf("\n");
2940: fprintf(ficlog,"\n");
2941:
2942: }
2943:
1.127 brouard 2944: 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 2945:
2946: {
2947: /* Covariances of health expectancies eij and of total life expectancies according
2948: to initial status i, ei. .
2949: */
2950: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
2951: int nhstepma, nstepma; /* Decreasing with age */
2952: double age, agelim, hf;
2953: double ***p3matp, ***p3matm, ***varhe;
2954: double **dnewm,**doldm;
2955: double *xp, *xm;
2956: double **gp, **gm;
2957: double ***gradg, ***trgradg;
2958: int theta;
2959:
2960: double eip, vip;
2961:
2962: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
2963: xp=vector(1,npar);
2964: xm=vector(1,npar);
2965: dnewm=matrix(1,nlstate*nlstate,1,npar);
2966: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
2967:
2968: pstamp(ficresstdeij);
2969: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
2970: fprintf(ficresstdeij,"# Age");
2971: for(i=1; i<=nlstate;i++){
2972: for(j=1; j<=nlstate;j++)
2973: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
2974: fprintf(ficresstdeij," e%1d. ",i);
2975: }
2976: fprintf(ficresstdeij,"\n");
2977:
2978: pstamp(ficrescveij);
2979: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
2980: fprintf(ficrescveij,"# Age");
2981: for(i=1; i<=nlstate;i++)
2982: for(j=1; j<=nlstate;j++){
2983: cptj= (j-1)*nlstate+i;
2984: for(i2=1; i2<=nlstate;i2++)
2985: for(j2=1; j2<=nlstate;j2++){
2986: cptj2= (j2-1)*nlstate+i2;
2987: if(cptj2 <= cptj)
2988: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
2989: }
2990: }
2991: fprintf(ficrescveij,"\n");
2992:
2993: if(estepm < stepm){
2994: printf ("Problem %d lower than %d\n",estepm, stepm);
2995: }
2996: else hstepm=estepm;
2997: /* We compute the life expectancy from trapezoids spaced every estepm months
2998: * This is mainly to measure the difference between two models: for example
2999: * if stepm=24 months pijx are given only every 2 years and by summing them
3000: * we are calculating an estimate of the Life Expectancy assuming a linear
3001: * progression in between and thus overestimating or underestimating according
3002: * to the curvature of the survival function. If, for the same date, we
3003: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3004: * to compare the new estimate of Life expectancy with the same linear
3005: * hypothesis. A more precise result, taking into account a more precise
3006: * curvature will be obtained if estepm is as small as stepm. */
3007:
3008: /* For example we decided to compute the life expectancy with the smallest unit */
3009: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3010: nhstepm is the number of hstepm from age to agelim
3011: nstepm is the number of stepm from age to agelin.
3012: Look at hpijx to understand the reason of that which relies in memory size
3013: and note for a fixed period like estepm months */
3014: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3015: survival function given by stepm (the optimization length). Unfortunately it
3016: means that if the survival funtion is printed only each two years of age and if
3017: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3018: results. So we changed our mind and took the option of the best precision.
3019: */
3020: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3021:
3022: /* If stepm=6 months */
3023: /* nhstepm age range expressed in number of stepm */
3024: agelim=AGESUP;
3025: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3026: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3027: /* if (stepm >= YEARM) hstepm=1;*/
3028: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3029:
3030: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3031: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3032: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3033: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3034: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3035: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3036:
3037: for (age=bage; age<=fage; age ++){
3038: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3039: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3040: /* if (stepm >= YEARM) hstepm=1;*/
3041: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3042:
3043: /* If stepm=6 months */
3044: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3045: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3046:
3047: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3048:
3049: /* Computing Variances of health expectancies */
3050: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3051: decrease memory allocation */
3052: for(theta=1; theta <=npar; theta++){
3053: for(i=1; i<=npar; i++){
3054: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3055: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3056: }
3057: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3058: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3059:
3060: for(j=1; j<= nlstate; j++){
3061: for(i=1; i<=nlstate; i++){
3062: for(h=0; h<=nhstepm-1; h++){
3063: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3064: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3065: }
3066: }
3067: }
3068:
3069: for(ij=1; ij<= nlstate*nlstate; ij++)
3070: for(h=0; h<=nhstepm-1; h++){
3071: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3072: }
3073: }/* End theta */
3074:
3075:
3076: for(h=0; h<=nhstepm-1; h++)
3077: for(j=1; j<=nlstate*nlstate;j++)
3078: for(theta=1; theta <=npar; theta++)
3079: trgradg[h][j][theta]=gradg[h][theta][j];
3080:
3081:
3082: for(ij=1;ij<=nlstate*nlstate;ij++)
3083: for(ji=1;ji<=nlstate*nlstate;ji++)
3084: varhe[ij][ji][(int)age] =0.;
3085:
3086: printf("%d|",(int)age);fflush(stdout);
3087: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3088: for(h=0;h<=nhstepm-1;h++){
3089: for(k=0;k<=nhstepm-1;k++){
3090: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3091: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3092: for(ij=1;ij<=nlstate*nlstate;ij++)
3093: for(ji=1;ji<=nlstate*nlstate;ji++)
3094: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3095: }
3096: }
3097:
3098: /* Computing expectancies */
3099: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3100: for(i=1; i<=nlstate;i++)
3101: for(j=1; j<=nlstate;j++)
3102: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3103: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3104:
3105: /* 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]);*/
3106:
3107: }
3108:
3109: fprintf(ficresstdeij,"%3.0f",age );
3110: for(i=1; i<=nlstate;i++){
3111: eip=0.;
3112: vip=0.;
3113: for(j=1; j<=nlstate;j++){
3114: eip += eij[i][j][(int)age];
3115: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3116: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3117: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3118: }
3119: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3120: }
3121: fprintf(ficresstdeij,"\n");
3122:
3123: fprintf(ficrescveij,"%3.0f",age );
3124: for(i=1; i<=nlstate;i++)
3125: for(j=1; j<=nlstate;j++){
3126: cptj= (j-1)*nlstate+i;
3127: for(i2=1; i2<=nlstate;i2++)
3128: for(j2=1; j2<=nlstate;j2++){
3129: cptj2= (j2-1)*nlstate+i2;
3130: if(cptj2 <= cptj)
3131: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3132: }
3133: }
3134: fprintf(ficrescveij,"\n");
3135:
3136: }
3137: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3138: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3139: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3140: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3141: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3142: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3143: printf("\n");
3144: fprintf(ficlog,"\n");
3145:
3146: free_vector(xm,1,npar);
3147: free_vector(xp,1,npar);
3148: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3149: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3150: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3151: }
3152:
3153: /************ Variance ******************/
3154: 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[])
3155: {
3156: /* Variance of health expectancies */
3157: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3158: /* double **newm;*/
3159: double **dnewm,**doldm;
3160: double **dnewmp,**doldmp;
3161: int i, j, nhstepm, hstepm, h, nstepm ;
3162: int k, cptcode;
3163: double *xp;
3164: double **gp, **gm; /* for var eij */
3165: double ***gradg, ***trgradg; /*for var eij */
3166: double **gradgp, **trgradgp; /* for var p point j */
3167: double *gpp, *gmp; /* for var p point j */
3168: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3169: double ***p3mat;
3170: double age,agelim, hf;
3171: double ***mobaverage;
3172: int theta;
3173: char digit[4];
3174: char digitp[25];
3175:
3176: char fileresprobmorprev[FILENAMELENGTH];
3177:
3178: if(popbased==1){
3179: if(mobilav!=0)
3180: strcpy(digitp,"-populbased-mobilav-");
3181: else strcpy(digitp,"-populbased-nomobil-");
3182: }
3183: else
3184: strcpy(digitp,"-stablbased-");
3185:
3186: if (mobilav!=0) {
3187: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3188: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3189: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3190: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3191: }
3192: }
3193:
3194: strcpy(fileresprobmorprev,"prmorprev");
3195: sprintf(digit,"%-d",ij);
3196: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3197: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3198: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3199: strcat(fileresprobmorprev,fileres);
3200: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3201: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3202: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3203: }
3204: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3205:
3206: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3207: pstamp(ficresprobmorprev);
3208: 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);
3209: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3210: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3211: fprintf(ficresprobmorprev," p.%-d SE",j);
3212: for(i=1; i<=nlstate;i++)
3213: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3214: }
3215: fprintf(ficresprobmorprev,"\n");
3216: fprintf(ficgp,"\n# Routine varevsij");
3217: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3218: 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");
3219: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3220: /* } */
3221: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3222: pstamp(ficresvij);
3223: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3224: if(popbased==1)
1.128 brouard 3225: 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 3226: else
3227: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3228: fprintf(ficresvij,"# Age");
3229: for(i=1; i<=nlstate;i++)
3230: for(j=1; j<=nlstate;j++)
3231: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3232: fprintf(ficresvij,"\n");
3233:
3234: xp=vector(1,npar);
3235: dnewm=matrix(1,nlstate,1,npar);
3236: doldm=matrix(1,nlstate,1,nlstate);
3237: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3238: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3239:
3240: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3241: gpp=vector(nlstate+1,nlstate+ndeath);
3242: gmp=vector(nlstate+1,nlstate+ndeath);
3243: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3244:
3245: if(estepm < stepm){
3246: printf ("Problem %d lower than %d\n",estepm, stepm);
3247: }
3248: else hstepm=estepm;
3249: /* For example we decided to compute the life expectancy with the smallest unit */
3250: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3251: nhstepm is the number of hstepm from age to agelim
3252: nstepm is the number of stepm from age to agelin.
1.128 brouard 3253: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3254: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3255: survival function given by stepm (the optimization length). Unfortunately it
3256: means that if the survival funtion is printed every two years of age and if
3257: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3258: results. So we changed our mind and took the option of the best precision.
3259: */
3260: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3261: agelim = AGESUP;
3262: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3263: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3264: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3265: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3266: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3267: gp=matrix(0,nhstepm,1,nlstate);
3268: gm=matrix(0,nhstepm,1,nlstate);
3269:
3270:
3271: for(theta=1; theta <=npar; theta++){
3272: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3273: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3274: }
3275: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3276: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3277:
3278: if (popbased==1) {
3279: if(mobilav ==0){
3280: for(i=1; i<=nlstate;i++)
3281: prlim[i][i]=probs[(int)age][i][ij];
3282: }else{ /* mobilav */
3283: for(i=1; i<=nlstate;i++)
3284: prlim[i][i]=mobaverage[(int)age][i][ij];
3285: }
3286: }
3287:
3288: for(j=1; j<= nlstate; j++){
3289: for(h=0; h<=nhstepm; h++){
3290: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3291: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3292: }
3293: }
3294: /* This for computing probability of death (h=1 means
3295: computed over hstepm matrices product = hstepm*stepm months)
3296: as a weighted average of prlim.
3297: */
3298: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3299: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3300: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3301: }
3302: /* end probability of death */
3303:
3304: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3305: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3306: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3307: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3308:
3309: if (popbased==1) {
3310: if(mobilav ==0){
3311: for(i=1; i<=nlstate;i++)
3312: prlim[i][i]=probs[(int)age][i][ij];
3313: }else{ /* mobilav */
3314: for(i=1; i<=nlstate;i++)
3315: prlim[i][i]=mobaverage[(int)age][i][ij];
3316: }
3317: }
3318:
1.128 brouard 3319: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3320: for(h=0; h<=nhstepm; h++){
3321: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3322: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3323: }
3324: }
3325: /* This for computing probability of death (h=1 means
3326: computed over hstepm matrices product = hstepm*stepm months)
3327: as a weighted average of prlim.
3328: */
3329: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3330: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3331: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3332: }
3333: /* end probability of death */
3334:
3335: for(j=1; j<= nlstate; j++) /* vareij */
3336: for(h=0; h<=nhstepm; h++){
3337: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3338: }
3339:
3340: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3341: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3342: }
3343:
3344: } /* End theta */
3345:
3346: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3347:
3348: for(h=0; h<=nhstepm; h++) /* veij */
3349: for(j=1; j<=nlstate;j++)
3350: for(theta=1; theta <=npar; theta++)
3351: trgradg[h][j][theta]=gradg[h][theta][j];
3352:
3353: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3354: for(theta=1; theta <=npar; theta++)
3355: trgradgp[j][theta]=gradgp[theta][j];
3356:
3357:
3358: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3359: for(i=1;i<=nlstate;i++)
3360: for(j=1;j<=nlstate;j++)
3361: vareij[i][j][(int)age] =0.;
3362:
3363: for(h=0;h<=nhstepm;h++){
3364: for(k=0;k<=nhstepm;k++){
3365: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3366: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3367: for(i=1;i<=nlstate;i++)
3368: for(j=1;j<=nlstate;j++)
3369: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3370: }
3371: }
3372:
3373: /* pptj */
3374: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3375: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3376: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3377: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3378: varppt[j][i]=doldmp[j][i];
3379: /* end ppptj */
3380: /* x centered again */
3381: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3382: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3383:
3384: if (popbased==1) {
3385: if(mobilav ==0){
3386: for(i=1; i<=nlstate;i++)
3387: prlim[i][i]=probs[(int)age][i][ij];
3388: }else{ /* mobilav */
3389: for(i=1; i<=nlstate;i++)
3390: prlim[i][i]=mobaverage[(int)age][i][ij];
3391: }
3392: }
3393:
3394: /* This for computing probability of death (h=1 means
3395: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3396: as a weighted average of prlim.
3397: */
3398: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3399: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3400: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3401: }
3402: /* end probability of death */
3403:
3404: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3405: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3406: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3407: for(i=1; i<=nlstate;i++){
3408: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3409: }
3410: }
3411: fprintf(ficresprobmorprev,"\n");
3412:
3413: fprintf(ficresvij,"%.0f ",age );
3414: for(i=1; i<=nlstate;i++)
3415: for(j=1; j<=nlstate;j++){
3416: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3417: }
3418: fprintf(ficresvij,"\n");
3419: free_matrix(gp,0,nhstepm,1,nlstate);
3420: free_matrix(gm,0,nhstepm,1,nlstate);
3421: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3422: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3423: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3424: } /* End age */
3425: free_vector(gpp,nlstate+1,nlstate+ndeath);
3426: free_vector(gmp,nlstate+1,nlstate+ndeath);
3427: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3428: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3429: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3430: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3431: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3432: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3433: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3434: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3435: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3436: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3437: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3438: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3439: 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);
3440: /* 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);
3441: */
3442: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3443: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3444:
3445: free_vector(xp,1,npar);
3446: free_matrix(doldm,1,nlstate,1,nlstate);
3447: free_matrix(dnewm,1,nlstate,1,npar);
3448: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3449: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3450: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3451: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3452: fclose(ficresprobmorprev);
3453: fflush(ficgp);
3454: fflush(fichtm);
3455: } /* end varevsij */
3456:
3457: /************ Variance of prevlim ******************/
3458: 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[])
3459: {
3460: /* Variance of prevalence limit */
3461: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3462: double **newm;
3463: double **dnewm,**doldm;
3464: int i, j, nhstepm, hstepm;
3465: int k, cptcode;
3466: double *xp;
3467: double *gp, *gm;
3468: double **gradg, **trgradg;
3469: double age,agelim;
3470: int theta;
3471:
3472: pstamp(ficresvpl);
3473: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3474: fprintf(ficresvpl,"# Age");
3475: for(i=1; i<=nlstate;i++)
3476: fprintf(ficresvpl," %1d-%1d",i,i);
3477: fprintf(ficresvpl,"\n");
3478:
3479: xp=vector(1,npar);
3480: dnewm=matrix(1,nlstate,1,npar);
3481: doldm=matrix(1,nlstate,1,nlstate);
3482:
3483: hstepm=1*YEARM; /* Every year of age */
3484: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3485: agelim = AGESUP;
3486: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3487: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3488: if (stepm >= YEARM) hstepm=1;
3489: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3490: gradg=matrix(1,npar,1,nlstate);
3491: gp=vector(1,nlstate);
3492: gm=vector(1,nlstate);
3493:
3494: for(theta=1; theta <=npar; theta++){
3495: for(i=1; i<=npar; i++){ /* Computes gradient */
3496: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3497: }
3498: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3499: for(i=1;i<=nlstate;i++)
3500: gp[i] = prlim[i][i];
3501:
3502: for(i=1; i<=npar; i++) /* Computes gradient */
3503: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3504: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3505: for(i=1;i<=nlstate;i++)
3506: gm[i] = prlim[i][i];
3507:
3508: for(i=1;i<=nlstate;i++)
3509: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3510: } /* End theta */
3511:
3512: trgradg =matrix(1,nlstate,1,npar);
3513:
3514: for(j=1; j<=nlstate;j++)
3515: for(theta=1; theta <=npar; theta++)
3516: trgradg[j][theta]=gradg[theta][j];
3517:
3518: for(i=1;i<=nlstate;i++)
3519: varpl[i][(int)age] =0.;
3520: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3521: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3522: for(i=1;i<=nlstate;i++)
3523: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3524:
3525: fprintf(ficresvpl,"%.0f ",age );
3526: for(i=1; i<=nlstate;i++)
3527: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3528: fprintf(ficresvpl,"\n");
3529: free_vector(gp,1,nlstate);
3530: free_vector(gm,1,nlstate);
3531: free_matrix(gradg,1,npar,1,nlstate);
3532: free_matrix(trgradg,1,nlstate,1,npar);
3533: } /* End age */
3534:
3535: free_vector(xp,1,npar);
3536: free_matrix(doldm,1,nlstate,1,npar);
3537: free_matrix(dnewm,1,nlstate,1,nlstate);
3538:
3539: }
3540:
3541: /************ Variance of one-step probabilities ******************/
3542: 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[])
3543: {
3544: int i, j=0, i1, k1, l1, t, tj;
3545: int k2, l2, j1, z1;
3546: int k=0,l, cptcode;
1.145 brouard 3547: int first=1, first1, first2;
1.126 brouard 3548: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3549: double **dnewm,**doldm;
3550: double *xp;
3551: double *gp, *gm;
3552: double **gradg, **trgradg;
3553: double **mu;
1.145 brouard 3554: double age,agelim, cov[NCOVMAX+1];
1.126 brouard 3555: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3556: int theta;
3557: char fileresprob[FILENAMELENGTH];
3558: char fileresprobcov[FILENAMELENGTH];
3559: char fileresprobcor[FILENAMELENGTH];
3560: double ***varpij;
3561:
3562: strcpy(fileresprob,"prob");
3563: strcat(fileresprob,fileres);
3564: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3565: printf("Problem with resultfile: %s\n", fileresprob);
3566: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3567: }
3568: strcpy(fileresprobcov,"probcov");
3569: strcat(fileresprobcov,fileres);
3570: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3571: printf("Problem with resultfile: %s\n", fileresprobcov);
3572: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3573: }
3574: strcpy(fileresprobcor,"probcor");
3575: strcat(fileresprobcor,fileres);
3576: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3577: printf("Problem with resultfile: %s\n", fileresprobcor);
3578: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3579: }
3580: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3581: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3582: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3583: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3584: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3585: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3586: pstamp(ficresprob);
3587: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3588: fprintf(ficresprob,"# Age");
3589: pstamp(ficresprobcov);
3590: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3591: fprintf(ficresprobcov,"# Age");
3592: pstamp(ficresprobcor);
3593: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3594: fprintf(ficresprobcor,"# Age");
3595:
3596:
3597: for(i=1; i<=nlstate;i++)
3598: for(j=1; j<=(nlstate+ndeath);j++){
3599: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3600: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3601: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3602: }
3603: /* fprintf(ficresprob,"\n");
3604: fprintf(ficresprobcov,"\n");
3605: fprintf(ficresprobcor,"\n");
3606: */
1.131 brouard 3607: xp=vector(1,npar);
1.126 brouard 3608: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3609: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3610: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3611: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3612: first=1;
3613: fprintf(ficgp,"\n# Routine varprob");
3614: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3615: fprintf(fichtm,"\n");
3616:
3617: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3618: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3619: file %s<br>\n",optionfilehtmcov);
3620: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3621: and drawn. It helps understanding how is the covariance between two incidences.\
3622: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3623: 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. \
3624: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3625: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3626: standard deviations wide on each axis. <br>\
3627: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3628: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3629: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3630:
3631: cov[1]=1;
1.145 brouard 3632: /* tj=cptcoveff; */
3633: tj = (int) pow(2,cptcoveff);
1.126 brouard 3634: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3635: j1=0;
1.145 brouard 3636: for(j1=1; j1<=tj;j1++){
3637: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3638: /*j1++;*/
1.126 brouard 3639: if (cptcovn>0) {
3640: fprintf(ficresprob, "\n#********** Variable ");
3641: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3642: fprintf(ficresprob, "**********\n#\n");
3643: fprintf(ficresprobcov, "\n#********** Variable ");
3644: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3645: fprintf(ficresprobcov, "**********\n#\n");
3646:
3647: fprintf(ficgp, "\n#********** Variable ");
3648: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3649: fprintf(ficgp, "**********\n#\n");
3650:
3651:
3652: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3653: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3654: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3655:
3656: fprintf(ficresprobcor, "\n#********** Variable ");
3657: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3658: fprintf(ficresprobcor, "**********\n#");
3659: }
3660:
1.145 brouard 3661: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3662: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3663: gp=vector(1,(nlstate)*(nlstate+ndeath));
3664: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3665: for (age=bage; age<=fage; age ++){
3666: cov[2]=age;
3667: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3668: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3669: * 1 1 1 1 1
3670: * 2 2 1 1 1
3671: * 3 1 2 1 1
3672: */
3673: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3674: }
3675: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3676: for (k=1; k<=cptcovprod;k++)
3677: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3678:
3679:
3680: for(theta=1; theta <=npar; theta++){
3681: for(i=1; i<=npar; i++)
3682: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3683:
3684: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3685:
3686: k=0;
3687: for(i=1; i<= (nlstate); i++){
3688: for(j=1; j<=(nlstate+ndeath);j++){
3689: k=k+1;
3690: gp[k]=pmmij[i][j];
3691: }
3692: }
3693:
3694: for(i=1; i<=npar; i++)
3695: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3696:
3697: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3698: k=0;
3699: for(i=1; i<=(nlstate); i++){
3700: for(j=1; j<=(nlstate+ndeath);j++){
3701: k=k+1;
3702: gm[k]=pmmij[i][j];
3703: }
3704: }
3705:
3706: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3707: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3708: }
3709:
3710: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3711: for(theta=1; theta <=npar; theta++)
3712: trgradg[j][theta]=gradg[theta][j];
3713:
3714: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3715: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3716:
3717: pmij(pmmij,cov,ncovmodel,x,nlstate);
3718:
3719: k=0;
3720: for(i=1; i<=(nlstate); i++){
3721: for(j=1; j<=(nlstate+ndeath);j++){
3722: k=k+1;
3723: mu[k][(int) age]=pmmij[i][j];
3724: }
3725: }
3726: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3727: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3728: varpij[i][j][(int)age] = doldm[i][j];
3729:
3730: /*printf("\n%d ",(int)age);
3731: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3732: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3733: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3734: }*/
3735:
3736: fprintf(ficresprob,"\n%d ",(int)age);
3737: fprintf(ficresprobcov,"\n%d ",(int)age);
3738: fprintf(ficresprobcor,"\n%d ",(int)age);
3739:
3740: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3741: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3742: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3743: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3744: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3745: }
3746: i=0;
3747: for (k=1; k<=(nlstate);k++){
3748: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3749: i++;
1.126 brouard 3750: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3751: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3752: for (j=1; j<=i;j++){
1.145 brouard 3753: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3754: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3755: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3756: }
3757: }
3758: }/* end of loop for state */
3759: } /* end of loop for age */
1.145 brouard 3760: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3761: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3762: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3763: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3764:
1.126 brouard 3765: /* Confidence intervalle of pij */
3766: /*
1.131 brouard 3767: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3768: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3769: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3770: 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);
3771: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3772: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3773: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3774: */
3775:
3776: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3777: first1=1;first2=2;
1.126 brouard 3778: for (k2=1; k2<=(nlstate);k2++){
3779: for (l2=1; l2<=(nlstate+ndeath);l2++){
3780: if(l2==k2) continue;
3781: j=(k2-1)*(nlstate+ndeath)+l2;
3782: for (k1=1; k1<=(nlstate);k1++){
3783: for (l1=1; l1<=(nlstate+ndeath);l1++){
3784: if(l1==k1) continue;
3785: i=(k1-1)*(nlstate+ndeath)+l1;
3786: if(i<=j) continue;
3787: for (age=bage; age<=fage; age ++){
3788: if ((int)age %5==0){
3789: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3790: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3791: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3792: mu1=mu[i][(int) age]/stepm*YEARM ;
3793: mu2=mu[j][(int) age]/stepm*YEARM;
3794: c12=cv12/sqrt(v1*v2);
3795: /* Computing eigen value of matrix of covariance */
3796: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3797: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3798: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3799: if(first2==1){
3800: first1=0;
3801: 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);
3802: }
3803: 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);
3804: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3805: /* lc2=fabs(lc2); */
1.135 brouard 3806: }
3807:
1.126 brouard 3808: /* Eigen vectors */
3809: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3810: /*v21=sqrt(1.-v11*v11); *//* error */
3811: v21=(lc1-v1)/cv12*v11;
3812: v12=-v21;
3813: v22=v11;
3814: tnalp=v21/v11;
3815: if(first1==1){
3816: first1=0;
3817: 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);
3818: }
3819: 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);
3820: /*printf(fignu*/
3821: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3822: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3823: if(first==1){
3824: first=0;
3825: fprintf(ficgp,"\nset parametric;unset label");
3826: 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 3827: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3828: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3829: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3830: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3831: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3832: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3833: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3834: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3835: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3836: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3837: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3838: 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",\
3839: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3840: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3841: }else{
3842: first=0;
3843: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3844: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3845: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3846: 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",\
3847: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3848: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3849: }/* if first */
3850: } /* age mod 5 */
3851: } /* end loop age */
3852: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3853: first=1;
3854: } /*l12 */
3855: } /* k12 */
3856: } /*l1 */
3857: }/* k1 */
1.145 brouard 3858: /* } /* loop covariates */
1.126 brouard 3859: }
3860: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3861: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3862: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3863: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3864: free_vector(xp,1,npar);
3865: fclose(ficresprob);
3866: fclose(ficresprobcov);
3867: fclose(ficresprobcor);
3868: fflush(ficgp);
3869: fflush(fichtmcov);
3870: }
3871:
3872:
3873: /******************* Printing html file ***********/
3874: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3875: int lastpass, int stepm, int weightopt, char model[],\
3876: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3877: int popforecast, int estepm ,\
3878: double jprev1, double mprev1,double anprev1, \
3879: double jprev2, double mprev2,double anprev2){
3880: int jj1, k1, i1, cpt;
3881:
3882: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3883: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3884: </ul>");
3885: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3886: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3887: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3888: fprintf(fichtm,"\
3889: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3890: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3891: fprintf(fichtm,"\
3892: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3893: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3894: fprintf(fichtm,"\
1.128 brouard 3895: - (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 3896: <a href=\"%s\">%s</a> <br>\n",
3897: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3898: fprintf(fichtm,"\
3899: - Population projections by age and states: \
3900: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3901:
3902: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3903:
1.145 brouard 3904: m=pow(2,cptcoveff);
1.126 brouard 3905: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3906:
3907: jj1=0;
3908: for(k1=1; k1<=m;k1++){
3909: for(i1=1; i1<=ncodemax[k1];i1++){
3910: jj1++;
3911: if (cptcovn > 0) {
3912: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3913: for (cpt=1; cpt<=cptcoveff;cpt++)
3914: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3915: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3916: }
3917: /* Pij */
1.145 brouard 3918: 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> \
3919: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3920: /* Quasi-incidences */
3921: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 3922: 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> \
3923: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3924: /* Period (stable) prevalence in each health state */
1.154 brouard 3925: for(cpt=1; cpt<=nlstate;cpt++){
3926: 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> \
3927: <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 3928: }
3929: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 3930: 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> \
3931: <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 3932: }
3933: } /* end i1 */
3934: }/* End k1 */
3935: fprintf(fichtm,"</ul>");
3936:
3937:
3938: fprintf(fichtm,"\
3939: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3940: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3941:
3942: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3943: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3944: fprintf(fichtm,"\
3945: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3946: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
3947:
3948: fprintf(fichtm,"\
3949: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3950: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
3951: fprintf(fichtm,"\
3952: - 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): \
3953: <a href=\"%s\">%s</a> <br>\n</li>",
3954: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
3955: fprintf(fichtm,"\
3956: - (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): \
3957: <a href=\"%s\">%s</a> <br>\n</li>",
3958: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
3959: fprintf(fichtm,"\
1.128 brouard 3960: - 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 3961: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
3962: fprintf(fichtm,"\
1.128 brouard 3963: - 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",
3964: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 3965: fprintf(fichtm,"\
3966: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
3967: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
3968:
3969: /* if(popforecast==1) fprintf(fichtm,"\n */
3970: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
3971: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
3972: /* <br>",fileres,fileres,fileres,fileres); */
3973: /* else */
3974: /* 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); */
3975: fflush(fichtm);
3976: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
3977:
1.145 brouard 3978: m=pow(2,cptcoveff);
1.126 brouard 3979: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3980:
3981: jj1=0;
3982: for(k1=1; k1<=m;k1++){
3983: for(i1=1; i1<=ncodemax[k1];i1++){
3984: jj1++;
3985: if (cptcovn > 0) {
3986: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3987: for (cpt=1; cpt<=cptcoveff;cpt++)
3988: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3989: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3990: }
3991: for(cpt=1; cpt<=nlstate;cpt++) {
3992: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 3993: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
3994: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 3995: }
3996: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 3997: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
3998: true period expectancies (those weighted with period prevalences are also\
3999: drawn in addition to the population based expectancies computed using\
4000: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4001: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4002: } /* end i1 */
4003: }/* End k1 */
4004: fprintf(fichtm,"</ul>");
4005: fflush(fichtm);
4006: }
4007:
4008: /******************* Gnuplot file **************/
4009: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4010:
4011: char dirfileres[132],optfileres[132];
1.130 brouard 4012: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4013: int ng=0;
1.126 brouard 4014: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4015: /* printf("Problem with file %s",optionfilegnuplot); */
4016: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4017: /* } */
4018:
4019: /*#ifdef windows */
4020: fprintf(ficgp,"cd \"%s\" \n",pathc);
4021: /*#endif */
4022: m=pow(2,cptcoveff);
4023:
4024: strcpy(dirfileres,optionfilefiname);
4025: strcpy(optfileres,"vpl");
4026: /* 1eme*/
1.153 brouard 4027: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4028: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4029: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4030: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4031: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4032: fprintf(ficgp,"set xlabel \"Age\" \n\
4033: set ylabel \"Probability\" \n\
1.145 brouard 4034: set ter png small size 320, 240\n\
1.126 brouard 4035: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4036:
4037: for (i=1; i<= nlstate ; i ++) {
4038: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4039: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4040: }
1.145 brouard 4041: 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 4042: for (i=1; i<= nlstate ; i ++) {
4043: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4044: else fprintf(ficgp," \%%*lf (\%%*lf)");
4045: }
1.145 brouard 4046: 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 4047: for (i=1; i<= nlstate ; i ++) {
4048: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4049: else fprintf(ficgp," \%%*lf (\%%*lf)");
4050: }
1.145 brouard 4051: 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 4052: }
4053: }
4054: /*2 eme*/
1.153 brouard 4055: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4056: for (k1=1; k1<= m ; k1 ++) {
4057: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4058: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4059:
4060: for (i=1; i<= nlstate+1 ; i ++) {
4061: k=2*i;
4062: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4063: for (j=1; j<= nlstate+1 ; j ++) {
4064: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4065: else fprintf(ficgp," \%%*lf (\%%*lf)");
4066: }
4067: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4068: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4069: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4070: for (j=1; j<= nlstate+1 ; j ++) {
4071: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4072: else fprintf(ficgp," \%%*lf (\%%*lf)");
4073: }
1.145 brouard 4074: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4075: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4076: for (j=1; j<= nlstate+1 ; j ++) {
4077: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4078: else fprintf(ficgp," \%%*lf (\%%*lf)");
4079: }
1.145 brouard 4080: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4081: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4082: }
4083: }
4084:
4085: /*3eme*/
4086:
4087: for (k1=1; k1<= m ; k1 ++) {
4088: for (cpt=1; cpt<= nlstate ; cpt ++) {
4089: /* k=2+nlstate*(2*cpt-2); */
4090: k=2+(nlstate+1)*(cpt-1);
4091: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4092: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4093: 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);
4094: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4095: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4096: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4097: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4098: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4099: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4100:
4101: */
4102: for (i=1; i< nlstate ; i ++) {
4103: 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);
4104: /* 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);*/
4105:
4106: }
4107: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4108: }
4109: }
4110:
4111: /* CV preval stable (period) */
1.153 brouard 4112: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4113: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4114: k=3;
1.153 brouard 4115: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4116: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4117: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4118: set ter png small size 320, 240\n\
1.126 brouard 4119: unset log y\n\
1.153 brouard 4120: plot [%.f:%.f] ", ageminpar, agemaxpar);
4121: for (i=1; i<= nlstate ; i ++){
4122: if(i==1)
4123: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4124: else
4125: fprintf(ficgp,", '' ");
1.154 brouard 4126: l=(nlstate+ndeath)*(i-1)+1;
4127: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4128: for (j=1; j<= (nlstate-1) ; j ++)
4129: fprintf(ficgp,"+$%d",k+l+j);
4130: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4131: } /* nlstate */
4132: fprintf(ficgp,"\n");
4133: } /* end cpt state*/
4134: } /* end covariate */
1.126 brouard 4135:
4136: /* proba elementaires */
4137: for(i=1,jk=1; i <=nlstate; i++){
4138: for(k=1; k <=(nlstate+ndeath); k++){
4139: if (k != i) {
4140: for(j=1; j <=ncovmodel; j++){
4141: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4142: jk++;
4143: fprintf(ficgp,"\n");
4144: }
4145: }
4146: }
4147: }
1.145 brouard 4148: /*goto avoid;*/
1.126 brouard 4149: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4150: for(jk=1; jk <=m; jk++) {
1.145 brouard 4151: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4152: if (ng==2)
4153: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4154: else
4155: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4156: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4157: i=1;
4158: for(k2=1; k2<=nlstate; k2++) {
4159: k3=i;
4160: for(k=1; k<=(nlstate+ndeath); k++) {
4161: if (k != k2){
4162: if(ng==2)
4163: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4164: else
4165: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4166: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4167: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4168: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4169: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4170: /* ij++; */
4171: /* } */
4172: /* else */
1.126 brouard 4173: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4174: }
4175: fprintf(ficgp,")/(1");
4176:
4177: for(k1=1; k1 <=nlstate; k1++){
4178: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4179: ij=1;
4180: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4181: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4182: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4183: /* ij++; */
4184: /* } */
4185: /* else */
1.126 brouard 4186: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4187: }
4188: fprintf(ficgp,")");
4189: }
4190: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4191: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4192: i=i+ncovmodel;
4193: }
4194: } /* end k */
4195: } /* end k2 */
4196: } /* end jk */
4197: } /* end ng */
1.145 brouard 4198: avoid:
1.126 brouard 4199: fflush(ficgp);
4200: } /* end gnuplot */
4201:
4202:
4203: /*************** Moving average **************/
4204: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4205:
4206: int i, cpt, cptcod;
4207: int modcovmax =1;
4208: int mobilavrange, mob;
4209: double age;
4210:
4211: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4212: a covariate has 2 modalities */
4213: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4214:
4215: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4216: if(mobilav==1) mobilavrange=5; /* default */
4217: else mobilavrange=mobilav;
4218: for (age=bage; age<=fage; age++)
4219: for (i=1; i<=nlstate;i++)
4220: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4221: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4222: /* We keep the original values on the extreme ages bage, fage and for
4223: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4224: we use a 5 terms etc. until the borders are no more concerned.
4225: */
4226: for (mob=3;mob <=mobilavrange;mob=mob+2){
4227: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4228: for (i=1; i<=nlstate;i++){
4229: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4230: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4231: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4232: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4233: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4234: }
4235: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4236: }
4237: }
4238: }/* end age */
4239: }/* end mob */
4240: }else return -1;
4241: return 0;
4242: }/* End movingaverage */
4243:
4244:
4245: /************** Forecasting ******************/
4246: 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){
4247: /* proj1, year, month, day of starting projection
4248: agemin, agemax range of age
4249: dateprev1 dateprev2 range of dates during which prevalence is computed
4250: anproj2 year of en of projection (same day and month as proj1).
4251: */
4252: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4253: int *popage;
4254: double agec; /* generic age */
4255: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4256: double *popeffectif,*popcount;
4257: double ***p3mat;
4258: double ***mobaverage;
4259: char fileresf[FILENAMELENGTH];
4260:
4261: agelim=AGESUP;
4262: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4263:
4264: strcpy(fileresf,"f");
4265: strcat(fileresf,fileres);
4266: if((ficresf=fopen(fileresf,"w"))==NULL) {
4267: printf("Problem with forecast resultfile: %s\n", fileresf);
4268: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4269: }
4270: printf("Computing forecasting: result on file '%s' \n", fileresf);
4271: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4272:
4273: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4274:
4275: if (mobilav!=0) {
4276: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4277: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4278: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4279: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4280: }
4281: }
4282:
4283: stepsize=(int) (stepm+YEARM-1)/YEARM;
4284: if (stepm<=12) stepsize=1;
4285: if(estepm < stepm){
4286: printf ("Problem %d lower than %d\n",estepm, stepm);
4287: }
4288: else hstepm=estepm;
4289:
4290: hstepm=hstepm/stepm;
4291: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4292: fractional in yp1 */
4293: anprojmean=yp;
4294: yp2=modf((yp1*12),&yp);
4295: mprojmean=yp;
4296: yp1=modf((yp2*30.5),&yp);
4297: jprojmean=yp;
4298: if(jprojmean==0) jprojmean=1;
4299: if(mprojmean==0) jprojmean=1;
4300:
4301: i1=cptcoveff;
4302: if (cptcovn < 1){i1=1;}
4303:
4304: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4305:
4306: fprintf(ficresf,"#****** Routine prevforecast **\n");
4307:
4308: /* if (h==(int)(YEARM*yearp)){ */
4309: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4310: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4311: k=k+1;
4312: fprintf(ficresf,"\n#******");
4313: for(j=1;j<=cptcoveff;j++) {
4314: 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]]);
4315: }
4316: fprintf(ficresf,"******\n");
4317: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4318: for(j=1; j<=nlstate+ndeath;j++){
4319: for(i=1; i<=nlstate;i++)
4320: fprintf(ficresf," p%d%d",i,j);
4321: fprintf(ficresf," p.%d",j);
4322: }
4323: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4324: fprintf(ficresf,"\n");
4325: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4326:
4327: for (agec=fage; agec>=(ageminpar-1); agec--){
4328: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4329: nhstepm = nhstepm/hstepm;
4330: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4331: oldm=oldms;savm=savms;
4332: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4333:
4334: for (h=0; h<=nhstepm; h++){
4335: if (h*hstepm/YEARM*stepm ==yearp) {
4336: fprintf(ficresf,"\n");
4337: for(j=1;j<=cptcoveff;j++)
4338: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4339: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4340: }
4341: for(j=1; j<=nlstate+ndeath;j++) {
4342: ppij=0.;
4343: for(i=1; i<=nlstate;i++) {
4344: if (mobilav==1)
4345: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4346: else {
4347: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4348: }
4349: if (h*hstepm/YEARM*stepm== yearp) {
4350: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4351: }
4352: } /* end i */
4353: if (h*hstepm/YEARM*stepm==yearp) {
4354: fprintf(ficresf," %.3f", ppij);
4355: }
4356: }/* end j */
4357: } /* end h */
4358: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4359: } /* end agec */
4360: } /* end yearp */
4361: } /* end cptcod */
4362: } /* end cptcov */
4363:
4364: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4365:
4366: fclose(ficresf);
4367: }
4368:
4369: /************** Forecasting *****not tested NB*************/
4370: 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){
4371:
4372: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4373: int *popage;
4374: double calagedatem, agelim, kk1, kk2;
4375: double *popeffectif,*popcount;
4376: double ***p3mat,***tabpop,***tabpopprev;
4377: double ***mobaverage;
4378: char filerespop[FILENAMELENGTH];
4379:
4380: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4381: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4382: agelim=AGESUP;
4383: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4384:
4385: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4386:
4387:
4388: strcpy(filerespop,"pop");
4389: strcat(filerespop,fileres);
4390: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4391: printf("Problem with forecast resultfile: %s\n", filerespop);
4392: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4393: }
4394: printf("Computing forecasting: result on file '%s' \n", filerespop);
4395: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4396:
4397: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4398:
4399: if (mobilav!=0) {
4400: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4401: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4402: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4403: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4404: }
4405: }
4406:
4407: stepsize=(int) (stepm+YEARM-1)/YEARM;
4408: if (stepm<=12) stepsize=1;
4409:
4410: agelim=AGESUP;
4411:
4412: hstepm=1;
4413: hstepm=hstepm/stepm;
4414:
4415: if (popforecast==1) {
4416: if((ficpop=fopen(popfile,"r"))==NULL) {
4417: printf("Problem with population file : %s\n",popfile);exit(0);
4418: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4419: }
4420: popage=ivector(0,AGESUP);
4421: popeffectif=vector(0,AGESUP);
4422: popcount=vector(0,AGESUP);
4423:
4424: i=1;
4425: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4426:
4427: imx=i;
4428: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4429: }
4430:
4431: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4432: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4433: k=k+1;
4434: fprintf(ficrespop,"\n#******");
4435: for(j=1;j<=cptcoveff;j++) {
4436: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4437: }
4438: fprintf(ficrespop,"******\n");
4439: fprintf(ficrespop,"# Age");
4440: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4441: if (popforecast==1) fprintf(ficrespop," [Population]");
4442:
4443: for (cpt=0; cpt<=0;cpt++) {
4444: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4445:
4446: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4447: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4448: nhstepm = nhstepm/hstepm;
4449:
4450: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4451: oldm=oldms;savm=savms;
4452: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4453:
4454: for (h=0; h<=nhstepm; h++){
4455: if (h==(int) (calagedatem+YEARM*cpt)) {
4456: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4457: }
4458: for(j=1; j<=nlstate+ndeath;j++) {
4459: kk1=0.;kk2=0;
4460: for(i=1; i<=nlstate;i++) {
4461: if (mobilav==1)
4462: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4463: else {
4464: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4465: }
4466: }
4467: if (h==(int)(calagedatem+12*cpt)){
4468: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4469: /*fprintf(ficrespop," %.3f", kk1);
4470: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4471: }
4472: }
4473: for(i=1; i<=nlstate;i++){
4474: kk1=0.;
4475: for(j=1; j<=nlstate;j++){
4476: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4477: }
4478: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4479: }
4480:
4481: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4482: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4483: }
4484: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4485: }
4486: }
4487:
4488: /******/
4489:
4490: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4491: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4492: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4493: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4494: nhstepm = nhstepm/hstepm;
4495:
4496: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4497: oldm=oldms;savm=savms;
4498: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4499: for (h=0; h<=nhstepm; h++){
4500: if (h==(int) (calagedatem+YEARM*cpt)) {
4501: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4502: }
4503: for(j=1; j<=nlstate+ndeath;j++) {
4504: kk1=0.;kk2=0;
4505: for(i=1; i<=nlstate;i++) {
4506: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4507: }
4508: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4509: }
4510: }
4511: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4512: }
4513: }
4514: }
4515: }
4516:
4517: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4518:
4519: if (popforecast==1) {
4520: free_ivector(popage,0,AGESUP);
4521: free_vector(popeffectif,0,AGESUP);
4522: free_vector(popcount,0,AGESUP);
4523: }
4524: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4525: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4526: fclose(ficrespop);
4527: } /* End of popforecast */
4528:
4529: int fileappend(FILE *fichier, char *optionfich)
4530: {
4531: if((fichier=fopen(optionfich,"a"))==NULL) {
4532: printf("Problem with file: %s\n", optionfich);
4533: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4534: return (0);
4535: }
4536: fflush(fichier);
4537: return (1);
4538: }
4539:
4540:
4541: /**************** function prwizard **********************/
4542: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4543: {
4544:
4545: /* Wizard to print covariance matrix template */
4546:
4547: char ca[32], cb[32], cc[32];
4548: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4549: int numlinepar;
4550:
4551: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4552: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4553: for(i=1; i <=nlstate; i++){
4554: jj=0;
4555: for(j=1; j <=nlstate+ndeath; j++){
4556: if(j==i) continue;
4557: jj++;
4558: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4559: printf("%1d%1d",i,j);
4560: fprintf(ficparo,"%1d%1d",i,j);
4561: for(k=1; k<=ncovmodel;k++){
4562: /* printf(" %lf",param[i][j][k]); */
4563: /* fprintf(ficparo," %lf",param[i][j][k]); */
4564: printf(" 0.");
4565: fprintf(ficparo," 0.");
4566: }
4567: printf("\n");
4568: fprintf(ficparo,"\n");
4569: }
4570: }
4571: printf("# Scales (for hessian or gradient estimation)\n");
4572: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4573: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4574: for(i=1; i <=nlstate; i++){
4575: jj=0;
4576: for(j=1; j <=nlstate+ndeath; j++){
4577: if(j==i) continue;
4578: jj++;
4579: fprintf(ficparo,"%1d%1d",i,j);
4580: printf("%1d%1d",i,j);
4581: fflush(stdout);
4582: for(k=1; k<=ncovmodel;k++){
4583: /* printf(" %le",delti3[i][j][k]); */
4584: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4585: printf(" 0.");
4586: fprintf(ficparo," 0.");
4587: }
4588: numlinepar++;
4589: printf("\n");
4590: fprintf(ficparo,"\n");
4591: }
4592: }
4593: printf("# Covariance matrix\n");
4594: /* # 121 Var(a12)\n\ */
4595: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4596: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4597: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4598: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4599: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4600: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4601: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4602: fflush(stdout);
4603: fprintf(ficparo,"# Covariance matrix\n");
4604: /* # 121 Var(a12)\n\ */
4605: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4606: /* # ...\n\ */
4607: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4608:
4609: for(itimes=1;itimes<=2;itimes++){
4610: jj=0;
4611: for(i=1; i <=nlstate; i++){
4612: for(j=1; j <=nlstate+ndeath; j++){
4613: if(j==i) continue;
4614: for(k=1; k<=ncovmodel;k++){
4615: jj++;
4616: ca[0]= k+'a'-1;ca[1]='\0';
4617: if(itimes==1){
4618: printf("#%1d%1d%d",i,j,k);
4619: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4620: }else{
4621: printf("%1d%1d%d",i,j,k);
4622: fprintf(ficparo,"%1d%1d%d",i,j,k);
4623: /* printf(" %.5le",matcov[i][j]); */
4624: }
4625: ll=0;
4626: for(li=1;li <=nlstate; li++){
4627: for(lj=1;lj <=nlstate+ndeath; lj++){
4628: if(lj==li) continue;
4629: for(lk=1;lk<=ncovmodel;lk++){
4630: ll++;
4631: if(ll<=jj){
4632: cb[0]= lk +'a'-1;cb[1]='\0';
4633: if(ll<jj){
4634: if(itimes==1){
4635: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4636: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4637: }else{
4638: printf(" 0.");
4639: fprintf(ficparo," 0.");
4640: }
4641: }else{
4642: if(itimes==1){
4643: printf(" Var(%s%1d%1d)",ca,i,j);
4644: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4645: }else{
4646: printf(" 0.");
4647: fprintf(ficparo," 0.");
4648: }
4649: }
4650: }
4651: } /* end lk */
4652: } /* end lj */
4653: } /* end li */
4654: printf("\n");
4655: fprintf(ficparo,"\n");
4656: numlinepar++;
4657: } /* end k*/
4658: } /*end j */
4659: } /* end i */
4660: } /* end itimes */
4661:
4662: } /* end of prwizard */
4663: /******************* Gompertz Likelihood ******************************/
4664: double gompertz(double x[])
4665: {
4666: double A,B,L=0.0,sump=0.,num=0.;
4667: int i,n=0; /* n is the size of the sample */
4668:
4669: for (i=0;i<=imx-1 ; i++) {
4670: sump=sump+weight[i];
4671: /* sump=sump+1;*/
4672: num=num+1;
4673: }
4674:
4675:
4676: /* for (i=0; i<=imx; i++)
4677: 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]);*/
4678:
4679: for (i=1;i<=imx ; i++)
4680: {
4681: if (cens[i] == 1 && wav[i]>1)
4682: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4683:
4684: if (cens[i] == 0 && wav[i]>1)
4685: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4686: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4687:
4688: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4689: if (wav[i] > 1 ) { /* ??? */
4690: L=L+A*weight[i];
4691: /* 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]);*/
4692: }
4693: }
4694:
4695: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4696:
4697: return -2*L*num/sump;
4698: }
4699:
1.136 brouard 4700: #ifdef GSL
4701: /******************* Gompertz_f Likelihood ******************************/
4702: double gompertz_f(const gsl_vector *v, void *params)
4703: {
4704: double A,B,LL=0.0,sump=0.,num=0.;
4705: double *x= (double *) v->data;
4706: int i,n=0; /* n is the size of the sample */
4707:
4708: for (i=0;i<=imx-1 ; i++) {
4709: sump=sump+weight[i];
4710: /* sump=sump+1;*/
4711: num=num+1;
4712: }
4713:
4714:
4715: /* for (i=0; i<=imx; i++)
4716: 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]);*/
4717: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4718: for (i=1;i<=imx ; i++)
4719: {
4720: if (cens[i] == 1 && wav[i]>1)
4721: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4722:
4723: if (cens[i] == 0 && wav[i]>1)
4724: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4725: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4726:
4727: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4728: if (wav[i] > 1 ) { /* ??? */
4729: LL=LL+A*weight[i];
4730: /* 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]);*/
4731: }
4732: }
4733:
4734: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4735: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4736:
4737: return -2*LL*num/sump;
4738: }
4739: #endif
4740:
1.126 brouard 4741: /******************* Printing html file ***********/
4742: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4743: int lastpass, int stepm, int weightopt, char model[],\
4744: int imx, double p[],double **matcov,double agemortsup){
4745: int i,k;
4746:
4747: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4748: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4749: for (i=1;i<=2;i++)
4750: 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]));
4751: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4752: fprintf(fichtm,"</ul>");
4753:
4754: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4755:
4756: 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>");
4757:
4758: for (k=agegomp;k<(agemortsup-2);k++)
4759: 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]);
4760:
4761:
4762: fflush(fichtm);
4763: }
4764:
4765: /******************* Gnuplot file **************/
4766: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4767:
4768: char dirfileres[132],optfileres[132];
4769: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4770: int ng;
4771:
4772:
4773: /*#ifdef windows */
4774: fprintf(ficgp,"cd \"%s\" \n",pathc);
4775: /*#endif */
4776:
4777:
4778: strcpy(dirfileres,optionfilefiname);
4779: strcpy(optfileres,"vpl");
4780: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4781: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4782: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4783: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4784: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4785:
4786: }
4787:
1.136 brouard 4788: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4789: {
1.126 brouard 4790:
1.136 brouard 4791: /*-------- data file ----------*/
4792: FILE *fic;
4793: char dummy[]=" ";
4794: int i, j, n;
4795: int linei, month, year,iout;
4796: char line[MAXLINE], linetmp[MAXLINE];
4797: char stra[80], strb[80];
4798: char *stratrunc;
4799: int lstra;
1.126 brouard 4800:
4801:
1.136 brouard 4802: if((fic=fopen(datafile,"r"))==NULL) {
4803: printf("Problem while opening datafile: %s\n", datafile);return 1;
4804: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4805: }
1.126 brouard 4806:
1.136 brouard 4807: i=1;
4808: linei=0;
4809: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4810: linei=linei+1;
4811: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4812: if(line[j] == '\t')
4813: line[j] = ' ';
4814: }
4815: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4816: ;
4817: };
4818: line[j+1]=0; /* Trims blanks at end of line */
4819: if(line[0]=='#'){
4820: fprintf(ficlog,"Comment line\n%s\n",line);
4821: printf("Comment line\n%s\n",line);
4822: continue;
4823: }
4824: trimbb(linetmp,line); /* Trims multiple blanks in line */
4825: for (j=0; line[j]!='\0';j++){
4826: line[j]=linetmp[j];
4827: }
4828:
1.126 brouard 4829:
1.136 brouard 4830: for (j=maxwav;j>=1;j--){
1.137 brouard 4831: cutv(stra, strb, line, ' ');
1.136 brouard 4832: if(strb[0]=='.') { /* Missing status */
4833: lval=-1;
4834: }else{
4835: errno=0;
4836: lval=strtol(strb,&endptr,10);
4837: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4838: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4839: 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);
4840: 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 4841: return 1;
4842: }
4843: }
4844: s[j][i]=lval;
4845:
4846: strcpy(line,stra);
4847: cutv(stra, strb,line,' ');
4848: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4849: }
1.145 brouard 4850: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 4851: month=99;
4852: year=9999;
4853: }else{
1.141 brouard 4854: 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);
4855: 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 4856: return 1;
4857: }
4858: anint[j][i]= (double) year;
4859: mint[j][i]= (double)month;
4860: strcpy(line,stra);
4861: } /* ENd Waves */
4862:
4863: cutv(stra, strb,line,' ');
4864: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4865: }
4866: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4867: month=99;
4868: year=9999;
4869: }else{
1.141 brouard 4870: 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);
4871: 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 4872: return 1;
4873: }
4874: andc[i]=(double) year;
4875: moisdc[i]=(double) month;
4876: strcpy(line,stra);
4877:
4878: cutv(stra, strb,line,' ');
4879: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4880: }
1.145 brouard 4881: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 4882: month=99;
4883: year=9999;
4884: }else{
1.141 brouard 4885: 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);
4886: 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 4887: return 1;
4888: }
4889: if (year==9999) {
1.141 brouard 4890: 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);
4891: 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 4892: return 1;
1.126 brouard 4893:
1.136 brouard 4894: }
4895: annais[i]=(double)(year);
4896: moisnais[i]=(double)(month);
4897: strcpy(line,stra);
4898:
4899: cutv(stra, strb,line,' ');
4900: errno=0;
4901: dval=strtod(strb,&endptr);
4902: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4903: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4904: 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 4905: fflush(ficlog);
4906: return 1;
4907: }
4908: weight[i]=dval;
4909: strcpy(line,stra);
4910:
4911: for (j=ncovcol;j>=1;j--){
4912: cutv(stra, strb,line,' ');
4913: if(strb[0]=='.') { /* Missing status */
4914: lval=-1;
4915: }else{
4916: errno=0;
4917: lval=strtol(strb,&endptr,10);
4918: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4919: 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);
4920: 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 4921: return 1;
4922: }
4923: }
4924: if(lval <-1 || lval >1){
1.141 brouard 4925: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4926: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4927: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4928: For example, for multinomial values like 1, 2 and 3,\n \
4929: build V1=0 V2=0 for the reference value (1),\n \
4930: V1=1 V2=0 for (2) \n \
4931: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4932: output of IMaCh is often meaningless.\n \
4933: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 4934: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4935: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4936: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4937: For example, for multinomial values like 1, 2 and 3,\n \
4938: build V1=0 V2=0 for the reference value (1),\n \
4939: V1=1 V2=0 for (2) \n \
4940: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4941: output of IMaCh is often meaningless.\n \
4942: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
4943: return 1;
4944: }
4945: covar[j][i]=(double)(lval);
4946: strcpy(line,stra);
4947: }
4948: lstra=strlen(stra);
4949:
4950: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
4951: stratrunc = &(stra[lstra-9]);
4952: num[i]=atol(stratrunc);
4953: }
4954: else
4955: num[i]=atol(stra);
4956: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
4957: 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;}*/
4958:
4959: i=i+1;
4960: } /* End loop reading data */
1.126 brouard 4961:
1.136 brouard 4962: *imax=i-1; /* Number of individuals */
4963: fclose(fic);
4964:
4965: return (0);
4966: endread:
4967: printf("Exiting readdata: ");
4968: fclose(fic);
4969: return (1);
1.126 brouard 4970:
4971:
4972:
1.136 brouard 4973: }
1.145 brouard 4974: void removespace(char *str) {
4975: char *p1 = str, *p2 = str;
4976: do
4977: while (*p2 == ' ')
4978: p2++;
4979: while (*p1++ = *p2++);
4980: }
4981:
4982: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
4983: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
4984: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
4985: * - cptcovn or number of covariates k of the models excluding age*products =6
4986: * - cptcovage number of covariates with age*products =2
4987: * - cptcovs number of simple covariates
4988: * - 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
4989: * which is a new column after the 9 (ncovcol) variables.
4990: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
4991: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
4992: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
4993: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
4994: */
1.136 brouard 4995: {
1.145 brouard 4996: int i, j, k, ks;
1.136 brouard 4997: int i1, j1, k1, k2;
4998: char modelsav[80];
1.145 brouard 4999: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5000:
1.145 brouard 5001: /*removespace(model);*/
1.136 brouard 5002: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5003: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5004: j=nbocc(model,'+'); /**< j=Number of '+' */
5005: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5006: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5007: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5008: /* including age products which are counted in cptcovage.
5009: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5010: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5011: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5012: strcpy(modelsav,model);
1.137 brouard 5013: if (strstr(model,"AGE") !=0){
5014: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5015: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5016: return 1;
5017: }
1.141 brouard 5018: if (strstr(model,"v") !=0){
5019: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5020: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5021: return 1;
5022: }
1.136 brouard 5023:
1.145 brouard 5024: /* Design
5025: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5026: * < ncovcol=8 >
5027: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5028: * k= 1 2 3 4 5 6 7 8
5029: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5030: * covar[k,i], value of kth covariate if not including age for individual i:
5031: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5032: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5033: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5034: * Tage[++cptcovage]=k
5035: * if products, new covar are created after ncovcol with k1
5036: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5037: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5038: * 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
5039: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5040: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5041: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5042: * < ncovcol=8 >
5043: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5044: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5045: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5046: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5047: * p Tprod[1]@2={ 6, 5}
5048: *p Tvard[1][1]@4= {7, 8, 5, 6}
5049: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5050: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5051: *How to reorganize?
5052: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5053: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5054: * {2, 1, 4, 8, 5, 6, 3, 7}
5055: * Struct []
5056: */
5057:
1.136 brouard 5058: /* This loop fills the array Tvar from the string 'model'.*/
5059: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5060: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5061: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5062: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5063: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5064: /* k=1 Tvar[1]=2 (from V2) */
5065: /* k=5 Tvar[5] */
5066: /* for (k=1; k<=cptcovn;k++) { */
5067: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5068: /* } */
5069: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5070: /*
5071: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5072: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5073: Tvar[k]=0;
5074: cptcovage=0;
5075: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5076: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5077: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5078: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5079: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5080: /*scanf("%d",i);*/
1.145 brouard 5081: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5082: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5083: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5084: /* covar is not filled and then is empty */
1.136 brouard 5085: cptcovprod--;
1.145 brouard 5086: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5087: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5088: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5089: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5090: /*printf("stre=%s ", stre);*/
1.137 brouard 5091: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5092: cptcovprod--;
1.145 brouard 5093: cutl(stre,strb,strc,'V');
1.136 brouard 5094: Tvar[k]=atoi(stre);
5095: cptcovage++;
5096: Tage[cptcovage]=k;
1.137 brouard 5097: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5098: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5099: cptcovn++;
5100: cptcovprodnoage++;k1++;
5101: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5102: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5103: because this model-covariate is a construction we invent a new column
5104: ncovcol + k1
5105: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5106: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5107: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5108: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5109: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5110: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5111: k2=k2+2;
5112: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5113: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5114: for (i=1; i<=lastobs;i++){
5115: /* Computes the new covariate which is a product of
1.145 brouard 5116: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5117: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5118: }
5119: } /* End age is not in the model */
5120: } /* End if model includes a product */
1.136 brouard 5121: else { /* no more sum */
5122: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5123: /* scanf("%d",i);*/
1.145 brouard 5124: cutl(strd,strc,strb,'V');
5125: ks++; /**< Number of simple covariates */
5126: cptcovn++;
5127: Tvar[k]=atoi(strd);
1.136 brouard 5128: }
1.137 brouard 5129: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5130: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5131: scanf("%d",i);*/
5132: } /* end of loop + */
5133: } /* end model */
5134:
5135: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5136: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5137:
5138: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5139: printf("cptcovprod=%d ", cptcovprod);
5140: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5141:
5142: scanf("%d ",i);*/
5143:
5144:
1.137 brouard 5145: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.136 brouard 5146: endread:
5147: printf("Exiting decodemodel: ");
5148: return (1);
5149: }
5150:
5151: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5152: {
5153: int i, m;
5154:
5155: for (i=1; i<=imx; i++) {
5156: for(m=2; (m<= maxwav); m++) {
5157: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5158: anint[m][i]=9999;
5159: s[m][i]=-1;
5160: }
5161: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5162: *nberr++;
5163: 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);
5164: 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);
5165: s[m][i]=-1;
5166: }
5167: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5168: *nberr++;
5169: 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]);
5170: 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]);
5171: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5172: }
5173: }
5174: }
5175:
5176: for (i=1; i<=imx; i++) {
5177: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5178: for(m=firstpass; (m<= lastpass); m++){
5179: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5180: if (s[m][i] >= nlstate+1) {
5181: if(agedc[i]>0)
5182: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5183: agev[m][i]=agedc[i];
5184: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5185: else {
5186: if ((int)andc[i]!=9999){
5187: nbwarn++;
5188: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5189: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5190: agev[m][i]=-1;
5191: }
5192: }
5193: }
5194: else if(s[m][i] !=9){ /* Standard case, age in fractional
5195: years but with the precision of a month */
5196: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5197: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5198: agev[m][i]=1;
5199: else if(agev[m][i] < *agemin){
5200: *agemin=agev[m][i];
5201: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5202: }
5203: else if(agev[m][i] >*agemax){
5204: *agemax=agev[m][i];
1.156 brouard 5205: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5206: }
5207: /*agev[m][i]=anint[m][i]-annais[i];*/
5208: /* agev[m][i] = age[i]+2*m;*/
5209: }
5210: else { /* =9 */
5211: agev[m][i]=1;
5212: s[m][i]=-1;
5213: }
5214: }
5215: else /*= 0 Unknown */
5216: agev[m][i]=1;
5217: }
5218:
5219: }
5220: for (i=1; i<=imx; i++) {
5221: for(m=firstpass; (m<=lastpass); m++){
5222: if (s[m][i] > (nlstate+ndeath)) {
5223: *nberr++;
5224: 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);
5225: 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);
5226: return 1;
5227: }
5228: }
5229: }
5230:
5231: /*for (i=1; i<=imx; i++){
5232: for (m=firstpass; (m<lastpass); m++){
5233: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5234: }
5235:
5236: }*/
5237:
5238:
1.139 brouard 5239: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5240: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5241:
5242: return (0);
5243: endread:
5244: printf("Exiting calandcheckages: ");
5245: return (1);
5246: }
5247:
5248:
5249: /***********************************************/
5250: /**************** Main Program *****************/
5251: /***********************************************/
5252:
5253: int main(int argc, char *argv[])
5254: {
5255: #ifdef GSL
5256: const gsl_multimin_fminimizer_type *T;
5257: size_t iteri = 0, it;
5258: int rval = GSL_CONTINUE;
5259: int status = GSL_SUCCESS;
5260: double ssval;
5261: #endif
5262: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5263: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5264: int linei, month, year,iout;
5265: int jj, ll, li, lj, lk, imk;
5266: int numlinepar=0; /* Current linenumber of parameter file */
5267: int itimes;
5268: int NDIM=2;
5269: int vpopbased=0;
5270:
5271: char ca[32], cb[32], cc[32];
5272: /* FILE *fichtm; *//* Html File */
5273: /* FILE *ficgp;*/ /*Gnuplot File */
5274: struct stat info;
5275: double agedeb, agefin,hf;
5276: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5277:
5278: double fret;
5279: double **xi,tmp,delta;
5280:
5281: double dum; /* Dummy variable */
5282: double ***p3mat;
5283: double ***mobaverage;
5284: int *indx;
5285: char line[MAXLINE], linepar[MAXLINE];
5286: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5287: char pathr[MAXLINE], pathimach[MAXLINE];
5288: char **bp, *tok, *val; /* pathtot */
5289: int firstobs=1, lastobs=10;
5290: int sdeb, sfin; /* Status at beginning and end */
5291: int c, h , cpt,l;
5292: int ju,jl, mi;
5293: int i1,j1, jk,aa,bb, stepsize, ij;
5294: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5295: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5296: int mobilav=0,popforecast=0;
5297: int hstepm, nhstepm;
5298: int agemortsup;
5299: float sumlpop=0.;
5300: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5301: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5302:
5303: double bage, fage, age, agelim, agebase;
5304: double ftolpl=FTOL;
5305: double **prlim;
5306: double ***param; /* Matrix of parameters */
5307: double *p;
5308: double **matcov; /* Matrix of covariance */
5309: double ***delti3; /* Scale */
5310: double *delti; /* Scale */
5311: double ***eij, ***vareij;
5312: double **varpl; /* Variances of prevalence limits by age */
5313: double *epj, vepp;
5314: double kk1, kk2;
5315: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5316: double **ximort;
1.145 brouard 5317: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5318: int *dcwave;
5319:
5320: char z[1]="c", occ;
5321:
5322: /*char *strt;*/
5323: char strtend[80];
1.126 brouard 5324:
5325: long total_usecs;
5326:
5327: /* setlocale (LC_ALL, ""); */
5328: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5329: /* textdomain (PACKAGE); */
5330: /* setlocale (LC_CTYPE, ""); */
5331: /* setlocale (LC_MESSAGES, ""); */
5332:
5333: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5334: rstart_time = time(NULL);
5335: /* (void) gettimeofday(&start_time,&tzp);*/
5336: start_time = *localtime(&rstart_time);
1.126 brouard 5337: curr_time=start_time;
1.157 brouard 5338: /*tml = *localtime(&start_time.tm_sec);*/
5339: /* strcpy(strstart,asctime(&tml)); */
5340: strcpy(strstart,asctime(&start_time));
1.126 brouard 5341:
5342: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5343: /* tp.tm_sec = tp.tm_sec +86400; */
5344: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5345: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5346: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5347: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5348: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5349: /* strt=asctime(&tmg); */
5350: /* printf("Time(after) =%s",strstart); */
5351: /* (void) time (&time_value);
5352: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5353: * tm = *localtime(&time_value);
5354: * strstart=asctime(&tm);
5355: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5356: */
5357:
5358: nberr=0; /* Number of errors and warnings */
5359: nbwarn=0;
5360: getcwd(pathcd, size);
5361:
5362: printf("\n%s\n%s",version,fullversion);
5363: if(argc <=1){
5364: printf("\nEnter the parameter file name: ");
5365: fgets(pathr,FILENAMELENGTH,stdin);
5366: i=strlen(pathr);
5367: if(pathr[i-1]=='\n')
5368: pathr[i-1]='\0';
1.156 brouard 5369: i=strlen(pathr);
5370: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5371: pathr[i-1]='\0';
1.126 brouard 5372: for (tok = pathr; tok != NULL; ){
5373: printf("Pathr |%s|\n",pathr);
5374: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5375: printf("val= |%s| pathr=%s\n",val,pathr);
5376: strcpy (pathtot, val);
5377: if(pathr[0] == '\0') break; /* Dirty */
5378: }
5379: }
5380: else{
5381: strcpy(pathtot,argv[1]);
5382: }
5383: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5384: /*cygwin_split_path(pathtot,path,optionfile);
5385: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5386: /* cutv(path,optionfile,pathtot,'\\');*/
5387:
5388: /* Split argv[0], imach program to get pathimach */
5389: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5390: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5391: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5392: /* strcpy(pathimach,argv[0]); */
5393: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5394: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5395: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5396: chdir(path); /* Can be a relative path */
5397: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5398: printf("Current directory %s!\n",pathcd);
5399: strcpy(command,"mkdir ");
5400: strcat(command,optionfilefiname);
5401: if((outcmd=system(command)) != 0){
5402: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5403: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5404: /* fclose(ficlog); */
5405: /* exit(1); */
5406: }
5407: /* if((imk=mkdir(optionfilefiname))<0){ */
5408: /* perror("mkdir"); */
5409: /* } */
5410:
5411: /*-------- arguments in the command line --------*/
5412:
5413: /* Log file */
5414: strcat(filelog, optionfilefiname);
5415: strcat(filelog,".log"); /* */
5416: if((ficlog=fopen(filelog,"w"))==NULL) {
5417: printf("Problem with logfile %s\n",filelog);
5418: goto end;
5419: }
5420: fprintf(ficlog,"Log filename:%s\n",filelog);
5421: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5422: fprintf(ficlog,"\nEnter the parameter file name: \n");
5423: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5424: path=%s \n\
5425: optionfile=%s\n\
5426: optionfilext=%s\n\
1.156 brouard 5427: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5428:
5429: printf("Local time (at start):%s",strstart);
5430: fprintf(ficlog,"Local time (at start): %s",strstart);
5431: fflush(ficlog);
5432: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5433: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5434:
5435: /* */
5436: strcpy(fileres,"r");
5437: strcat(fileres, optionfilefiname);
5438: strcat(fileres,".txt"); /* Other files have txt extension */
5439:
5440: /*---------arguments file --------*/
5441:
5442: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5443: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5444: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5445: fflush(ficlog);
1.149 brouard 5446: /* goto end; */
5447: exit(70);
1.126 brouard 5448: }
5449:
5450:
5451:
5452: strcpy(filereso,"o");
5453: strcat(filereso,fileres);
5454: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5455: printf("Problem with Output resultfile: %s\n", filereso);
5456: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5457: fflush(ficlog);
5458: goto end;
5459: }
5460:
5461: /* Reads comments: lines beginning with '#' */
5462: numlinepar=0;
5463: while((c=getc(ficpar))=='#' && c!= EOF){
5464: ungetc(c,ficpar);
5465: fgets(line, MAXLINE, ficpar);
5466: numlinepar++;
1.141 brouard 5467: fputs(line,stdout);
1.126 brouard 5468: fputs(line,ficparo);
5469: fputs(line,ficlog);
5470: }
5471: ungetc(c,ficpar);
5472:
5473: 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);
5474: numlinepar++;
5475: 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);
5476: 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);
5477: 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);
5478: fflush(ficlog);
5479: while((c=getc(ficpar))=='#' && c!= EOF){
5480: ungetc(c,ficpar);
5481: fgets(line, MAXLINE, ficpar);
5482: numlinepar++;
1.141 brouard 5483: fputs(line, stdout);
5484: //puts(line);
1.126 brouard 5485: fputs(line,ficparo);
5486: fputs(line,ficlog);
5487: }
5488: ungetc(c,ficpar);
5489:
5490:
1.145 brouard 5491: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5492: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5493: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5494: v1+v2*age+v2*v3 makes cptcovn = 3
5495: */
5496: if (strlen(model)>1)
1.145 brouard 5497: 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*/
5498: else
5499: ncovmodel=2;
1.126 brouard 5500: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5501: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5502: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5503: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5504: 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);
5505: 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);
5506: fflush(stdout);
5507: fclose (ficlog);
5508: goto end;
5509: }
1.126 brouard 5510: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5511: delti=delti3[1][1];
5512: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5513: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5514: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5515: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5516: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5517: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5518: fclose (ficparo);
5519: fclose (ficlog);
5520: goto end;
5521: exit(0);
5522: }
5523: else if(mle==-3) {
5524: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5525: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5526: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5527: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5528: matcov=matrix(1,npar,1,npar);
5529: }
5530: else{
1.145 brouard 5531: /* Read guessed parameters */
1.126 brouard 5532: /* Reads comments: lines beginning with '#' */
5533: while((c=getc(ficpar))=='#' && c!= EOF){
5534: ungetc(c,ficpar);
5535: fgets(line, MAXLINE, ficpar);
5536: numlinepar++;
1.141 brouard 5537: fputs(line,stdout);
1.126 brouard 5538: fputs(line,ficparo);
5539: fputs(line,ficlog);
5540: }
5541: ungetc(c,ficpar);
5542:
5543: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5544: for(i=1; i <=nlstate; i++){
5545: j=0;
5546: for(jj=1; jj <=nlstate+ndeath; jj++){
5547: if(jj==i) continue;
5548: j++;
5549: fscanf(ficpar,"%1d%1d",&i1,&j1);
5550: if ((i1 != i) && (j1 != j)){
5551: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5552: It might be a problem of design; if ncovcol and the model are correct\n \
5553: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5554: exit(1);
5555: }
5556: fprintf(ficparo,"%1d%1d",i1,j1);
5557: if(mle==1)
5558: printf("%1d%1d",i,j);
5559: fprintf(ficlog,"%1d%1d",i,j);
5560: for(k=1; k<=ncovmodel;k++){
5561: fscanf(ficpar," %lf",¶m[i][j][k]);
5562: if(mle==1){
5563: printf(" %lf",param[i][j][k]);
5564: fprintf(ficlog," %lf",param[i][j][k]);
5565: }
5566: else
5567: fprintf(ficlog," %lf",param[i][j][k]);
5568: fprintf(ficparo," %lf",param[i][j][k]);
5569: }
5570: fscanf(ficpar,"\n");
5571: numlinepar++;
5572: if(mle==1)
5573: printf("\n");
5574: fprintf(ficlog,"\n");
5575: fprintf(ficparo,"\n");
5576: }
5577: }
5578: fflush(ficlog);
5579:
1.145 brouard 5580: /* Reads scales values */
1.126 brouard 5581: p=param[1][1];
5582:
5583: /* Reads comments: lines beginning with '#' */
5584: while((c=getc(ficpar))=='#' && c!= EOF){
5585: ungetc(c,ficpar);
5586: fgets(line, MAXLINE, ficpar);
5587: numlinepar++;
1.141 brouard 5588: fputs(line,stdout);
1.126 brouard 5589: fputs(line,ficparo);
5590: fputs(line,ficlog);
5591: }
5592: ungetc(c,ficpar);
5593:
5594: for(i=1; i <=nlstate; i++){
5595: for(j=1; j <=nlstate+ndeath-1; j++){
5596: fscanf(ficpar,"%1d%1d",&i1,&j1);
5597: if ((i1-i)*(j1-j)!=0){
5598: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5599: exit(1);
5600: }
5601: printf("%1d%1d",i,j);
5602: fprintf(ficparo,"%1d%1d",i1,j1);
5603: fprintf(ficlog,"%1d%1d",i1,j1);
5604: for(k=1; k<=ncovmodel;k++){
5605: fscanf(ficpar,"%le",&delti3[i][j][k]);
5606: printf(" %le",delti3[i][j][k]);
5607: fprintf(ficparo," %le",delti3[i][j][k]);
5608: fprintf(ficlog," %le",delti3[i][j][k]);
5609: }
5610: fscanf(ficpar,"\n");
5611: numlinepar++;
5612: printf("\n");
5613: fprintf(ficparo,"\n");
5614: fprintf(ficlog,"\n");
5615: }
5616: }
5617: fflush(ficlog);
5618:
1.145 brouard 5619: /* Reads covariance matrix */
1.126 brouard 5620: delti=delti3[1][1];
5621:
5622:
5623: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5624:
5625: /* Reads comments: lines beginning with '#' */
5626: while((c=getc(ficpar))=='#' && c!= EOF){
5627: ungetc(c,ficpar);
5628: fgets(line, MAXLINE, ficpar);
5629: numlinepar++;
1.141 brouard 5630: fputs(line,stdout);
1.126 brouard 5631: fputs(line,ficparo);
5632: fputs(line,ficlog);
5633: }
5634: ungetc(c,ficpar);
5635:
5636: matcov=matrix(1,npar,1,npar);
1.131 brouard 5637: for(i=1; i <=npar; i++)
5638: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5639:
1.126 brouard 5640: for(i=1; i <=npar; i++){
1.145 brouard 5641: fscanf(ficpar,"%s",str);
1.126 brouard 5642: if(mle==1)
5643: printf("%s",str);
5644: fprintf(ficlog,"%s",str);
5645: fprintf(ficparo,"%s",str);
5646: for(j=1; j <=i; j++){
5647: fscanf(ficpar," %le",&matcov[i][j]);
5648: if(mle==1){
5649: printf(" %.5le",matcov[i][j]);
5650: }
5651: fprintf(ficlog," %.5le",matcov[i][j]);
5652: fprintf(ficparo," %.5le",matcov[i][j]);
5653: }
5654: fscanf(ficpar,"\n");
5655: numlinepar++;
5656: if(mle==1)
5657: printf("\n");
5658: fprintf(ficlog,"\n");
5659: fprintf(ficparo,"\n");
5660: }
5661: for(i=1; i <=npar; i++)
5662: for(j=i+1;j<=npar;j++)
5663: matcov[i][j]=matcov[j][i];
5664:
5665: if(mle==1)
5666: printf("\n");
5667: fprintf(ficlog,"\n");
5668:
5669: fflush(ficlog);
5670:
5671: /*-------- Rewriting parameter file ----------*/
5672: strcpy(rfileres,"r"); /* "Rparameterfile */
5673: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5674: strcat(rfileres,"."); /* */
5675: strcat(rfileres,optionfilext); /* Other files have txt extension */
5676: if((ficres =fopen(rfileres,"w"))==NULL) {
5677: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5678: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5679: }
5680: fprintf(ficres,"#%s\n",version);
5681: } /* End of mle != -3 */
5682:
5683:
5684: n= lastobs;
5685: num=lvector(1,n);
5686: moisnais=vector(1,n);
5687: annais=vector(1,n);
5688: moisdc=vector(1,n);
5689: andc=vector(1,n);
5690: agedc=vector(1,n);
5691: cod=ivector(1,n);
5692: weight=vector(1,n);
5693: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5694: mint=matrix(1,maxwav,1,n);
5695: anint=matrix(1,maxwav,1,n);
1.131 brouard 5696: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5697: tab=ivector(1,NCOVMAX);
1.144 brouard 5698: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5699:
1.136 brouard 5700: /* Reads data from file datafile */
5701: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5702: goto end;
5703:
5704: /* Calculation of the number of parameters from char model */
1.137 brouard 5705: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5706: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5707: k=3 V4 Tvar[k=3]= 4 (from V4)
5708: k=2 V1 Tvar[k=2]= 1 (from V1)
5709: k=1 Tvar[1]=2 (from V2)
5710: */
5711: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5712: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5713: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5714: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5715: */
5716: /* For model-covariate k tells which data-covariate to use but
5717: because this model-covariate is a construction we invent a new column
5718: ncovcol + k1
5719: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5720: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5721: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5722: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5723: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5724: */
1.145 brouard 5725: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5726: 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 5727: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5728: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5729: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5730: 4 covariates (3 plus signs)
5731: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5732: */
1.136 brouard 5733:
5734: if(decodemodel(model, lastobs) == 1)
5735: goto end;
5736:
1.137 brouard 5737: if((double)(lastobs-imx)/(double)imx > 1.10){
5738: nbwarn++;
5739: 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);
5740: 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);
5741: }
1.136 brouard 5742: /* if(mle==1){*/
1.137 brouard 5743: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5744: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5745: }
5746:
5747: /*-calculation of age at interview from date of interview and age at death -*/
5748: agev=matrix(1,maxwav,1,imx);
5749:
5750: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5751: goto end;
5752:
1.126 brouard 5753:
1.136 brouard 5754: agegomp=(int)agemin;
5755: free_vector(moisnais,1,n);
5756: free_vector(annais,1,n);
1.126 brouard 5757: /* free_matrix(mint,1,maxwav,1,n);
5758: free_matrix(anint,1,maxwav,1,n);*/
5759: free_vector(moisdc,1,n);
5760: free_vector(andc,1,n);
1.145 brouard 5761: /* */
5762:
1.126 brouard 5763: wav=ivector(1,imx);
5764: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5765: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5766: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5767:
5768: /* Concatenates waves */
5769: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5770: /* */
5771:
1.126 brouard 5772: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5773:
5774: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5775: ncodemax[1]=1;
1.145 brouard 5776: Ndum =ivector(-1,NCOVMAX);
5777: if (ncovmodel > 2)
5778: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5779:
5780: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5781: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5782: h=0;
5783:
5784:
5785: /*if (cptcovn > 0) */
1.126 brouard 5786:
1.145 brouard 5787:
1.126 brouard 5788: m=pow(2,cptcoveff);
5789:
1.131 brouard 5790: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5791: 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 */
5792: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5793: 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 5794: h++;
1.141 brouard 5795: if (h>m)
1.136 brouard 5796: h=1;
1.144 brouard 5797: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5798: * h 1 2 3 4
5799: *______________________________
5800: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5801: * 2 2 1 1 1
5802: * 3 i=2 1 2 1 1
5803: * 4 2 2 1 1
5804: * 5 i=3 1 i=2 1 2 1
5805: * 6 2 1 2 1
5806: * 7 i=4 1 2 2 1
5807: * 8 2 2 2 1
5808: * 9 i=5 1 i=3 1 i=2 1 1
5809: * 10 2 1 1 1
5810: * 11 i=6 1 2 1 1
5811: * 12 2 2 1 1
5812: * 13 i=7 1 i=4 1 2 1
5813: * 14 2 1 2 1
5814: * 15 i=8 1 2 2 1
5815: * 16 2 2 2 1
5816: */
1.141 brouard 5817: codtab[h][k]=j;
1.145 brouard 5818: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5819: 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 5820: }
5821: }
5822: }
5823: }
5824: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5825: codtab[1][2]=1;codtab[2][2]=2; */
5826: /* for(i=1; i <=m ;i++){
5827: for(k=1; k <=cptcovn; k++){
1.131 brouard 5828: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5829: }
5830: printf("\n");
5831: }
5832: scanf("%d",i);*/
1.145 brouard 5833:
5834: free_ivector(Ndum,-1,NCOVMAX);
5835:
5836:
1.126 brouard 5837:
5838: /*------------ gnuplot -------------*/
5839: strcpy(optionfilegnuplot,optionfilefiname);
5840: if(mle==-3)
5841: strcat(optionfilegnuplot,"-mort");
5842: strcat(optionfilegnuplot,".gp");
5843:
5844: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5845: printf("Problem with file %s",optionfilegnuplot);
5846: }
5847: else{
5848: fprintf(ficgp,"\n# %s\n", version);
5849: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 5850: //fprintf(ficgp,"set missing 'NaNq'\n");
5851: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 5852: }
5853: /* fclose(ficgp);*/
5854: /*--------- index.htm --------*/
5855:
5856: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5857: if(mle==-3)
5858: strcat(optionfilehtm,"-mort");
5859: strcat(optionfilehtm,".htm");
5860: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 5861: printf("Problem with %s \n",optionfilehtm);
5862: exit(0);
1.126 brouard 5863: }
5864:
5865: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5866: strcat(optionfilehtmcov,"-cov.htm");
5867: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5868: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5869: }
5870: else{
5871: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5872: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5873: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5874: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5875: }
5876:
5877: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5878: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5879: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5880: \n\
5881: <hr size=\"2\" color=\"#EC5E5E\">\
5882: <ul><li><h4>Parameter files</h4>\n\
5883: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5884: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5885: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5886: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5887: - Date and time at start: %s</ul>\n",\
5888: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5889: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5890: fileres,fileres,\
5891: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5892: fflush(fichtm);
5893:
5894: strcpy(pathr,path);
5895: strcat(pathr,optionfilefiname);
5896: chdir(optionfilefiname); /* Move to directory named optionfile */
5897:
5898: /* Calculates basic frequencies. Computes observed prevalence at single age
5899: and prints on file fileres'p'. */
5900: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5901:
5902: fprintf(fichtm,"\n");
5903: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5904: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5905: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5906: imx,agemin,agemax,jmin,jmax,jmean);
5907: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5908: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5909: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5910: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5911: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5912:
5913:
5914: /* For Powell, parameters are in a vector p[] starting at p[1]
5915: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5916: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5917:
5918: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5919:
5920: if (mle==-3){
1.136 brouard 5921: ximort=matrix(1,NDIM,1,NDIM);
5922: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 5923: cens=ivector(1,n);
5924: ageexmed=vector(1,n);
5925: agecens=vector(1,n);
5926: dcwave=ivector(1,n);
5927:
5928: for (i=1; i<=imx; i++){
5929: dcwave[i]=-1;
5930: for (m=firstpass; m<=lastpass; m++)
5931: if (s[m][i]>nlstate) {
5932: dcwave[i]=m;
5933: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5934: break;
5935: }
5936: }
5937:
5938: for (i=1; i<=imx; i++) {
5939: if (wav[i]>0){
5940: ageexmed[i]=agev[mw[1][i]][i];
5941: j=wav[i];
5942: agecens[i]=1.;
5943:
5944: if (ageexmed[i]> 1 && wav[i] > 0){
5945: agecens[i]=agev[mw[j][i]][i];
5946: cens[i]= 1;
5947: }else if (ageexmed[i]< 1)
5948: cens[i]= -1;
5949: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
5950: cens[i]=0 ;
5951: }
5952: else cens[i]=-1;
5953: }
5954:
5955: for (i=1;i<=NDIM;i++) {
5956: for (j=1;j<=NDIM;j++)
5957: ximort[i][j]=(i == j ? 1.0 : 0.0);
5958: }
5959:
1.145 brouard 5960: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 5961: /*printf("%lf %lf", p[1], p[2]);*/
5962:
5963:
1.136 brouard 5964: #ifdef GSL
5965: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
5966: #elsedef
1.126 brouard 5967: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 5968: #endif
1.126 brouard 5969: strcpy(filerespow,"pow-mort");
5970: strcat(filerespow,fileres);
5971: if((ficrespow=fopen(filerespow,"w"))==NULL) {
5972: printf("Problem with resultfile: %s\n", filerespow);
5973: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
5974: }
1.136 brouard 5975: #ifdef GSL
5976: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
5977: #elsedef
1.126 brouard 5978: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 5979: #endif
1.126 brouard 5980: /* for (i=1;i<=nlstate;i++)
5981: for(j=1;j<=nlstate+ndeath;j++)
5982: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
5983: */
5984: fprintf(ficrespow,"\n");
1.136 brouard 5985: #ifdef GSL
5986: /* gsl starts here */
5987: T = gsl_multimin_fminimizer_nmsimplex;
5988: gsl_multimin_fminimizer *sfm = NULL;
5989: gsl_vector *ss, *x;
5990: gsl_multimin_function minex_func;
5991:
5992: /* Initial vertex size vector */
5993: ss = gsl_vector_alloc (NDIM);
5994:
5995: if (ss == NULL){
5996: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
5997: }
5998: /* Set all step sizes to 1 */
5999: gsl_vector_set_all (ss, 0.001);
6000:
6001: /* Starting point */
1.126 brouard 6002:
1.136 brouard 6003: x = gsl_vector_alloc (NDIM);
6004:
6005: if (x == NULL){
6006: gsl_vector_free(ss);
6007: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6008: }
6009:
6010: /* Initialize method and iterate */
6011: /* p[1]=0.0268; p[NDIM]=0.083; */
6012: /* gsl_vector_set(x, 0, 0.0268); */
6013: /* gsl_vector_set(x, 1, 0.083); */
6014: gsl_vector_set(x, 0, p[1]);
6015: gsl_vector_set(x, 1, p[2]);
6016:
6017: minex_func.f = &gompertz_f;
6018: minex_func.n = NDIM;
6019: minex_func.params = (void *)&p; /* ??? */
6020:
6021: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6022: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6023:
6024: printf("Iterations beginning .....\n\n");
6025: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6026:
6027: iteri=0;
6028: while (rval == GSL_CONTINUE){
6029: iteri++;
6030: status = gsl_multimin_fminimizer_iterate(sfm);
6031:
6032: if (status) printf("error: %s\n", gsl_strerror (status));
6033: fflush(0);
6034:
6035: if (status)
6036: break;
6037:
6038: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6039: ssval = gsl_multimin_fminimizer_size (sfm);
6040:
6041: if (rval == GSL_SUCCESS)
6042: printf ("converged to a local maximum at\n");
6043:
6044: printf("%5d ", iteri);
6045: for (it = 0; it < NDIM; it++){
6046: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6047: }
6048: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6049: }
6050:
6051: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6052:
6053: gsl_vector_free(x); /* initial values */
6054: gsl_vector_free(ss); /* inital step size */
6055: for (it=0; it<NDIM; it++){
6056: p[it+1]=gsl_vector_get(sfm->x,it);
6057: fprintf(ficrespow," %.12lf", p[it]);
6058: }
6059: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6060: #endif
6061: #ifdef POWELL
6062: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6063: #endif
1.126 brouard 6064: fclose(ficrespow);
6065:
6066: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6067:
6068: for(i=1; i <=NDIM; i++)
6069: for(j=i+1;j<=NDIM;j++)
6070: matcov[i][j]=matcov[j][i];
6071:
6072: printf("\nCovariance matrix\n ");
6073: for(i=1; i <=NDIM; i++) {
6074: for(j=1;j<=NDIM;j++){
6075: printf("%f ",matcov[i][j]);
6076: }
6077: printf("\n ");
6078: }
6079:
6080: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6081: for (i=1;i<=NDIM;i++)
6082: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6083:
6084: lsurv=vector(1,AGESUP);
6085: lpop=vector(1,AGESUP);
6086: tpop=vector(1,AGESUP);
6087: lsurv[agegomp]=100000;
6088:
6089: for (k=agegomp;k<=AGESUP;k++) {
6090: agemortsup=k;
6091: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6092: }
6093:
6094: for (k=agegomp;k<agemortsup;k++)
6095: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6096:
6097: for (k=agegomp;k<agemortsup;k++){
6098: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6099: sumlpop=sumlpop+lpop[k];
6100: }
6101:
6102: tpop[agegomp]=sumlpop;
6103: for (k=agegomp;k<(agemortsup-3);k++){
6104: /* tpop[k+1]=2;*/
6105: tpop[k+1]=tpop[k]-lpop[k];
6106: }
6107:
6108:
6109: printf("\nAge lx qx dx Lx Tx e(x)\n");
6110: for (k=agegomp;k<(agemortsup-2);k++)
6111: 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]);
6112:
6113:
6114: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6115: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6116:
6117: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6118: stepm, weightopt,\
6119: model,imx,p,matcov,agemortsup);
6120:
6121: free_vector(lsurv,1,AGESUP);
6122: free_vector(lpop,1,AGESUP);
6123: free_vector(tpop,1,AGESUP);
1.136 brouard 6124: #ifdef GSL
6125: free_ivector(cens,1,n);
6126: free_vector(agecens,1,n);
6127: free_ivector(dcwave,1,n);
6128: free_matrix(ximort,1,NDIM,1,NDIM);
6129: #endif
1.126 brouard 6130: } /* Endof if mle==-3 */
6131:
6132: else{ /* For mle >=1 */
1.132 brouard 6133: globpr=0;/* debug */
6134: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6135: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6136: for (k=1; k<=npar;k++)
6137: printf(" %d %8.5f",k,p[k]);
6138: printf("\n");
6139: globpr=1; /* to print the contributions */
6140: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6141: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6142: for (k=1; k<=npar;k++)
6143: printf(" %d %8.5f",k,p[k]);
6144: printf("\n");
6145: if(mle>=1){ /* Could be 1 or 2 */
6146: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6147: }
6148:
6149: /*--------- results files --------------*/
6150: 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);
6151:
6152:
6153: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6154: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6155: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6156: for(i=1,jk=1; i <=nlstate; i++){
6157: for(k=1; k <=(nlstate+ndeath); k++){
6158: if (k != i) {
6159: printf("%d%d ",i,k);
6160: fprintf(ficlog,"%d%d ",i,k);
6161: fprintf(ficres,"%1d%1d ",i,k);
6162: for(j=1; j <=ncovmodel; j++){
6163: printf("%lf ",p[jk]);
6164: fprintf(ficlog,"%lf ",p[jk]);
6165: fprintf(ficres,"%lf ",p[jk]);
6166: jk++;
6167: }
6168: printf("\n");
6169: fprintf(ficlog,"\n");
6170: fprintf(ficres,"\n");
6171: }
6172: }
6173: }
6174: if(mle!=0){
6175: /* Computing hessian and covariance matrix */
6176: ftolhess=ftol; /* Usually correct */
6177: hesscov(matcov, p, npar, delti, ftolhess, func);
6178: }
6179: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6180: printf("# Scales (for hessian or gradient estimation)\n");
6181: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6182: for(i=1,jk=1; i <=nlstate; i++){
6183: for(j=1; j <=nlstate+ndeath; j++){
6184: if (j!=i) {
6185: fprintf(ficres,"%1d%1d",i,j);
6186: printf("%1d%1d",i,j);
6187: fprintf(ficlog,"%1d%1d",i,j);
6188: for(k=1; k<=ncovmodel;k++){
6189: printf(" %.5e",delti[jk]);
6190: fprintf(ficlog," %.5e",delti[jk]);
6191: fprintf(ficres," %.5e",delti[jk]);
6192: jk++;
6193: }
6194: printf("\n");
6195: fprintf(ficlog,"\n");
6196: fprintf(ficres,"\n");
6197: }
6198: }
6199: }
6200:
6201: 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");
6202: if(mle>=1)
6203: 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");
6204: 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");
6205: /* # 121 Var(a12)\n\ */
6206: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6207: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6208: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6209: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6210: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6211: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6212: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6213:
6214:
6215: /* Just to have a covariance matrix which will be more understandable
6216: even is we still don't want to manage dictionary of variables
6217: */
6218: for(itimes=1;itimes<=2;itimes++){
6219: jj=0;
6220: for(i=1; i <=nlstate; i++){
6221: for(j=1; j <=nlstate+ndeath; j++){
6222: if(j==i) continue;
6223: for(k=1; k<=ncovmodel;k++){
6224: jj++;
6225: ca[0]= k+'a'-1;ca[1]='\0';
6226: if(itimes==1){
6227: if(mle>=1)
6228: printf("#%1d%1d%d",i,j,k);
6229: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6230: fprintf(ficres,"#%1d%1d%d",i,j,k);
6231: }else{
6232: if(mle>=1)
6233: printf("%1d%1d%d",i,j,k);
6234: fprintf(ficlog,"%1d%1d%d",i,j,k);
6235: fprintf(ficres,"%1d%1d%d",i,j,k);
6236: }
6237: ll=0;
6238: for(li=1;li <=nlstate; li++){
6239: for(lj=1;lj <=nlstate+ndeath; lj++){
6240: if(lj==li) continue;
6241: for(lk=1;lk<=ncovmodel;lk++){
6242: ll++;
6243: if(ll<=jj){
6244: cb[0]= lk +'a'-1;cb[1]='\0';
6245: if(ll<jj){
6246: if(itimes==1){
6247: if(mle>=1)
6248: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6249: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6250: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6251: }else{
6252: if(mle>=1)
6253: printf(" %.5e",matcov[jj][ll]);
6254: fprintf(ficlog," %.5e",matcov[jj][ll]);
6255: fprintf(ficres," %.5e",matcov[jj][ll]);
6256: }
6257: }else{
6258: if(itimes==1){
6259: if(mle>=1)
6260: printf(" Var(%s%1d%1d)",ca,i,j);
6261: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6262: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6263: }else{
6264: if(mle>=1)
6265: printf(" %.5e",matcov[jj][ll]);
6266: fprintf(ficlog," %.5e",matcov[jj][ll]);
6267: fprintf(ficres," %.5e",matcov[jj][ll]);
6268: }
6269: }
6270: }
6271: } /* end lk */
6272: } /* end lj */
6273: } /* end li */
6274: if(mle>=1)
6275: printf("\n");
6276: fprintf(ficlog,"\n");
6277: fprintf(ficres,"\n");
6278: numlinepar++;
6279: } /* end k*/
6280: } /*end j */
6281: } /* end i */
6282: } /* end itimes */
6283:
6284: fflush(ficlog);
6285: fflush(ficres);
6286:
6287: while((c=getc(ficpar))=='#' && c!= EOF){
6288: ungetc(c,ficpar);
6289: fgets(line, MAXLINE, ficpar);
1.141 brouard 6290: fputs(line,stdout);
1.126 brouard 6291: fputs(line,ficparo);
6292: }
6293: ungetc(c,ficpar);
6294:
6295: estepm=0;
6296: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6297: if (estepm==0 || estepm < stepm) estepm=stepm;
6298: if (fage <= 2) {
6299: bage = ageminpar;
6300: fage = agemaxpar;
6301: }
6302:
6303: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6304: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6305: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6306:
6307: while((c=getc(ficpar))=='#' && c!= EOF){
6308: ungetc(c,ficpar);
6309: fgets(line, MAXLINE, ficpar);
1.141 brouard 6310: fputs(line,stdout);
1.126 brouard 6311: fputs(line,ficparo);
6312: }
6313: ungetc(c,ficpar);
6314:
6315: 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);
6316: 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);
6317: 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);
6318: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6319: 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);
6320:
6321: while((c=getc(ficpar))=='#' && c!= EOF){
6322: ungetc(c,ficpar);
6323: fgets(line, MAXLINE, ficpar);
1.141 brouard 6324: fputs(line,stdout);
1.126 brouard 6325: fputs(line,ficparo);
6326: }
6327: ungetc(c,ficpar);
6328:
6329:
6330: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6331: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6332:
6333: fscanf(ficpar,"pop_based=%d\n",&popbased);
6334: fprintf(ficparo,"pop_based=%d\n",popbased);
6335: fprintf(ficres,"pop_based=%d\n",popbased);
6336:
6337: while((c=getc(ficpar))=='#' && c!= EOF){
6338: ungetc(c,ficpar);
6339: fgets(line, MAXLINE, ficpar);
1.141 brouard 6340: fputs(line,stdout);
1.126 brouard 6341: fputs(line,ficparo);
6342: }
6343: ungetc(c,ficpar);
6344:
6345: 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);
6346: 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);
6347: 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);
6348: 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);
6349: 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);
6350: /* day and month of proj2 are not used but only year anproj2.*/
6351:
6352:
6353:
1.145 brouard 6354: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6355: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6356:
6357: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6358: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6359:
6360: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6361: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6362: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6363:
6364: /*------------ free_vector -------------*/
6365: /* chdir(path); */
6366:
6367: free_ivector(wav,1,imx);
6368: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6369: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6370: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6371: free_lvector(num,1,n);
6372: free_vector(agedc,1,n);
6373: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6374: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6375: fclose(ficparo);
6376: fclose(ficres);
6377:
6378:
6379: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6380: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6381: fclose(ficrespl);
6382:
1.145 brouard 6383: #ifdef FREEEXIT2
6384: #include "freeexit2.h"
6385: #endif
6386:
1.126 brouard 6387: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6388: #include "hpijx.h"
6389: fclose(ficrespij);
1.126 brouard 6390:
1.145 brouard 6391: /*-------------- Variance of one-step probabilities---*/
6392: k=1;
1.126 brouard 6393: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6394:
6395:
6396: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6397: for(i=1;i<=AGESUP;i++)
6398: for(j=1;j<=NCOVMAX;j++)
6399: for(k=1;k<=NCOVMAX;k++)
6400: probs[i][j][k]=0.;
6401:
6402: /*---------- Forecasting ------------------*/
6403: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6404: if(prevfcast==1){
6405: /* if(stepm ==1){*/
6406: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6407: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6408: /* } */
6409: /* else{ */
6410: /* erreur=108; */
6411: /* 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); */
6412: /* 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); */
6413: /* } */
6414: }
6415:
6416:
1.127 brouard 6417: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6418:
6419: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6420: /* 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",\
6421: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6422: */
1.126 brouard 6423:
1.127 brouard 6424: if (mobilav!=0) {
6425: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6426: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6427: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6428: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6429: }
1.126 brouard 6430: }
6431:
6432:
1.127 brouard 6433: /*---------- Health expectancies, no variances ------------*/
6434:
1.126 brouard 6435: strcpy(filerese,"e");
6436: strcat(filerese,fileres);
6437: if((ficreseij=fopen(filerese,"w"))==NULL) {
6438: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6439: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6440: }
6441: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6442: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6443: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6444: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6445:
6446: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6447: fprintf(ficreseij,"\n#****** ");
6448: for(j=1;j<=cptcoveff;j++) {
6449: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6450: }
6451: fprintf(ficreseij,"******\n");
6452:
6453: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6454: oldm=oldms;savm=savms;
6455: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6456:
6457: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6458: /*}*/
1.127 brouard 6459: }
6460: fclose(ficreseij);
6461:
6462:
6463: /*---------- Health expectancies and variances ------------*/
6464:
6465:
6466: strcpy(filerest,"t");
6467: strcat(filerest,fileres);
6468: if((ficrest=fopen(filerest,"w"))==NULL) {
6469: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6470: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6471: }
6472: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6473: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6474:
1.126 brouard 6475:
6476: strcpy(fileresstde,"stde");
6477: strcat(fileresstde,fileres);
6478: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6479: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6480: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6481: }
6482: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6483: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6484:
6485: strcpy(filerescve,"cve");
6486: strcat(filerescve,fileres);
6487: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6488: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6489: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6490: }
6491: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6492: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6493:
6494: strcpy(fileresv,"v");
6495: strcat(fileresv,fileres);
6496: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6497: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6498: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6499: }
6500: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6501: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6502:
1.145 brouard 6503: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6504: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6505:
6506: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6507: fprintf(ficrest,"\n#****** ");
1.126 brouard 6508: for(j=1;j<=cptcoveff;j++)
6509: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6510: fprintf(ficrest,"******\n");
6511:
6512: fprintf(ficresstdeij,"\n#****** ");
6513: fprintf(ficrescveij,"\n#****** ");
6514: for(j=1;j<=cptcoveff;j++) {
6515: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6516: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6517: }
6518: fprintf(ficresstdeij,"******\n");
6519: fprintf(ficrescveij,"******\n");
6520:
6521: fprintf(ficresvij,"\n#****** ");
6522: for(j=1;j<=cptcoveff;j++)
6523: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6524: fprintf(ficresvij,"******\n");
6525:
6526: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6527: oldm=oldms;savm=savms;
1.127 brouard 6528: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6529: /*
6530: */
6531: /* goto endfree; */
1.126 brouard 6532:
6533: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6534: pstamp(ficrest);
1.145 brouard 6535:
6536:
1.128 brouard 6537: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6538: oldm=oldms;savm=savms; /* Segmentation fault */
6539: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);
6540: 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 6541: if(vpopbased==1)
6542: 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);
6543: else
6544: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6545: fprintf(ficrest,"# Age e.. (std) ");
6546: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6547: fprintf(ficrest,"\n");
1.126 brouard 6548:
1.128 brouard 6549: epj=vector(1,nlstate+1);
6550: for(age=bage; age <=fage ;age++){
6551: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6552: if (vpopbased==1) {
6553: if(mobilav ==0){
6554: for(i=1; i<=nlstate;i++)
6555: prlim[i][i]=probs[(int)age][i][k];
6556: }else{ /* mobilav */
6557: for(i=1; i<=nlstate;i++)
6558: prlim[i][i]=mobaverage[(int)age][i][k];
6559: }
1.126 brouard 6560: }
6561:
1.128 brouard 6562: fprintf(ficrest," %4.0f",age);
6563: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6564: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6565: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6566: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6567: }
6568: epj[nlstate+1] +=epj[j];
1.126 brouard 6569: }
6570:
1.128 brouard 6571: for(i=1, vepp=0.;i <=nlstate;i++)
6572: for(j=1;j <=nlstate;j++)
6573: vepp += vareij[i][j][(int)age];
6574: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6575: for(j=1;j <=nlstate;j++){
6576: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6577: }
6578: fprintf(ficrest,"\n");
1.126 brouard 6579: }
6580: }
6581: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6582: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6583: free_vector(epj,1,nlstate+1);
1.145 brouard 6584: /*}*/
1.126 brouard 6585: }
6586: free_vector(weight,1,n);
1.145 brouard 6587: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6588: free_imatrix(s,1,maxwav+1,1,n);
6589: free_matrix(anint,1,maxwav,1,n);
6590: free_matrix(mint,1,maxwav,1,n);
6591: free_ivector(cod,1,n);
6592: free_ivector(tab,1,NCOVMAX);
6593: fclose(ficresstdeij);
6594: fclose(ficrescveij);
6595: fclose(ficresvij);
6596: fclose(ficrest);
6597: fclose(ficpar);
6598:
6599: /*------- Variance of period (stable) prevalence------*/
6600:
6601: strcpy(fileresvpl,"vpl");
6602: strcat(fileresvpl,fileres);
6603: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6604: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6605: exit(0);
6606: }
6607: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6608:
1.145 brouard 6609: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6610: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6611:
6612: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6613: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6614: for(j=1;j<=cptcoveff;j++)
6615: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6616: fprintf(ficresvpl,"******\n");
6617:
6618: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6619: oldm=oldms;savm=savms;
6620: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6621: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6622: /*}*/
1.126 brouard 6623: }
6624:
6625: fclose(ficresvpl);
6626:
6627: /*---------- End : free ----------------*/
6628: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6629: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6630: } /* mle==-3 arrives here for freeing */
1.131 brouard 6631: endfree:
1.141 brouard 6632: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6633: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6634: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6635: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6636: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6637: free_matrix(covar,0,NCOVMAX,1,n);
6638: free_matrix(matcov,1,npar,1,npar);
6639: /*free_vector(delti,1,npar);*/
6640: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6641: free_matrix(agev,1,maxwav,1,imx);
6642: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6643:
1.145 brouard 6644: free_ivector(ncodemax,1,NCOVMAX);
6645: free_ivector(Tvar,1,NCOVMAX);
6646: free_ivector(Tprod,1,NCOVMAX);
6647: free_ivector(Tvaraff,1,NCOVMAX);
6648: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6649:
6650: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6651: free_imatrix(codtab,1,100,1,10);
6652: fflush(fichtm);
6653: fflush(ficgp);
6654:
6655:
6656: if((nberr >0) || (nbwarn>0)){
6657: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6658: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6659: }else{
6660: printf("End of Imach\n");
6661: fprintf(ficlog,"End of Imach\n");
6662: }
6663: printf("See log file on %s\n",filelog);
6664: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6665: /*(void) gettimeofday(&end_time,&tzp);*/
6666: rend_time = time(NULL);
6667: end_time = *localtime(&rend_time);
6668: /* tml = *localtime(&end_time.tm_sec); */
6669: strcpy(strtend,asctime(&end_time));
1.126 brouard 6670: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6671: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6672: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6673:
1.157 brouard 6674: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6675: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6676: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6677: /* printf("Total time was %d uSec.\n", total_usecs);*/
6678: /* if(fileappend(fichtm,optionfilehtm)){ */
6679: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6680: fclose(fichtm);
6681: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6682: fclose(fichtmcov);
6683: fclose(ficgp);
6684: fclose(ficlog);
6685: /*------ End -----------*/
6686:
6687:
6688: printf("Before Current directory %s!\n",pathcd);
6689: if(chdir(pathcd) != 0)
6690: printf("Can't move to directory %s!\n",path);
6691: if(getcwd(pathcd,MAXLINE) > 0)
6692: printf("Current directory %s!\n",pathcd);
6693: /*strcat(plotcmd,CHARSEPARATOR);*/
6694: sprintf(plotcmd,"gnuplot");
1.157 brouard 6695: #ifdef _WIN32
1.126 brouard 6696: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6697: #endif
6698: if(!stat(plotcmd,&info)){
1.158 ! brouard 6699: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6700: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 ! brouard 6701: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6702: }else
6703: strcpy(pplotcmd,plotcmd);
1.157 brouard 6704: #ifdef __unix
1.126 brouard 6705: strcpy(plotcmd,GNUPLOTPROGRAM);
6706: if(!stat(plotcmd,&info)){
1.158 ! brouard 6707: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6708: }else
6709: strcpy(pplotcmd,plotcmd);
6710: #endif
6711: }else
6712: strcpy(pplotcmd,plotcmd);
6713:
6714: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 ! brouard 6715: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6716:
6717: if((outcmd=system(plotcmd)) != 0){
1.158 ! brouard 6718: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6719: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6720: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6721: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6722: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6723: }
1.158 ! brouard 6724: printf(" Successful, please wait...");
1.126 brouard 6725: while (z[0] != 'q') {
6726: /* chdir(path); */
1.154 brouard 6727: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6728: scanf("%s",z);
6729: /* if (z[0] == 'c') system("./imach"); */
6730: if (z[0] == 'e') {
1.158 ! brouard 6731: #ifdef __APPLE__
1.152 brouard 6732: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6733: #elif __linux
6734: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6735: #else
1.152 brouard 6736: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6737: #endif
6738: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6739: system(pplotcmd);
1.126 brouard 6740: }
6741: else if (z[0] == 'g') system(plotcmd);
6742: else if (z[0] == 'q') exit(0);
6743: }
6744: end:
6745: while (z[0] != 'q') {
6746: printf("\nType q for exiting: ");
6747: scanf("%s",z);
6748: }
6749: }
6750:
6751:
6752:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>