Annotation of imach/src/imach.c, revision 1.161
1.161 ! brouard 1: /* $Id: imach.c,v 1.160 2014/09/02 09:24:05 brouard Exp $
1.126 brouard 2: $State: Exp $
3: $Log: imach.c,v $
1.161 ! brouard 4: Revision 1.160 2014/09/02 09:24:05 brouard
! 5: *** empty log message ***
! 6:
1.160 brouard 7: Revision 1.159 2014/09/01 10:34:10 brouard
8: Summary: WIN32
9: Author: Brouard
10:
1.159 brouard 11: Revision 1.158 2014/08/27 17:11:51 brouard
12: *** empty log message ***
13:
1.158 brouard 14: Revision 1.157 2014/08/27 16:26:55 brouard
15: Summary: Preparing windows Visual studio version
16: Author: Brouard
17:
18: In order to compile on Visual studio, time.h is now correct and time_t
19: and tm struct should be used. difftime should be used but sometimes I
20: just make the differences in raw time format (time(&now).
21: Trying to suppress #ifdef LINUX
22: Add xdg-open for __linux in order to open default browser.
23:
1.157 brouard 24: Revision 1.156 2014/08/25 20:10:10 brouard
25: *** empty log message ***
26:
1.156 brouard 27: Revision 1.155 2014/08/25 18:32:34 brouard
28: Summary: New compile, minor changes
29: Author: Brouard
30:
1.155 brouard 31: Revision 1.154 2014/06/20 17:32:08 brouard
32: Summary: Outputs now all graphs of convergence to period prevalence
33:
1.154 brouard 34: Revision 1.153 2014/06/20 16:45:46 brouard
35: Summary: If 3 live state, convergence to period prevalence on same graph
36: Author: Brouard
37:
1.153 brouard 38: Revision 1.152 2014/06/18 17:54:09 brouard
39: Summary: open browser, use gnuplot on same dir than imach if not found in the path
40:
1.152 brouard 41: Revision 1.151 2014/06/18 16:43:30 brouard
42: *** empty log message ***
43:
1.151 brouard 44: Revision 1.150 2014/06/18 16:42:35 brouard
45: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
46: Author: brouard
47:
1.150 brouard 48: Revision 1.149 2014/06/18 15:51:14 brouard
49: Summary: Some fixes in parameter files errors
50: Author: Nicolas Brouard
51:
1.149 brouard 52: Revision 1.148 2014/06/17 17:38:48 brouard
53: Summary: Nothing new
54: Author: Brouard
55:
56: Just a new packaging for OS/X version 0.98nS
57:
1.148 brouard 58: Revision 1.147 2014/06/16 10:33:11 brouard
59: *** empty log message ***
60:
1.147 brouard 61: Revision 1.146 2014/06/16 10:20:28 brouard
62: Summary: Merge
63: Author: Brouard
64:
65: Merge, before building revised version.
66:
1.146 brouard 67: Revision 1.145 2014/06/10 21:23:15 brouard
68: Summary: Debugging with valgrind
69: Author: Nicolas Brouard
70:
71: Lot of changes in order to output the results with some covariates
72: After the Edimburgh REVES conference 2014, it seems mandatory to
73: improve the code.
74: No more memory valgrind error but a lot has to be done in order to
75: continue the work of splitting the code into subroutines.
76: Also, decodemodel has been improved. Tricode is still not
77: optimal. nbcode should be improved. Documentation has been added in
78: the source code.
79:
1.144 brouard 80: Revision 1.143 2014/01/26 09:45:38 brouard
81: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
82:
83: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
84: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
85:
1.143 brouard 86: Revision 1.142 2014/01/26 03:57:36 brouard
87: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
88:
89: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
90:
1.142 brouard 91: Revision 1.141 2014/01/26 02:42:01 brouard
92: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
93:
1.141 brouard 94: Revision 1.140 2011/09/02 10:37:54 brouard
95: Summary: times.h is ok with mingw32 now.
96:
1.140 brouard 97: Revision 1.139 2010/06/14 07:50:17 brouard
98: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
99: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
100:
1.139 brouard 101: Revision 1.138 2010/04/30 18:19:40 brouard
102: *** empty log message ***
103:
1.138 brouard 104: Revision 1.137 2010/04/29 18:11:38 brouard
105: (Module): Checking covariates for more complex models
106: than V1+V2. A lot of change to be done. Unstable.
107:
1.137 brouard 108: Revision 1.136 2010/04/26 20:30:53 brouard
109: (Module): merging some libgsl code. Fixing computation
110: of likelione (using inter/intrapolation if mle = 0) in order to
111: get same likelihood as if mle=1.
112: Some cleaning of code and comments added.
113:
1.136 brouard 114: Revision 1.135 2009/10/29 15:33:14 brouard
115: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
116:
1.135 brouard 117: Revision 1.134 2009/10/29 13:18:53 brouard
118: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
119:
1.134 brouard 120: Revision 1.133 2009/07/06 10:21:25 brouard
121: just nforces
122:
1.133 brouard 123: Revision 1.132 2009/07/06 08:22:05 brouard
124: Many tings
125:
1.132 brouard 126: Revision 1.131 2009/06/20 16:22:47 brouard
127: Some dimensions resccaled
128:
1.131 brouard 129: Revision 1.130 2009/05/26 06:44:34 brouard
130: (Module): Max Covariate is now set to 20 instead of 8. A
131: lot of cleaning with variables initialized to 0. Trying to make
132: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
133:
1.130 brouard 134: Revision 1.129 2007/08/31 13:49:27 lievre
135: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
136:
1.129 lievre 137: Revision 1.128 2006/06/30 13:02:05 brouard
138: (Module): Clarifications on computing e.j
139:
1.128 brouard 140: Revision 1.127 2006/04/28 18:11:50 brouard
141: (Module): Yes the sum of survivors was wrong since
142: imach-114 because nhstepm was no more computed in the age
143: loop. Now we define nhstepma in the age loop.
144: (Module): In order to speed up (in case of numerous covariates) we
145: compute health expectancies (without variances) in a first step
146: and then all the health expectancies with variances or standard
147: deviation (needs data from the Hessian matrices) which slows the
148: computation.
149: In the future we should be able to stop the program is only health
150: expectancies and graph are needed without standard deviations.
151:
1.127 brouard 152: Revision 1.126 2006/04/28 17:23:28 brouard
153: (Module): Yes the sum of survivors was wrong since
154: imach-114 because nhstepm was no more computed in the age
155: loop. Now we define nhstepma in the age loop.
156: Version 0.98h
157:
1.126 brouard 158: Revision 1.125 2006/04/04 15:20:31 lievre
159: Errors in calculation of health expectancies. Age was not initialized.
160: Forecasting file added.
161:
162: Revision 1.124 2006/03/22 17:13:53 lievre
163: Parameters are printed with %lf instead of %f (more numbers after the comma).
164: The log-likelihood is printed in the log file
165:
166: Revision 1.123 2006/03/20 10:52:43 brouard
167: * imach.c (Module): <title> changed, corresponds to .htm file
168: name. <head> headers where missing.
169:
170: * imach.c (Module): Weights can have a decimal point as for
171: English (a comma might work with a correct LC_NUMERIC environment,
172: otherwise the weight is truncated).
173: Modification of warning when the covariates values are not 0 or
174: 1.
175: Version 0.98g
176:
177: Revision 1.122 2006/03/20 09:45:41 brouard
178: (Module): Weights can have a decimal point as for
179: English (a comma might work with a correct LC_NUMERIC environment,
180: otherwise the weight is truncated).
181: Modification of warning when the covariates values are not 0 or
182: 1.
183: Version 0.98g
184:
185: Revision 1.121 2006/03/16 17:45:01 lievre
186: * imach.c (Module): Comments concerning covariates added
187:
188: * imach.c (Module): refinements in the computation of lli if
189: status=-2 in order to have more reliable computation if stepm is
190: not 1 month. Version 0.98f
191:
192: Revision 1.120 2006/03/16 15:10:38 lievre
193: (Module): refinements in the computation of lli if
194: status=-2 in order to have more reliable computation if stepm is
195: not 1 month. Version 0.98f
196:
197: Revision 1.119 2006/03/15 17:42:26 brouard
198: (Module): Bug if status = -2, the loglikelihood was
199: computed as likelihood omitting the logarithm. Version O.98e
200:
201: Revision 1.118 2006/03/14 18:20:07 brouard
202: (Module): varevsij Comments added explaining the second
203: table of variances if popbased=1 .
204: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
205: (Module): Function pstamp added
206: (Module): Version 0.98d
207:
208: Revision 1.117 2006/03/14 17:16:22 brouard
209: (Module): varevsij Comments added explaining the second
210: table of variances if popbased=1 .
211: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
212: (Module): Function pstamp added
213: (Module): Version 0.98d
214:
215: Revision 1.116 2006/03/06 10:29:27 brouard
216: (Module): Variance-covariance wrong links and
217: varian-covariance of ej. is needed (Saito).
218:
219: Revision 1.115 2006/02/27 12:17:45 brouard
220: (Module): One freematrix added in mlikeli! 0.98c
221:
222: Revision 1.114 2006/02/26 12:57:58 brouard
223: (Module): Some improvements in processing parameter
224: filename with strsep.
225:
226: Revision 1.113 2006/02/24 14:20:24 brouard
227: (Module): Memory leaks checks with valgrind and:
228: datafile was not closed, some imatrix were not freed and on matrix
229: allocation too.
230:
231: Revision 1.112 2006/01/30 09:55:26 brouard
232: (Module): Back to gnuplot.exe instead of wgnuplot.exe
233:
234: Revision 1.111 2006/01/25 20:38:18 brouard
235: (Module): Lots of cleaning and bugs added (Gompertz)
236: (Module): Comments can be added in data file. Missing date values
237: can be a simple dot '.'.
238:
239: Revision 1.110 2006/01/25 00:51:50 brouard
240: (Module): Lots of cleaning and bugs added (Gompertz)
241:
242: Revision 1.109 2006/01/24 19:37:15 brouard
243: (Module): Comments (lines starting with a #) are allowed in data.
244:
245: Revision 1.108 2006/01/19 18:05:42 lievre
246: Gnuplot problem appeared...
247: To be fixed
248:
249: Revision 1.107 2006/01/19 16:20:37 brouard
250: Test existence of gnuplot in imach path
251:
252: Revision 1.106 2006/01/19 13:24:36 brouard
253: Some cleaning and links added in html output
254:
255: Revision 1.105 2006/01/05 20:23:19 lievre
256: *** empty log message ***
257:
258: Revision 1.104 2005/09/30 16:11:43 lievre
259: (Module): sump fixed, loop imx fixed, and simplifications.
260: (Module): If the status is missing at the last wave but we know
261: that the person is alive, then we can code his/her status as -2
262: (instead of missing=-1 in earlier versions) and his/her
263: contributions to the likelihood is 1 - Prob of dying from last
264: health status (= 1-p13= p11+p12 in the easiest case of somebody in
265: the healthy state at last known wave). Version is 0.98
266:
267: Revision 1.103 2005/09/30 15:54:49 lievre
268: (Module): sump fixed, loop imx fixed, and simplifications.
269:
270: Revision 1.102 2004/09/15 17:31:30 brouard
271: Add the possibility to read data file including tab characters.
272:
273: Revision 1.101 2004/09/15 10:38:38 brouard
274: Fix on curr_time
275:
276: Revision 1.100 2004/07/12 18:29:06 brouard
277: Add version for Mac OS X. Just define UNIX in Makefile
278:
279: Revision 1.99 2004/06/05 08:57:40 brouard
280: *** empty log message ***
281:
282: Revision 1.98 2004/05/16 15:05:56 brouard
283: New version 0.97 . First attempt to estimate force of mortality
284: directly from the data i.e. without the need of knowing the health
285: state at each age, but using a Gompertz model: log u =a + b*age .
286: This is the basic analysis of mortality and should be done before any
287: other analysis, in order to test if the mortality estimated from the
288: cross-longitudinal survey is different from the mortality estimated
289: from other sources like vital statistic data.
290:
291: The same imach parameter file can be used but the option for mle should be -3.
292:
1.133 brouard 293: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 294: former routines in order to include the new code within the former code.
295:
296: The output is very simple: only an estimate of the intercept and of
297: the slope with 95% confident intervals.
298:
299: Current limitations:
300: A) Even if you enter covariates, i.e. with the
301: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
302: B) There is no computation of Life Expectancy nor Life Table.
303:
304: Revision 1.97 2004/02/20 13:25:42 lievre
305: Version 0.96d. Population forecasting command line is (temporarily)
306: suppressed.
307:
308: Revision 1.96 2003/07/15 15:38:55 brouard
309: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
310: rewritten within the same printf. Workaround: many printfs.
311:
312: Revision 1.95 2003/07/08 07:54:34 brouard
313: * imach.c (Repository):
314: (Repository): Using imachwizard code to output a more meaningful covariance
315: matrix (cov(a12,c31) instead of numbers.
316:
317: Revision 1.94 2003/06/27 13:00:02 brouard
318: Just cleaning
319:
320: Revision 1.93 2003/06/25 16:33:55 brouard
321: (Module): On windows (cygwin) function asctime_r doesn't
322: exist so I changed back to asctime which exists.
323: (Module): Version 0.96b
324:
325: Revision 1.92 2003/06/25 16:30:45 brouard
326: (Module): On windows (cygwin) function asctime_r doesn't
327: exist so I changed back to asctime which exists.
328:
329: Revision 1.91 2003/06/25 15:30:29 brouard
330: * imach.c (Repository): Duplicated warning errors corrected.
331: (Repository): Elapsed time after each iteration is now output. It
332: helps to forecast when convergence will be reached. Elapsed time
333: is stamped in powell. We created a new html file for the graphs
334: concerning matrix of covariance. It has extension -cov.htm.
335:
336: Revision 1.90 2003/06/24 12:34:15 brouard
337: (Module): Some bugs corrected for windows. Also, when
338: mle=-1 a template is output in file "or"mypar.txt with the design
339: of the covariance matrix to be input.
340:
341: Revision 1.89 2003/06/24 12:30:52 brouard
342: (Module): Some bugs corrected for windows. Also, when
343: mle=-1 a template is output in file "or"mypar.txt with the design
344: of the covariance matrix to be input.
345:
346: Revision 1.88 2003/06/23 17:54:56 brouard
347: * 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.
348:
349: Revision 1.87 2003/06/18 12:26:01 brouard
350: Version 0.96
351:
352: Revision 1.86 2003/06/17 20:04:08 brouard
353: (Module): Change position of html and gnuplot routines and added
354: routine fileappend.
355:
356: Revision 1.85 2003/06/17 13:12:43 brouard
357: * imach.c (Repository): Check when date of death was earlier that
358: current date of interview. It may happen when the death was just
359: prior to the death. In this case, dh was negative and likelihood
360: was wrong (infinity). We still send an "Error" but patch by
361: assuming that the date of death was just one stepm after the
362: interview.
363: (Repository): Because some people have very long ID (first column)
364: we changed int to long in num[] and we added a new lvector for
365: memory allocation. But we also truncated to 8 characters (left
366: truncation)
367: (Repository): No more line truncation errors.
368:
369: Revision 1.84 2003/06/13 21:44:43 brouard
370: * imach.c (Repository): Replace "freqsummary" at a correct
371: place. It differs from routine "prevalence" which may be called
372: many times. Probs is memory consuming and must be used with
373: parcimony.
374: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
375:
376: Revision 1.83 2003/06/10 13:39:11 lievre
377: *** empty log message ***
378:
379: Revision 1.82 2003/06/05 15:57:20 brouard
380: Add log in imach.c and fullversion number is now printed.
381:
382: */
383: /*
384: Interpolated Markov Chain
385:
386: Short summary of the programme:
387:
388: This program computes Healthy Life Expectancies from
389: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
390: first survey ("cross") where individuals from different ages are
391: interviewed on their health status or degree of disability (in the
392: case of a health survey which is our main interest) -2- at least a
393: second wave of interviews ("longitudinal") which measure each change
394: (if any) in individual health status. Health expectancies are
395: computed from the time spent in each health state according to a
396: model. More health states you consider, more time is necessary to reach the
397: Maximum Likelihood of the parameters involved in the model. The
398: simplest model is the multinomial logistic model where pij is the
399: probability to be observed in state j at the second wave
400: conditional to be observed in state i at the first wave. Therefore
401: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
402: 'age' is age and 'sex' is a covariate. If you want to have a more
403: complex model than "constant and age", you should modify the program
404: where the markup *Covariates have to be included here again* invites
405: you to do it. More covariates you add, slower the
406: convergence.
407:
408: The advantage of this computer programme, compared to a simple
409: multinomial logistic model, is clear when the delay between waves is not
410: identical for each individual. Also, if a individual missed an
411: intermediate interview, the information is lost, but taken into
412: account using an interpolation or extrapolation.
413:
414: hPijx is the probability to be observed in state i at age x+h
415: conditional to the observed state i at age x. The delay 'h' can be
416: split into an exact number (nh*stepm) of unobserved intermediate
417: states. This elementary transition (by month, quarter,
418: semester or year) is modelled as a multinomial logistic. The hPx
419: matrix is simply the matrix product of nh*stepm elementary matrices
420: and the contribution of each individual to the likelihood is simply
421: hPijx.
422:
423: Also this programme outputs the covariance matrix of the parameters but also
424: of the life expectancies. It also computes the period (stable) prevalence.
425:
1.133 brouard 426: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
427: Institut national d'études démographiques, Paris.
1.126 brouard 428: This software have been partly granted by Euro-REVES, a concerted action
429: from the European Union.
430: It is copyrighted identically to a GNU software product, ie programme and
431: software can be distributed freely for non commercial use. Latest version
432: can be accessed at http://euroreves.ined.fr/imach .
433:
434: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
435: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
436:
437: **********************************************************************/
438: /*
439: main
440: read parameterfile
441: read datafile
442: concatwav
443: freqsummary
444: if (mle >= 1)
445: mlikeli
446: print results files
447: if mle==1
448: computes hessian
449: read end of parameter file: agemin, agemax, bage, fage, estepm
450: begin-prev-date,...
451: open gnuplot file
452: open html file
1.145 brouard 453: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
454: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
455: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
456: freexexit2 possible for memory heap.
457:
458: h Pij x | pij_nom ficrestpij
459: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
460: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
461: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
462:
463: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
464: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
465: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
466: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
467: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
468:
1.126 brouard 469: forecasting if prevfcast==1 prevforecast call prevalence()
470: health expectancies
471: Variance-covariance of DFLE
472: prevalence()
473: movingaverage()
474: varevsij()
475: if popbased==1 varevsij(,popbased)
476: total life expectancies
477: Variance of period (stable) prevalence
478: end
479: */
480:
481:
482:
483:
484: #include <math.h>
485: #include <stdio.h>
486: #include <stdlib.h>
487: #include <string.h>
1.159 brouard 488:
489: #ifdef _WIN32
490: #include <io.h>
491: #else
1.126 brouard 492: #include <unistd.h>
1.159 brouard 493: #endif
1.126 brouard 494:
495: #include <limits.h>
496: #include <sys/types.h>
497: #include <sys/stat.h>
498: #include <errno.h>
1.159 brouard 499: /* extern int errno; */
1.126 brouard 500:
1.157 brouard 501: /* #ifdef LINUX */
502: /* #include <time.h> */
503: /* #include "timeval.h" */
504: /* #else */
505: /* #include <sys/time.h> */
506: /* #endif */
507:
1.126 brouard 508: #include <time.h>
509:
1.136 brouard 510: #ifdef GSL
511: #include <gsl/gsl_errno.h>
512: #include <gsl/gsl_multimin.h>
513: #endif
514:
1.126 brouard 515: /* #include <libintl.h> */
516: /* #define _(String) gettext (String) */
517:
1.141 brouard 518: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 519:
520: #define GNUPLOTPROGRAM "gnuplot"
521: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
522: #define FILENAMELENGTH 132
523:
524: #define GLOCK_ERROR_NOPATH -1 /* empty path */
525: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
526:
1.144 brouard 527: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
528: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 529:
530: #define NINTERVMAX 8
1.144 brouard 531: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
532: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
533: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 534: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 535: #define MAXN 20000
1.144 brouard 536: #define YEARM 12. /**< Number of months per year */
1.126 brouard 537: #define AGESUP 130
538: #define AGEBASE 40
1.144 brouard 539: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.157 brouard 540: #ifdef _WIN32
541: #define DIRSEPARATOR '\\'
542: #define CHARSEPARATOR "\\"
543: #define ODIRSEPARATOR '/'
544: #else
1.126 brouard 545: #define DIRSEPARATOR '/'
546: #define CHARSEPARATOR "/"
547: #define ODIRSEPARATOR '\\'
548: #endif
549:
1.161 ! brouard 550: /* $Id: imach.c,v 1.160 2014/09/02 09:24:05 brouard Exp $ */
1.126 brouard 551: /* $State: Exp $ */
552:
1.157 brouard 553: 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.161 ! brouard 554: char fullversion[]="$Revision: 1.160 $ $Date: 2014/09/02 09:24:05 $";
1.126 brouard 555: char strstart[80];
556: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 557: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 558: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 559: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
560: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
561: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
562: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
563: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
564: int cptcovprodnoage=0; /**< Number of covariate products without age */
565: int cptcoveff=0; /* Total number of covariates to vary for printing results */
566: int cptcov=0; /* Working variable */
1.126 brouard 567: int npar=NPARMAX;
568: int nlstate=2; /* Number of live states */
569: int ndeath=1; /* Number of dead states */
1.130 brouard 570: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 571: int popbased=0;
572:
573: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 574: int maxwav=0; /* Maxim number of waves */
575: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
576: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
577: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 578: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 579: int mle=1, weightopt=0;
1.126 brouard 580: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
581: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
582: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
583: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130 brouard 584: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 585: double **matprod2(); /* test */
1.126 brouard 586: double **oldm, **newm, **savm; /* Working pointers to matrices */
587: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 588: /*FILE *fic ; */ /* Used in readdata only */
589: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 590: FILE *ficlog, *ficrespow;
1.130 brouard 591: int globpr=0; /* Global variable for printing or not */
1.126 brouard 592: double fretone; /* Only one call to likelihood */
1.130 brouard 593: long ipmx=0; /* Number of contributions */
1.126 brouard 594: double sw; /* Sum of weights */
595: char filerespow[FILENAMELENGTH];
596: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
597: FILE *ficresilk;
598: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
599: FILE *ficresprobmorprev;
600: FILE *fichtm, *fichtmcov; /* Html File */
601: FILE *ficreseij;
602: char filerese[FILENAMELENGTH];
603: FILE *ficresstdeij;
604: char fileresstde[FILENAMELENGTH];
605: FILE *ficrescveij;
606: char filerescve[FILENAMELENGTH];
607: FILE *ficresvij;
608: char fileresv[FILENAMELENGTH];
609: FILE *ficresvpl;
610: char fileresvpl[FILENAMELENGTH];
611: char title[MAXLINE];
612: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
613: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
614: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
615: char command[FILENAMELENGTH];
616: int outcmd=0;
617:
618: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
619:
620: char filelog[FILENAMELENGTH]; /* Log file */
621: char filerest[FILENAMELENGTH];
622: char fileregp[FILENAMELENGTH];
623: char popfile[FILENAMELENGTH];
624:
625: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
626:
1.157 brouard 627: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
628: /* struct timezone tzp; */
629: /* extern int gettimeofday(); */
630: struct tm tml, *gmtime(), *localtime();
631:
632: extern time_t time();
633:
634: struct tm start_time, end_time, curr_time, last_time, forecast_time;
635: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
636: struct tm tm;
637:
1.126 brouard 638: char strcurr[80], strfor[80];
639:
640: char *endptr;
641: long lval;
642: double dval;
643:
644: #define NR_END 1
645: #define FREE_ARG char*
646: #define FTOL 1.0e-10
647:
648: #define NRANSI
649: #define ITMAX 200
650:
651: #define TOL 2.0e-4
652:
653: #define CGOLD 0.3819660
654: #define ZEPS 1.0e-10
655: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
656:
657: #define GOLD 1.618034
658: #define GLIMIT 100.0
659: #define TINY 1.0e-20
660:
661: static double maxarg1,maxarg2;
662: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
663: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
664:
665: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
666: #define rint(a) floor(a+0.5)
667:
668: static double sqrarg;
669: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
670: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
671: int agegomp= AGEGOMP;
672:
673: int imx;
674: int stepm=1;
675: /* Stepm, step in month: minimum step interpolation*/
676:
677: int estepm;
678: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
679:
680: int m,nb;
681: long *num;
682: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
683: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
684: double **pmmij, ***probs;
685: double *ageexmed,*agecens;
686: double dateintmean=0;
687:
688: double *weight;
689: int **s; /* Status */
1.141 brouard 690: double *agedc;
1.145 brouard 691: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 692: * covar=matrix(0,NCOVMAX,1,n);
693: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
694: double idx;
695: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 696: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 697: int **codtab; /**< codtab=imatrix(1,100,1,10); */
698: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 699: double *lsurv, *lpop, *tpop;
700:
1.143 brouard 701: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
702: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 703:
704: /**************** split *************************/
705: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
706: {
707: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
708: the name of the file (name), its extension only (ext) and its first part of the name (finame)
709: */
710: char *ss; /* pointer */
711: int l1, l2; /* length counters */
712:
713: l1 = strlen(path ); /* length of path */
714: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
715: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
716: if ( ss == NULL ) { /* no directory, so determine current directory */
717: strcpy( name, path ); /* we got the fullname name because no directory */
718: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
719: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
720: /* get current working directory */
721: /* extern char* getcwd ( char *buf , int len);*/
722: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
723: return( GLOCK_ERROR_GETCWD );
724: }
725: /* got dirc from getcwd*/
726: printf(" DIRC = %s \n",dirc);
727: } else { /* strip direcotry from path */
728: ss++; /* after this, the filename */
729: l2 = strlen( ss ); /* length of filename */
730: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
731: strcpy( name, ss ); /* save file name */
732: strncpy( dirc, path, l1 - l2 ); /* now the directory */
733: dirc[l1-l2] = 0; /* add zero */
734: printf(" DIRC2 = %s \n",dirc);
735: }
736: /* We add a separator at the end of dirc if not exists */
737: l1 = strlen( dirc ); /* length of directory */
738: if( dirc[l1-1] != DIRSEPARATOR ){
739: dirc[l1] = DIRSEPARATOR;
740: dirc[l1+1] = 0;
741: printf(" DIRC3 = %s \n",dirc);
742: }
743: ss = strrchr( name, '.' ); /* find last / */
744: if (ss >0){
745: ss++;
746: strcpy(ext,ss); /* save extension */
747: l1= strlen( name);
748: l2= strlen(ss)+1;
749: strncpy( finame, name, l1-l2);
750: finame[l1-l2]= 0;
751: }
752:
753: return( 0 ); /* we're done */
754: }
755:
756:
757: /******************************************/
758:
759: void replace_back_to_slash(char *s, char*t)
760: {
761: int i;
762: int lg=0;
763: i=0;
764: lg=strlen(t);
765: for(i=0; i<= lg; i++) {
766: (s[i] = t[i]);
767: if (t[i]== '\\') s[i]='/';
768: }
769: }
770:
1.132 brouard 771: char *trimbb(char *out, char *in)
1.137 brouard 772: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 773: char *s;
774: s=out;
775: while (*in != '\0'){
1.137 brouard 776: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 777: in++;
778: }
779: *out++ = *in++;
780: }
781: *out='\0';
782: return s;
783: }
784:
1.145 brouard 785: char *cutl(char *blocc, char *alocc, char *in, char occ)
786: {
787: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
788: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
789: gives blocc="abcdef2ghi" and alocc="j".
790: If occ is not found blocc is null and alocc is equal to in. Returns blocc
791: */
1.160 brouard 792: char *s, *t;
1.145 brouard 793: t=in;s=in;
794: while ((*in != occ) && (*in != '\0')){
795: *alocc++ = *in++;
796: }
797: if( *in == occ){
798: *(alocc)='\0';
799: s=++in;
800: }
801:
802: if (s == t) {/* occ not found */
803: *(alocc-(in-s))='\0';
804: in=s;
805: }
806: while ( *in != '\0'){
807: *blocc++ = *in++;
808: }
809:
810: *blocc='\0';
811: return t;
812: }
1.137 brouard 813: char *cutv(char *blocc, char *alocc, char *in, char occ)
814: {
815: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
816: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
817: gives blocc="abcdef2ghi" and alocc="j".
818: If occ is not found blocc is null and alocc is equal to in. Returns alocc
819: */
820: char *s, *t;
821: t=in;s=in;
822: while (*in != '\0'){
823: while( *in == occ){
824: *blocc++ = *in++;
825: s=in;
826: }
827: *blocc++ = *in++;
828: }
829: if (s == t) /* occ not found */
830: *(blocc-(in-s))='\0';
831: else
832: *(blocc-(in-s)-1)='\0';
833: in=s;
834: while ( *in != '\0'){
835: *alocc++ = *in++;
836: }
837:
838: *alocc='\0';
839: return s;
840: }
841:
1.126 brouard 842: int nbocc(char *s, char occ)
843: {
844: int i,j=0;
845: int lg=20;
846: i=0;
847: lg=strlen(s);
848: for(i=0; i<= lg; i++) {
849: if (s[i] == occ ) j++;
850: }
851: return j;
852: }
853:
1.137 brouard 854: /* void cutv(char *u,char *v, char*t, char occ) */
855: /* { */
856: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
857: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
858: /* gives u="abcdef2ghi" and v="j" *\/ */
859: /* int i,lg,j,p=0; */
860: /* i=0; */
861: /* lg=strlen(t); */
862: /* for(j=0; j<=lg-1; j++) { */
863: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
864: /* } */
1.126 brouard 865:
1.137 brouard 866: /* for(j=0; j<p; j++) { */
867: /* (u[j] = t[j]); */
868: /* } */
869: /* u[p]='\0'; */
1.126 brouard 870:
1.137 brouard 871: /* for(j=0; j<= lg; j++) { */
872: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
873: /* } */
874: /* } */
1.126 brouard 875:
1.160 brouard 876: #ifdef _WIN32
877: char * strsep(char **pp, const char *delim)
878: {
879: char *p, *q;
880:
881: if ((p = *pp) == NULL)
882: return 0;
883: if ((q = strpbrk (p, delim)) != NULL)
884: {
885: *pp = q + 1;
886: *q = '\0';
887: }
888: else
889: *pp = 0;
890: return p;
891: }
892: #endif
893:
1.126 brouard 894: /********************** nrerror ********************/
895:
896: void nrerror(char error_text[])
897: {
898: fprintf(stderr,"ERREUR ...\n");
899: fprintf(stderr,"%s\n",error_text);
900: exit(EXIT_FAILURE);
901: }
902: /*********************** vector *******************/
903: double *vector(int nl, int nh)
904: {
905: double *v;
906: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
907: if (!v) nrerror("allocation failure in vector");
908: return v-nl+NR_END;
909: }
910:
911: /************************ free vector ******************/
912: void free_vector(double*v, int nl, int nh)
913: {
914: free((FREE_ARG)(v+nl-NR_END));
915: }
916:
917: /************************ivector *******************************/
918: int *ivector(long nl,long nh)
919: {
920: int *v;
921: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
922: if (!v) nrerror("allocation failure in ivector");
923: return v-nl+NR_END;
924: }
925:
926: /******************free ivector **************************/
927: void free_ivector(int *v, long nl, long nh)
928: {
929: free((FREE_ARG)(v+nl-NR_END));
930: }
931:
932: /************************lvector *******************************/
933: long *lvector(long nl,long nh)
934: {
935: long *v;
936: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
937: if (!v) nrerror("allocation failure in ivector");
938: return v-nl+NR_END;
939: }
940:
941: /******************free lvector **************************/
942: void free_lvector(long *v, long nl, long nh)
943: {
944: free((FREE_ARG)(v+nl-NR_END));
945: }
946:
947: /******************* imatrix *******************************/
948: int **imatrix(long nrl, long nrh, long ncl, long nch)
949: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
950: {
951: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
952: int **m;
953:
954: /* allocate pointers to rows */
955: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
956: if (!m) nrerror("allocation failure 1 in matrix()");
957: m += NR_END;
958: m -= nrl;
959:
960:
961: /* allocate rows and set pointers to them */
962: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
963: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
964: m[nrl] += NR_END;
965: m[nrl] -= ncl;
966:
967: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
968:
969: /* return pointer to array of pointers to rows */
970: return m;
971: }
972:
973: /****************** free_imatrix *************************/
974: void free_imatrix(m,nrl,nrh,ncl,nch)
975: int **m;
976: long nch,ncl,nrh,nrl;
977: /* free an int matrix allocated by imatrix() */
978: {
979: free((FREE_ARG) (m[nrl]+ncl-NR_END));
980: free((FREE_ARG) (m+nrl-NR_END));
981: }
982:
983: /******************* matrix *******************************/
984: double **matrix(long nrl, long nrh, long ncl, long nch)
985: {
986: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
987: double **m;
988:
989: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
990: if (!m) nrerror("allocation failure 1 in matrix()");
991: m += NR_END;
992: m -= nrl;
993:
994: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
995: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
996: m[nrl] += NR_END;
997: m[nrl] -= ncl;
998:
999: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1000: return m;
1.145 brouard 1001: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1002: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1003: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1004: */
1005: }
1006:
1007: /*************************free matrix ************************/
1008: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1009: {
1010: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1011: free((FREE_ARG)(m+nrl-NR_END));
1012: }
1013:
1014: /******************* ma3x *******************************/
1015: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1016: {
1017: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1018: double ***m;
1019:
1020: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1021: if (!m) nrerror("allocation failure 1 in matrix()");
1022: m += NR_END;
1023: m -= nrl;
1024:
1025: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1026: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1027: m[nrl] += NR_END;
1028: m[nrl] -= ncl;
1029:
1030: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1031:
1032: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1033: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1034: m[nrl][ncl] += NR_END;
1035: m[nrl][ncl] -= nll;
1036: for (j=ncl+1; j<=nch; j++)
1037: m[nrl][j]=m[nrl][j-1]+nlay;
1038:
1039: for (i=nrl+1; i<=nrh; i++) {
1040: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1041: for (j=ncl+1; j<=nch; j++)
1042: m[i][j]=m[i][j-1]+nlay;
1043: }
1044: return m;
1045: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1046: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1047: */
1048: }
1049:
1050: /*************************free ma3x ************************/
1051: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1052: {
1053: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1054: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1055: free((FREE_ARG)(m+nrl-NR_END));
1056: }
1057:
1058: /*************** function subdirf ***********/
1059: char *subdirf(char fileres[])
1060: {
1061: /* Caution optionfilefiname is hidden */
1062: strcpy(tmpout,optionfilefiname);
1063: strcat(tmpout,"/"); /* Add to the right */
1064: strcat(tmpout,fileres);
1065: return tmpout;
1066: }
1067:
1068: /*************** function subdirf2 ***********/
1069: char *subdirf2(char fileres[], char *preop)
1070: {
1071:
1072: /* Caution optionfilefiname is hidden */
1073: strcpy(tmpout,optionfilefiname);
1074: strcat(tmpout,"/");
1075: strcat(tmpout,preop);
1076: strcat(tmpout,fileres);
1077: return tmpout;
1078: }
1079:
1080: /*************** function subdirf3 ***********/
1081: char *subdirf3(char fileres[], char *preop, char *preop2)
1082: {
1083:
1084: /* Caution optionfilefiname is hidden */
1085: strcpy(tmpout,optionfilefiname);
1086: strcat(tmpout,"/");
1087: strcat(tmpout,preop);
1088: strcat(tmpout,preop2);
1089: strcat(tmpout,fileres);
1090: return tmpout;
1091: }
1092:
1093: /***************** f1dim *************************/
1094: extern int ncom;
1095: extern double *pcom,*xicom;
1096: extern double (*nrfunc)(double []);
1097:
1098: double f1dim(double x)
1099: {
1100: int j;
1101: double f;
1102: double *xt;
1103:
1104: xt=vector(1,ncom);
1105: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1106: f=(*nrfunc)(xt);
1107: free_vector(xt,1,ncom);
1108: return f;
1109: }
1110:
1111: /*****************brent *************************/
1112: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1113: {
1114: int iter;
1115: double a,b,d,etemp;
1.159 brouard 1116: double fu=0,fv,fw,fx;
1.126 brouard 1117: double ftemp;
1118: double p,q,r,tol1,tol2,u,v,w,x,xm;
1119: double e=0.0;
1120:
1121: a=(ax < cx ? ax : cx);
1122: b=(ax > cx ? ax : cx);
1123: x=w=v=bx;
1124: fw=fv=fx=(*f)(x);
1125: for (iter=1;iter<=ITMAX;iter++) {
1126: xm=0.5*(a+b);
1127: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1128: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1129: printf(".");fflush(stdout);
1130: fprintf(ficlog,".");fflush(ficlog);
1131: #ifdef DEBUG
1132: 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);
1133: 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);
1134: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1135: #endif
1136: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1137: *xmin=x;
1138: return fx;
1139: }
1140: ftemp=fu;
1141: if (fabs(e) > tol1) {
1142: r=(x-w)*(fx-fv);
1143: q=(x-v)*(fx-fw);
1144: p=(x-v)*q-(x-w)*r;
1145: q=2.0*(q-r);
1146: if (q > 0.0) p = -p;
1147: q=fabs(q);
1148: etemp=e;
1149: e=d;
1150: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1151: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1152: else {
1153: d=p/q;
1154: u=x+d;
1155: if (u-a < tol2 || b-u < tol2)
1156: d=SIGN(tol1,xm-x);
1157: }
1158: } else {
1159: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1160: }
1161: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1162: fu=(*f)(u);
1163: if (fu <= fx) {
1164: if (u >= x) a=x; else b=x;
1165: SHFT(v,w,x,u)
1166: SHFT(fv,fw,fx,fu)
1167: } else {
1168: if (u < x) a=u; else b=u;
1169: if (fu <= fw || w == x) {
1170: v=w;
1171: w=u;
1172: fv=fw;
1173: fw=fu;
1174: } else if (fu <= fv || v == x || v == w) {
1175: v=u;
1176: fv=fu;
1177: }
1178: }
1179: }
1180: nrerror("Too many iterations in brent");
1181: *xmin=x;
1182: return fx;
1183: }
1184:
1185: /****************** mnbrak ***********************/
1186:
1187: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1188: double (*func)(double))
1189: {
1190: double ulim,u,r,q, dum;
1191: double fu;
1192:
1193: *fa=(*func)(*ax);
1194: *fb=(*func)(*bx);
1195: if (*fb > *fa) {
1196: SHFT(dum,*ax,*bx,dum)
1197: SHFT(dum,*fb,*fa,dum)
1198: }
1199: *cx=(*bx)+GOLD*(*bx-*ax);
1200: *fc=(*func)(*cx);
1201: while (*fb > *fc) {
1202: r=(*bx-*ax)*(*fb-*fc);
1203: q=(*bx-*cx)*(*fb-*fa);
1204: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1205: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
1206: ulim=(*bx)+GLIMIT*(*cx-*bx);
1207: if ((*bx-u)*(u-*cx) > 0.0) {
1208: fu=(*func)(u);
1209: } else if ((*cx-u)*(u-ulim) > 0.0) {
1210: fu=(*func)(u);
1211: if (fu < *fc) {
1212: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1213: SHFT(*fb,*fc,fu,(*func)(u))
1214: }
1215: } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
1216: u=ulim;
1217: fu=(*func)(u);
1218: } else {
1219: u=(*cx)+GOLD*(*cx-*bx);
1220: fu=(*func)(u);
1221: }
1222: SHFT(*ax,*bx,*cx,u)
1223: SHFT(*fa,*fb,*fc,fu)
1224: }
1225: }
1226:
1227: /*************** linmin ************************/
1228:
1229: int ncom;
1230: double *pcom,*xicom;
1231: double (*nrfunc)(double []);
1232:
1233: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1234: {
1235: double brent(double ax, double bx, double cx,
1236: double (*f)(double), double tol, double *xmin);
1237: double f1dim(double x);
1238: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1239: double *fc, double (*func)(double));
1240: int j;
1241: double xx,xmin,bx,ax;
1242: double fx,fb,fa;
1243:
1244: ncom=n;
1245: pcom=vector(1,n);
1246: xicom=vector(1,n);
1247: nrfunc=func;
1248: for (j=1;j<=n;j++) {
1249: pcom[j]=p[j];
1250: xicom[j]=xi[j];
1251: }
1252: ax=0.0;
1253: xx=1.0;
1254: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
1255: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
1256: #ifdef DEBUG
1257: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1258: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1259: #endif
1260: for (j=1;j<=n;j++) {
1261: xi[j] *= xmin;
1262: p[j] += xi[j];
1263: }
1264: free_vector(xicom,1,n);
1265: free_vector(pcom,1,n);
1266: }
1267:
1268: char *asc_diff_time(long time_sec, char ascdiff[])
1269: {
1270: long sec_left, days, hours, minutes;
1271: days = (time_sec) / (60*60*24);
1272: sec_left = (time_sec) % (60*60*24);
1273: hours = (sec_left) / (60*60) ;
1274: sec_left = (sec_left) %(60*60);
1275: minutes = (sec_left) /60;
1276: sec_left = (sec_left) % (60);
1.141 brouard 1277: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1.126 brouard 1278: return ascdiff;
1279: }
1280:
1281: /*************** powell ************************/
1282: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1283: double (*func)(double []))
1284: {
1285: void linmin(double p[], double xi[], int n, double *fret,
1286: double (*func)(double []));
1287: int i,ibig,j;
1288: double del,t,*pt,*ptt,*xit;
1289: double fp,fptt;
1290: double *xits;
1291: int niterf, itmp;
1292:
1293: pt=vector(1,n);
1294: ptt=vector(1,n);
1295: xit=vector(1,n);
1296: xits=vector(1,n);
1297: *fret=(*func)(p);
1298: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1299: rcurr_time = time(NULL);
1.126 brouard 1300: for (*iter=1;;++(*iter)) {
1301: fp=(*fret);
1302: ibig=0;
1303: del=0.0;
1.157 brouard 1304: rlast_time=rcurr_time;
1305: /* (void) gettimeofday(&curr_time,&tzp); */
1306: rcurr_time = time(NULL);
1307: curr_time = *localtime(&rcurr_time);
1308: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1309: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1310: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1311: for (i=1;i<=n;i++) {
1312: printf(" %d %.12f",i, p[i]);
1313: fprintf(ficlog," %d %.12lf",i, p[i]);
1314: fprintf(ficrespow," %.12lf", p[i]);
1315: }
1316: printf("\n");
1317: fprintf(ficlog,"\n");
1318: fprintf(ficrespow,"\n");fflush(ficrespow);
1319: if(*iter <=3){
1.157 brouard 1320: tml = *localtime(&rcurr_time);
1321: strcpy(strcurr,asctime(&tml));
1.126 brouard 1322: /* asctime_r(&tm,strcurr); */
1.157 brouard 1323: rforecast_time=rcurr_time;
1.126 brouard 1324: itmp = strlen(strcurr);
1325: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1326: strcurr[itmp-1]='\0';
1.157 brouard 1327: printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1328: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1329: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1330: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1331: forecast_time = *localtime(&rforecast_time);
1.126 brouard 1332: /* asctime_r(&tmf,strfor); */
1.157 brouard 1333: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1334: itmp = strlen(strfor);
1335: if(strfor[itmp-1]=='\n')
1336: strfor[itmp-1]='\0';
1.157 brouard 1337: 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);
1338: 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 1339: }
1340: }
1341: for (i=1;i<=n;i++) {
1342: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1343: fptt=(*fret);
1344: #ifdef DEBUG
1345: printf("fret=%lf \n",*fret);
1346: fprintf(ficlog,"fret=%lf \n",*fret);
1347: #endif
1348: printf("%d",i);fflush(stdout);
1349: fprintf(ficlog,"%d",i);fflush(ficlog);
1350: linmin(p,xit,n,fret,func);
1351: if (fabs(fptt-(*fret)) > del) {
1352: del=fabs(fptt-(*fret));
1353: ibig=i;
1354: }
1355: #ifdef DEBUG
1356: printf("%d %.12e",i,(*fret));
1357: fprintf(ficlog,"%d %.12e",i,(*fret));
1358: for (j=1;j<=n;j++) {
1359: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1360: printf(" x(%d)=%.12e",j,xit[j]);
1361: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1362: }
1363: for(j=1;j<=n;j++) {
1364: printf(" p=%.12e",p[j]);
1365: fprintf(ficlog," p=%.12e",p[j]);
1366: }
1367: printf("\n");
1368: fprintf(ficlog,"\n");
1369: #endif
1370: }
1371: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1372: #ifdef DEBUG
1373: int k[2],l;
1374: k[0]=1;
1375: k[1]=-1;
1376: printf("Max: %.12e",(*func)(p));
1377: fprintf(ficlog,"Max: %.12e",(*func)(p));
1378: for (j=1;j<=n;j++) {
1379: printf(" %.12e",p[j]);
1380: fprintf(ficlog," %.12e",p[j]);
1381: }
1382: printf("\n");
1383: fprintf(ficlog,"\n");
1384: for(l=0;l<=1;l++) {
1385: for (j=1;j<=n;j++) {
1386: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1387: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1388: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1389: }
1390: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1391: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1392: }
1393: #endif
1394:
1395:
1396: free_vector(xit,1,n);
1397: free_vector(xits,1,n);
1398: free_vector(ptt,1,n);
1399: free_vector(pt,1,n);
1400: return;
1401: }
1402: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 ! brouard 1403: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1404: ptt[j]=2.0*p[j]-pt[j];
1405: xit[j]=p[j]-pt[j];
1406: pt[j]=p[j];
1407: }
1408: fptt=(*func)(ptt);
1.161 ! brouard 1409: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
! 1410: /* x1 f1=fp x2 f2=*fret x3 f3=fptt, xm fm */
! 1411: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
! 1412: /* Let f"(x2) be the 2nd derivative equal everywhere. Then the parabolic through (x1,f1), (x2,f2) and (x3,f3)
! 1413: will reach at f3 = fm + h^2/2 f''m ; f" = (f1 -2f2 +f3 ) / h**2 */
! 1414: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
! 1415: /* Thus we compare delta(2h) with observed f1-f3 */
! 1416: /* or best gain on one ancient line 'del' with total gain f1-f2 = f1 - f2 - 'del' with del */
! 1417: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
! 1418: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
! 1419: t= t- del*SQR(fp-fptt);
! 1420: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
! 1421: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
! 1422: #ifdef DEBUG
! 1423: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
! 1424: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
! 1425: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
! 1426: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
! 1427: printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
! 1428: fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
! 1429: #endif
! 1430: if (t < 0.0) { /* Then we use it for last direction */
! 1431: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1432: for (j=1;j<=n;j++) {
1.161 ! brouard 1433: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
! 1434: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1435: }
1.161 ! brouard 1436: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
! 1437: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
! 1438:
1.126 brouard 1439: #ifdef DEBUG
1440: for(j=1;j<=n;j++){
1441: printf(" %.12e",xit[j]);
1442: fprintf(ficlog," %.12e",xit[j]);
1443: }
1444: printf("\n");
1445: fprintf(ficlog,"\n");
1446: #endif
1447: }
1448: }
1449: }
1450: }
1451:
1452: /**** Prevalence limit (stable or period prevalence) ****************/
1453:
1454: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1455: {
1456: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1457: matrix by transitions matrix until convergence is reached */
1458:
1459: int i, ii,j,k;
1460: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1461: /* double **matprod2(); */ /* test */
1.131 brouard 1462: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1463: double **newm;
1464: double agefin, delaymax=50 ; /* Max number of years to converge */
1465:
1466: for (ii=1;ii<=nlstate+ndeath;ii++)
1467: for (j=1;j<=nlstate+ndeath;j++){
1468: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1469: }
1470:
1471: cov[1]=1.;
1472:
1473: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1474: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1475: newm=savm;
1476: /* Covariates have to be included here again */
1.138 brouard 1477: cov[2]=agefin;
1478:
1479: for (k=1; k<=cptcovn;k++) {
1480: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1481: /*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 1482: }
1.145 brouard 1483: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1484: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1485: /* 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 1486:
1487: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1488: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1489: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1490: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1491: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1492: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1493:
1.126 brouard 1494: savm=oldm;
1495: oldm=newm;
1496: maxmax=0.;
1497: for(j=1;j<=nlstate;j++){
1498: min=1.;
1499: max=0.;
1500: for(i=1; i<=nlstate; i++) {
1501: sumnew=0;
1502: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1503: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1504: /*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 1505: max=FMAX(max,prlim[i][j]);
1506: min=FMIN(min,prlim[i][j]);
1507: }
1508: maxmin=max-min;
1509: maxmax=FMAX(maxmax,maxmin);
1510: }
1511: if(maxmax < ftolpl){
1512: return prlim;
1513: }
1514: }
1515: }
1516:
1517: /*************** transition probabilities ***************/
1518:
1519: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1520: {
1.138 brouard 1521: /* According to parameters values stored in x and the covariate's values stored in cov,
1522: computes the probability to be observed in state j being in state i by appying the
1523: model to the ncovmodel covariates (including constant and age).
1524: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1525: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1526: ncth covariate in the global vector x is given by the formula:
1527: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1528: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1529: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1530: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1531: Outputs ps[i][j] the probability to be observed in j being in j according to
1532: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1533: */
1534: double s1, lnpijopii;
1.126 brouard 1535: /*double t34;*/
1536: int i,j,j1, nc, ii, jj;
1537:
1538: for(i=1; i<= nlstate; i++){
1539: for(j=1; j<i;j++){
1.138 brouard 1540: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1541: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1542: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1543: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1544: }
1.138 brouard 1545: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1546: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1547: }
1548: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1549: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1550: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1551: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1552: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1553: }
1.138 brouard 1554: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1555: }
1556: }
1557:
1558: for(i=1; i<= nlstate; i++){
1559: s1=0;
1.131 brouard 1560: for(j=1; j<i; j++){
1.138 brouard 1561: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1562: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1563: }
1564: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1565: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1566: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1567: }
1.138 brouard 1568: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1569: ps[i][i]=1./(s1+1.);
1.138 brouard 1570: /* Computing other pijs */
1.126 brouard 1571: for(j=1; j<i; j++)
1572: ps[i][j]= exp(ps[i][j])*ps[i][i];
1573: for(j=i+1; j<=nlstate+ndeath; j++)
1574: ps[i][j]= exp(ps[i][j])*ps[i][i];
1575: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1576: } /* end i */
1577:
1578: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1579: for(jj=1; jj<= nlstate+ndeath; jj++){
1580: ps[ii][jj]=0;
1581: ps[ii][ii]=1;
1582: }
1583: }
1584:
1.145 brouard 1585:
1586: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1587: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1588: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1589: /* } */
1590: /* printf("\n "); */
1591: /* } */
1592: /* printf("\n ");printf("%lf ",cov[2]);*/
1593: /*
1.126 brouard 1594: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1595: goto end;*/
1596: return ps;
1597: }
1598:
1599: /**************** Product of 2 matrices ******************/
1600:
1.145 brouard 1601: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1602: {
1603: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1604: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1605: /* in, b, out are matrice of pointers which should have been initialized
1606: before: only the contents of out is modified. The function returns
1607: a pointer to pointers identical to out */
1.145 brouard 1608: int i, j, k;
1.126 brouard 1609: for(i=nrl; i<= nrh; i++)
1.145 brouard 1610: for(k=ncolol; k<=ncoloh; k++){
1611: out[i][k]=0.;
1612: for(j=ncl; j<=nch; j++)
1613: out[i][k] +=in[i][j]*b[j][k];
1614: }
1.126 brouard 1615: return out;
1616: }
1617:
1618:
1619: /************* Higher Matrix Product ***************/
1620:
1621: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1622: {
1623: /* Computes the transition matrix starting at age 'age' over
1624: 'nhstepm*hstepm*stepm' months (i.e. until
1625: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1626: nhstepm*hstepm matrices.
1627: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1628: (typically every 2 years instead of every month which is too big
1629: for the memory).
1630: Model is determined by parameters x and covariates have to be
1631: included manually here.
1632:
1633: */
1634:
1635: int i, j, d, h, k;
1.131 brouard 1636: double **out, cov[NCOVMAX+1];
1.126 brouard 1637: double **newm;
1638:
1639: /* Hstepm could be zero and should return the unit matrix */
1640: for (i=1;i<=nlstate+ndeath;i++)
1641: for (j=1;j<=nlstate+ndeath;j++){
1642: oldm[i][j]=(i==j ? 1.0 : 0.0);
1643: po[i][j][0]=(i==j ? 1.0 : 0.0);
1644: }
1645: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1646: for(h=1; h <=nhstepm; h++){
1647: for(d=1; d <=hstepm; d++){
1648: newm=savm;
1649: /* Covariates have to be included here again */
1650: cov[1]=1.;
1651: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1652: for (k=1; k<=cptcovn;k++)
1653: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1654: for (k=1; k<=cptcovage;k++)
1655: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1656: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1657: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1658:
1659:
1660: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1661: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1662: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1663: pmij(pmmij,cov,ncovmodel,x,nlstate));
1664: savm=oldm;
1665: oldm=newm;
1666: }
1667: for(i=1; i<=nlstate+ndeath; i++)
1668: for(j=1;j<=nlstate+ndeath;j++) {
1669: po[i][j][h]=newm[i][j];
1.128 brouard 1670: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1671: }
1.128 brouard 1672: /*printf("h=%d ",h);*/
1.126 brouard 1673: } /* end h */
1.128 brouard 1674: /* printf("\n H=%d \n",h); */
1.126 brouard 1675: return po;
1676: }
1677:
1678:
1679: /*************** log-likelihood *************/
1680: double func( double *x)
1681: {
1682: int i, ii, j, k, mi, d, kk;
1.131 brouard 1683: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1684: double **out;
1685: double sw; /* Sum of weights */
1686: double lli; /* Individual log likelihood */
1687: int s1, s2;
1688: double bbh, survp;
1689: long ipmx;
1690: /*extern weight */
1691: /* We are differentiating ll according to initial status */
1692: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1693: /*for(i=1;i<imx;i++)
1694: printf(" %d\n",s[4][i]);
1695: */
1696: cov[1]=1.;
1697:
1698: for(k=1; k<=nlstate; k++) ll[k]=0.;
1699:
1700: if(mle==1){
1701: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1702: /* Computes the values of the ncovmodel covariates of the model
1703: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1704: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1705: to be observed in j being in i according to the model.
1706: */
1.145 brouard 1707: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1708: cov[2+k]=covar[Tvar[k]][i];
1709: }
1.137 brouard 1710: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1711: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1712: has been calculated etc */
1.126 brouard 1713: for(mi=1; mi<= wav[i]-1; mi++){
1714: for (ii=1;ii<=nlstate+ndeath;ii++)
1715: for (j=1;j<=nlstate+ndeath;j++){
1716: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1717: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1718: }
1719: for(d=0; d<dh[mi][i]; d++){
1720: newm=savm;
1721: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1722: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1723: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1724: }
1725: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1726: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1727: savm=oldm;
1728: oldm=newm;
1729: } /* end mult */
1730:
1731: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1732: /* But now since version 0.9 we anticipate for bias at large stepm.
1733: * If stepm is larger than one month (smallest stepm) and if the exact delay
1734: * (in months) between two waves is not a multiple of stepm, we rounded to
1735: * the nearest (and in case of equal distance, to the lowest) interval but now
1736: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1737: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1738: * probability in order to take into account the bias as a fraction of the way
1739: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1740: * -stepm/2 to stepm/2 .
1741: * For stepm=1 the results are the same as for previous versions of Imach.
1742: * For stepm > 1 the results are less biased than in previous versions.
1743: */
1744: s1=s[mw[mi][i]][i];
1745: s2=s[mw[mi+1][i]][i];
1746: bbh=(double)bh[mi][i]/(double)stepm;
1747: /* bias bh is positive if real duration
1748: * is higher than the multiple of stepm and negative otherwise.
1749: */
1750: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1751: if( s2 > nlstate){
1752: /* i.e. if s2 is a death state and if the date of death is known
1753: then the contribution to the likelihood is the probability to
1754: die between last step unit time and current step unit time,
1755: which is also equal to probability to die before dh
1756: minus probability to die before dh-stepm .
1757: In version up to 0.92 likelihood was computed
1758: as if date of death was unknown. Death was treated as any other
1759: health state: the date of the interview describes the actual state
1760: and not the date of a change in health state. The former idea was
1761: to consider that at each interview the state was recorded
1762: (healthy, disable or death) and IMaCh was corrected; but when we
1763: introduced the exact date of death then we should have modified
1764: the contribution of an exact death to the likelihood. This new
1765: contribution is smaller and very dependent of the step unit
1766: stepm. It is no more the probability to die between last interview
1767: and month of death but the probability to survive from last
1768: interview up to one month before death multiplied by the
1769: probability to die within a month. Thanks to Chris
1770: Jackson for correcting this bug. Former versions increased
1771: mortality artificially. The bad side is that we add another loop
1772: which slows down the processing. The difference can be up to 10%
1773: lower mortality.
1774: */
1775: lli=log(out[s1][s2] - savm[s1][s2]);
1776:
1777:
1778: } else if (s2==-2) {
1779: for (j=1,survp=0. ; j<=nlstate; j++)
1780: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1781: /*survp += out[s1][j]; */
1782: lli= log(survp);
1783: }
1784:
1785: else if (s2==-4) {
1786: for (j=3,survp=0. ; j<=nlstate; j++)
1787: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1788: lli= log(survp);
1789: }
1790:
1791: else if (s2==-5) {
1792: for (j=1,survp=0. ; j<=2; j++)
1793: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1794: lli= log(survp);
1795: }
1796:
1797: else{
1798: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1799: /* 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 */
1800: }
1801: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1802: /*if(lli ==000.0)*/
1803: /*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); */
1804: ipmx +=1;
1805: sw += weight[i];
1806: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1807: } /* end of wave */
1808: } /* end of individual */
1809: } else if(mle==2){
1810: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1811: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1812: for(mi=1; mi<= wav[i]-1; mi++){
1813: for (ii=1;ii<=nlstate+ndeath;ii++)
1814: for (j=1;j<=nlstate+ndeath;j++){
1815: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1816: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1817: }
1818: for(d=0; d<=dh[mi][i]; d++){
1819: newm=savm;
1820: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1821: for (kk=1; kk<=cptcovage;kk++) {
1822: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1823: }
1824: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1825: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1826: savm=oldm;
1827: oldm=newm;
1828: } /* end mult */
1829:
1830: s1=s[mw[mi][i]][i];
1831: s2=s[mw[mi+1][i]][i];
1832: bbh=(double)bh[mi][i]/(double)stepm;
1833: 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 */
1834: ipmx +=1;
1835: sw += weight[i];
1836: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1837: } /* end of wave */
1838: } /* end of individual */
1839: } else if(mle==3){ /* exponential inter-extrapolation */
1840: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1841: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1842: for(mi=1; mi<= wav[i]-1; mi++){
1843: for (ii=1;ii<=nlstate+ndeath;ii++)
1844: for (j=1;j<=nlstate+ndeath;j++){
1845: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1846: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1847: }
1848: for(d=0; d<dh[mi][i]; d++){
1849: newm=savm;
1850: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1851: for (kk=1; kk<=cptcovage;kk++) {
1852: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1853: }
1854: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1855: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1856: savm=oldm;
1857: oldm=newm;
1858: } /* end mult */
1859:
1860: s1=s[mw[mi][i]][i];
1861: s2=s[mw[mi+1][i]][i];
1862: bbh=(double)bh[mi][i]/(double)stepm;
1863: 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 */
1864: ipmx +=1;
1865: sw += weight[i];
1866: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1867: } /* end of wave */
1868: } /* end of individual */
1869: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1870: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1871: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1872: for(mi=1; mi<= wav[i]-1; mi++){
1873: for (ii=1;ii<=nlstate+ndeath;ii++)
1874: for (j=1;j<=nlstate+ndeath;j++){
1875: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1876: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1877: }
1878: for(d=0; d<dh[mi][i]; d++){
1879: newm=savm;
1880: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1881: for (kk=1; kk<=cptcovage;kk++) {
1882: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1883: }
1884:
1885: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1886: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1887: savm=oldm;
1888: oldm=newm;
1889: } /* end mult */
1890:
1891: s1=s[mw[mi][i]][i];
1892: s2=s[mw[mi+1][i]][i];
1893: if( s2 > nlstate){
1894: lli=log(out[s1][s2] - savm[s1][s2]);
1895: }else{
1896: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1897: }
1898: ipmx +=1;
1899: sw += weight[i];
1900: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1901: /* 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]); */
1902: } /* end of wave */
1903: } /* end of individual */
1904: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1905: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1906: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1907: for(mi=1; mi<= wav[i]-1; mi++){
1908: for (ii=1;ii<=nlstate+ndeath;ii++)
1909: for (j=1;j<=nlstate+ndeath;j++){
1910: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1911: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1912: }
1913: for(d=0; d<dh[mi][i]; d++){
1914: newm=savm;
1915: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1916: for (kk=1; kk<=cptcovage;kk++) {
1917: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1918: }
1919:
1920: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1921: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1922: savm=oldm;
1923: oldm=newm;
1924: } /* end mult */
1925:
1926: s1=s[mw[mi][i]][i];
1927: s2=s[mw[mi+1][i]][i];
1928: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1929: ipmx +=1;
1930: sw += weight[i];
1931: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1932: /*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]);*/
1933: } /* end of wave */
1934: } /* end of individual */
1935: } /* End of if */
1936: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1937: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1938: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1939: return -l;
1940: }
1941:
1942: /*************** log-likelihood *************/
1943: double funcone( double *x)
1944: {
1945: /* Same as likeli but slower because of a lot of printf and if */
1946: int i, ii, j, k, mi, d, kk;
1.131 brouard 1947: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1948: double **out;
1949: double lli; /* Individual log likelihood */
1950: double llt;
1951: int s1, s2;
1952: double bbh, survp;
1953: /*extern weight */
1954: /* We are differentiating ll according to initial status */
1955: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1956: /*for(i=1;i<imx;i++)
1957: printf(" %d\n",s[4][i]);
1958: */
1959: cov[1]=1.;
1960:
1961: for(k=1; k<=nlstate; k++) ll[k]=0.;
1962:
1963: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1964: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1965: for(mi=1; mi<= wav[i]-1; mi++){
1966: for (ii=1;ii<=nlstate+ndeath;ii++)
1967: for (j=1;j<=nlstate+ndeath;j++){
1968: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1969: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1970: }
1971: for(d=0; d<dh[mi][i]; d++){
1972: newm=savm;
1973: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1974: for (kk=1; kk<=cptcovage;kk++) {
1975: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1976: }
1.145 brouard 1977: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 1978: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1979: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 1980: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
1981: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 1982: savm=oldm;
1983: oldm=newm;
1984: } /* end mult */
1985:
1986: s1=s[mw[mi][i]][i];
1987: s2=s[mw[mi+1][i]][i];
1988: bbh=(double)bh[mi][i]/(double)stepm;
1989: /* bias is positive if real duration
1990: * is higher than the multiple of stepm and negative otherwise.
1991: */
1992: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1993: lli=log(out[s1][s2] - savm[s1][s2]);
1994: } else if (s2==-2) {
1995: for (j=1,survp=0. ; j<=nlstate; j++)
1996: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1997: lli= log(survp);
1998: }else if (mle==1){
1999: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2000: } else if(mle==2){
2001: 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 */
2002: } else if(mle==3){ /* exponential inter-extrapolation */
2003: 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 */
2004: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2005: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2006: } else{ /* mle=0 back to 1 */
2007: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2008: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2009: } /* End of if */
2010: ipmx +=1;
2011: sw += weight[i];
2012: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2013: /*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 2014: if(globpr){
1.141 brouard 2015: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2016: %11.6f %11.6f %11.6f ", \
2017: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2018: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2019: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2020: llt +=ll[k]*gipmx/gsw;
2021: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2022: }
2023: fprintf(ficresilk," %10.6f\n", -llt);
2024: }
2025: } /* end of wave */
2026: } /* end of individual */
2027: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2028: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2029: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2030: if(globpr==0){ /* First time we count the contributions and weights */
2031: gipmx=ipmx;
2032: gsw=sw;
2033: }
2034: return -l;
2035: }
2036:
2037:
2038: /*************** function likelione ***********/
2039: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2040: {
2041: /* This routine should help understanding what is done with
2042: the selection of individuals/waves and
2043: to check the exact contribution to the likelihood.
2044: Plotting could be done.
2045: */
2046: int k;
2047:
2048: if(*globpri !=0){ /* Just counts and sums, no printings */
2049: strcpy(fileresilk,"ilk");
2050: strcat(fileresilk,fileres);
2051: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2052: printf("Problem with resultfile: %s\n", fileresilk);
2053: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2054: }
2055: 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");
2056: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2057: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2058: for(k=1; k<=nlstate; k++)
2059: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2060: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2061: }
2062:
2063: *fretone=(*funcone)(p);
2064: if(*globpri !=0){
2065: fclose(ficresilk);
2066: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2067: fflush(fichtm);
2068: }
2069: return;
2070: }
2071:
2072:
2073: /*********** Maximum Likelihood Estimation ***************/
2074:
2075: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2076: {
2077: int i,j, iter;
2078: double **xi;
2079: double fret;
2080: double fretone; /* Only one call to likelihood */
2081: /* char filerespow[FILENAMELENGTH];*/
2082: xi=matrix(1,npar,1,npar);
2083: for (i=1;i<=npar;i++)
2084: for (j=1;j<=npar;j++)
2085: xi[i][j]=(i==j ? 1.0 : 0.0);
2086: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2087: strcpy(filerespow,"pow");
2088: strcat(filerespow,fileres);
2089: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2090: printf("Problem with resultfile: %s\n", filerespow);
2091: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2092: }
2093: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2094: for (i=1;i<=nlstate;i++)
2095: for(j=1;j<=nlstate+ndeath;j++)
2096: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2097: fprintf(ficrespow,"\n");
2098:
2099: powell(p,xi,npar,ftol,&iter,&fret,func);
2100:
2101: free_matrix(xi,1,npar,1,npar);
2102: fclose(ficrespow);
2103: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
2104: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2105: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2106:
2107: }
2108:
2109: /**** Computes Hessian and covariance matrix ***/
2110: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2111: {
2112: double **a,**y,*x,pd;
2113: double **hess;
2114: int i, j,jk;
2115: int *indx;
2116:
2117: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2118: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2119: void lubksb(double **a, int npar, int *indx, double b[]) ;
2120: void ludcmp(double **a, int npar, int *indx, double *d) ;
2121: double gompertz(double p[]);
2122: hess=matrix(1,npar,1,npar);
2123:
2124: printf("\nCalculation of the hessian matrix. Wait...\n");
2125: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2126: for (i=1;i<=npar;i++){
2127: printf("%d",i);fflush(stdout);
2128: fprintf(ficlog,"%d",i);fflush(ficlog);
2129:
2130: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2131:
2132: /* printf(" %f ",p[i]);
2133: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2134: }
2135:
2136: for (i=1;i<=npar;i++) {
2137: for (j=1;j<=npar;j++) {
2138: if (j>i) {
2139: printf(".%d%d",i,j);fflush(stdout);
2140: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2141: hess[i][j]=hessij(p,delti,i,j,func,npar);
2142:
2143: hess[j][i]=hess[i][j];
2144: /*printf(" %lf ",hess[i][j]);*/
2145: }
2146: }
2147: }
2148: printf("\n");
2149: fprintf(ficlog,"\n");
2150:
2151: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2152: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2153:
2154: a=matrix(1,npar,1,npar);
2155: y=matrix(1,npar,1,npar);
2156: x=vector(1,npar);
2157: indx=ivector(1,npar);
2158: for (i=1;i<=npar;i++)
2159: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2160: ludcmp(a,npar,indx,&pd);
2161:
2162: for (j=1;j<=npar;j++) {
2163: for (i=1;i<=npar;i++) x[i]=0;
2164: x[j]=1;
2165: lubksb(a,npar,indx,x);
2166: for (i=1;i<=npar;i++){
2167: matcov[i][j]=x[i];
2168: }
2169: }
2170:
2171: printf("\n#Hessian matrix#\n");
2172: fprintf(ficlog,"\n#Hessian matrix#\n");
2173: for (i=1;i<=npar;i++) {
2174: for (j=1;j<=npar;j++) {
2175: printf("%.3e ",hess[i][j]);
2176: fprintf(ficlog,"%.3e ",hess[i][j]);
2177: }
2178: printf("\n");
2179: fprintf(ficlog,"\n");
2180: }
2181:
2182: /* Recompute Inverse */
2183: for (i=1;i<=npar;i++)
2184: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2185: ludcmp(a,npar,indx,&pd);
2186:
2187: /* printf("\n#Hessian matrix recomputed#\n");
2188:
2189: for (j=1;j<=npar;j++) {
2190: for (i=1;i<=npar;i++) x[i]=0;
2191: x[j]=1;
2192: lubksb(a,npar,indx,x);
2193: for (i=1;i<=npar;i++){
2194: y[i][j]=x[i];
2195: printf("%.3e ",y[i][j]);
2196: fprintf(ficlog,"%.3e ",y[i][j]);
2197: }
2198: printf("\n");
2199: fprintf(ficlog,"\n");
2200: }
2201: */
2202:
2203: free_matrix(a,1,npar,1,npar);
2204: free_matrix(y,1,npar,1,npar);
2205: free_vector(x,1,npar);
2206: free_ivector(indx,1,npar);
2207: free_matrix(hess,1,npar,1,npar);
2208:
2209:
2210: }
2211:
2212: /*************** hessian matrix ****************/
2213: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2214: {
2215: int i;
2216: int l=1, lmax=20;
2217: double k1,k2;
1.132 brouard 2218: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2219: double res;
2220: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2221: double fx;
2222: int k=0,kmax=10;
2223: double l1;
2224:
2225: fx=func(x);
2226: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2227: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2228: l1=pow(10,l);
2229: delts=delt;
2230: for(k=1 ; k <kmax; k=k+1){
2231: delt = delta*(l1*k);
2232: p2[theta]=x[theta] +delt;
1.145 brouard 2233: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2234: p2[theta]=x[theta]-delt;
2235: k2=func(p2)-fx;
2236: /*res= (k1-2.0*fx+k2)/delt/delt; */
2237: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2238:
1.132 brouard 2239: #ifdef DEBUGHESS
1.126 brouard 2240: 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);
2241: 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);
2242: #endif
2243: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2244: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2245: k=kmax;
2246: }
2247: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2248: k=kmax; l=lmax*10.;
2249: }
2250: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2251: delts=delt;
2252: }
2253: }
2254: }
2255: delti[theta]=delts;
2256: return res;
2257:
2258: }
2259:
2260: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2261: {
2262: int i;
2263: int l=1, l1, lmax=20;
2264: double k1,k2,k3,k4,res,fx;
1.132 brouard 2265: double p2[MAXPARM+1];
1.126 brouard 2266: int k;
2267:
2268: fx=func(x);
2269: for (k=1; k<=2; k++) {
2270: for (i=1;i<=npar;i++) p2[i]=x[i];
2271: p2[thetai]=x[thetai]+delti[thetai]/k;
2272: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2273: k1=func(p2)-fx;
2274:
2275: p2[thetai]=x[thetai]+delti[thetai]/k;
2276: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2277: k2=func(p2)-fx;
2278:
2279: p2[thetai]=x[thetai]-delti[thetai]/k;
2280: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2281: k3=func(p2)-fx;
2282:
2283: p2[thetai]=x[thetai]-delti[thetai]/k;
2284: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2285: k4=func(p2)-fx;
2286: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2287: #ifdef DEBUG
2288: 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);
2289: 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);
2290: #endif
2291: }
2292: return res;
2293: }
2294:
2295: /************** Inverse of matrix **************/
2296: void ludcmp(double **a, int n, int *indx, double *d)
2297: {
2298: int i,imax,j,k;
2299: double big,dum,sum,temp;
2300: double *vv;
2301:
2302: vv=vector(1,n);
2303: *d=1.0;
2304: for (i=1;i<=n;i++) {
2305: big=0.0;
2306: for (j=1;j<=n;j++)
2307: if ((temp=fabs(a[i][j])) > big) big=temp;
2308: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2309: vv[i]=1.0/big;
2310: }
2311: for (j=1;j<=n;j++) {
2312: for (i=1;i<j;i++) {
2313: sum=a[i][j];
2314: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2315: a[i][j]=sum;
2316: }
2317: big=0.0;
2318: for (i=j;i<=n;i++) {
2319: sum=a[i][j];
2320: for (k=1;k<j;k++)
2321: sum -= a[i][k]*a[k][j];
2322: a[i][j]=sum;
2323: if ( (dum=vv[i]*fabs(sum)) >= big) {
2324: big=dum;
2325: imax=i;
2326: }
2327: }
2328: if (j != imax) {
2329: for (k=1;k<=n;k++) {
2330: dum=a[imax][k];
2331: a[imax][k]=a[j][k];
2332: a[j][k]=dum;
2333: }
2334: *d = -(*d);
2335: vv[imax]=vv[j];
2336: }
2337: indx[j]=imax;
2338: if (a[j][j] == 0.0) a[j][j]=TINY;
2339: if (j != n) {
2340: dum=1.0/(a[j][j]);
2341: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2342: }
2343: }
2344: free_vector(vv,1,n); /* Doesn't work */
2345: ;
2346: }
2347:
2348: void lubksb(double **a, int n, int *indx, double b[])
2349: {
2350: int i,ii=0,ip,j;
2351: double sum;
2352:
2353: for (i=1;i<=n;i++) {
2354: ip=indx[i];
2355: sum=b[ip];
2356: b[ip]=b[i];
2357: if (ii)
2358: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2359: else if (sum) ii=i;
2360: b[i]=sum;
2361: }
2362: for (i=n;i>=1;i--) {
2363: sum=b[i];
2364: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2365: b[i]=sum/a[i][i];
2366: }
2367: }
2368:
2369: void pstamp(FILE *fichier)
2370: {
2371: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2372: }
2373:
2374: /************ Frequencies ********************/
2375: 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[])
2376: { /* Some frequencies */
2377:
1.130 brouard 2378: int i, m, jk, k1,i1, j1, bool, z1,j;
1.126 brouard 2379: int first;
2380: double ***freq; /* Frequencies */
2381: double *pp, **prop;
2382: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2383: char fileresp[FILENAMELENGTH];
2384:
2385: pp=vector(1,nlstate);
2386: prop=matrix(1,nlstate,iagemin,iagemax+3);
2387: strcpy(fileresp,"p");
2388: strcat(fileresp,fileres);
2389: if((ficresp=fopen(fileresp,"w"))==NULL) {
2390: printf("Problem with prevalence resultfile: %s\n", fileresp);
2391: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2392: exit(0);
2393: }
2394: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2395: j1=0;
2396:
2397: j=cptcoveff;
2398: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2399:
2400: first=1;
2401:
1.145 brouard 2402: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2403: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2404: /* j1++;
2405: */
2406: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2407: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2408: scanf("%d", i);*/
2409: for (i=-5; i<=nlstate+ndeath; i++)
2410: for (jk=-5; jk<=nlstate+ndeath; jk++)
2411: for(m=iagemin; m <= iagemax+3; m++)
2412: freq[i][jk][m]=0;
1.143 brouard 2413:
2414: for (i=1; i<=nlstate; i++)
2415: for(m=iagemin; m <= iagemax+3; m++)
2416: prop[i][m]=0;
1.126 brouard 2417:
2418: dateintsum=0;
2419: k2cpt=0;
2420: for (i=1; i<=imx; i++) {
2421: bool=1;
1.144 brouard 2422: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2423: for (z1=1; z1<=cptcoveff; z1++)
2424: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2425: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2426: bool=0;
1.145 brouard 2427: /* 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",
2428: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2429: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2430: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2431: }
1.126 brouard 2432: }
1.144 brouard 2433:
1.126 brouard 2434: if (bool==1){
2435: for(m=firstpass; m<=lastpass; m++){
2436: k2=anint[m][i]+(mint[m][i]/12.);
2437: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2438: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2439: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2440: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2441: if (m<lastpass) {
2442: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2443: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2444: }
2445:
2446: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2447: dateintsum=dateintsum+k2;
2448: k2cpt++;
2449: }
2450: /*}*/
2451: }
2452: }
1.145 brouard 2453: } /* end i */
1.126 brouard 2454:
2455: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2456: pstamp(ficresp);
2457: if (cptcovn>0) {
2458: fprintf(ficresp, "\n#********** Variable ");
2459: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2460: fprintf(ficresp, "**********\n#");
1.143 brouard 2461: fprintf(ficlog, "\n#********** Variable ");
2462: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2463: fprintf(ficlog, "**********\n#");
1.126 brouard 2464: }
2465: for(i=1; i<=nlstate;i++)
2466: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2467: fprintf(ficresp, "\n");
2468:
2469: for(i=iagemin; i <= iagemax+3; i++){
2470: if(i==iagemax+3){
2471: fprintf(ficlog,"Total");
2472: }else{
2473: if(first==1){
2474: first=0;
2475: printf("See log file for details...\n");
2476: }
2477: fprintf(ficlog,"Age %d", i);
2478: }
2479: for(jk=1; jk <=nlstate ; jk++){
2480: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2481: pp[jk] += freq[jk][m][i];
2482: }
2483: for(jk=1; jk <=nlstate ; jk++){
2484: for(m=-1, pos=0; m <=0 ; m++)
2485: pos += freq[jk][m][i];
2486: if(pp[jk]>=1.e-10){
2487: if(first==1){
1.132 brouard 2488: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2489: }
2490: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2491: }else{
2492: if(first==1)
2493: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2494: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2495: }
2496: }
2497:
2498: for(jk=1; jk <=nlstate ; jk++){
2499: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2500: pp[jk] += freq[jk][m][i];
2501: }
2502: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2503: pos += pp[jk];
2504: posprop += prop[jk][i];
2505: }
2506: for(jk=1; jk <=nlstate ; jk++){
2507: if(pos>=1.e-5){
2508: if(first==1)
2509: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2510: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2511: }else{
2512: if(first==1)
2513: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2514: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2515: }
2516: if( i <= iagemax){
2517: if(pos>=1.e-5){
2518: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2519: /*probs[i][jk][j1]= pp[jk]/pos;*/
2520: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2521: }
2522: else
2523: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2524: }
2525: }
2526:
2527: for(jk=-1; jk <=nlstate+ndeath; jk++)
2528: for(m=-1; m <=nlstate+ndeath; m++)
2529: if(freq[jk][m][i] !=0 ) {
2530: if(first==1)
2531: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2532: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2533: }
2534: if(i <= iagemax)
2535: fprintf(ficresp,"\n");
2536: if(first==1)
2537: printf("Others in log...\n");
2538: fprintf(ficlog,"\n");
2539: }
1.145 brouard 2540: /*}*/
1.126 brouard 2541: }
2542: dateintmean=dateintsum/k2cpt;
2543:
2544: fclose(ficresp);
2545: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2546: free_vector(pp,1,nlstate);
2547: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2548: /* End of Freq */
2549: }
2550:
2551: /************ Prevalence ********************/
2552: 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)
2553: {
2554: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2555: in each health status at the date of interview (if between dateprev1 and dateprev2).
2556: We still use firstpass and lastpass as another selection.
2557: */
2558:
1.130 brouard 2559: int i, m, jk, k1, i1, j1, bool, z1,j;
1.126 brouard 2560: double ***freq; /* Frequencies */
2561: double *pp, **prop;
2562: double pos,posprop;
2563: double y2; /* in fractional years */
2564: int iagemin, iagemax;
1.145 brouard 2565: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2566:
2567: iagemin= (int) agemin;
2568: iagemax= (int) agemax;
2569: /*pp=vector(1,nlstate);*/
2570: prop=matrix(1,nlstate,iagemin,iagemax+3);
2571: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2572: j1=0;
2573:
1.145 brouard 2574: /*j=cptcoveff;*/
1.126 brouard 2575: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2576:
1.145 brouard 2577: first=1;
2578: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2579: /*for(i1=1; i1<=ncodemax[k1];i1++){
2580: j1++;*/
1.126 brouard 2581:
2582: for (i=1; i<=nlstate; i++)
2583: for(m=iagemin; m <= iagemax+3; m++)
2584: prop[i][m]=0.0;
2585:
2586: for (i=1; i<=imx; i++) { /* Each individual */
2587: bool=1;
2588: if (cptcovn>0) {
2589: for (z1=1; z1<=cptcoveff; z1++)
2590: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2591: bool=0;
2592: }
2593: if (bool==1) {
2594: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2595: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2596: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2597: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2598: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2599: 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);
2600: if (s[m][i]>0 && s[m][i]<=nlstate) {
2601: /*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]]);*/
2602: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2603: prop[s[m][i]][iagemax+3] += weight[i];
2604: }
2605: }
2606: } /* end selection of waves */
2607: }
2608: }
2609: for(i=iagemin; i <= iagemax+3; i++){
2610: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2611: posprop += prop[jk][i];
2612: }
1.145 brouard 2613:
1.126 brouard 2614: for(jk=1; jk <=nlstate ; jk++){
2615: if( i <= iagemax){
2616: if(posprop>=1.e-5){
2617: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2618: } else{
2619: if(first==1){
2620: first=0;
2621: 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]);
2622: }
2623: }
1.126 brouard 2624: }
2625: }/* end jk */
2626: }/* end i */
1.145 brouard 2627: /*} *//* end i1 */
2628: } /* end j1 */
1.126 brouard 2629:
2630: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2631: /*free_vector(pp,1,nlstate);*/
2632: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2633: } /* End of prevalence */
2634:
2635: /************* Waves Concatenation ***************/
2636:
2637: 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)
2638: {
2639: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2640: Death is a valid wave (if date is known).
2641: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2642: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2643: and mw[mi+1][i]. dh depends on stepm.
2644: */
2645:
2646: int i, mi, m;
2647: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2648: double sum=0., jmean=0.;*/
2649: int first;
2650: int j, k=0,jk, ju, jl;
2651: double sum=0.;
2652: first=0;
2653: jmin=1e+5;
2654: jmax=-1;
2655: jmean=0.;
2656: for(i=1; i<=imx; i++){
2657: mi=0;
2658: m=firstpass;
2659: while(s[m][i] <= nlstate){
2660: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2661: mw[++mi][i]=m;
2662: if(m >=lastpass)
2663: break;
2664: else
2665: m++;
2666: }/* end while */
2667: if (s[m][i] > nlstate){
2668: mi++; /* Death is another wave */
2669: /* if(mi==0) never been interviewed correctly before death */
2670: /* Only death is a correct wave */
2671: mw[mi][i]=m;
2672: }
2673:
2674: wav[i]=mi;
2675: if(mi==0){
2676: nbwarn++;
2677: if(first==0){
2678: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2679: first=1;
2680: }
2681: if(first==1){
2682: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2683: }
2684: } /* end mi==0 */
2685: } /* End individuals */
2686:
2687: for(i=1; i<=imx; i++){
2688: for(mi=1; mi<wav[i];mi++){
2689: if (stepm <=0)
2690: dh[mi][i]=1;
2691: else{
2692: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2693: if (agedc[i] < 2*AGESUP) {
2694: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2695: if(j==0) j=1; /* Survives at least one month after exam */
2696: else if(j<0){
2697: nberr++;
2698: 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]);
2699: j=1; /* Temporary Dangerous patch */
2700: 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);
2701: 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]);
2702: 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);
2703: }
2704: k=k+1;
2705: if (j >= jmax){
2706: jmax=j;
2707: ijmax=i;
2708: }
2709: if (j <= jmin){
2710: jmin=j;
2711: ijmin=i;
2712: }
2713: sum=sum+j;
2714: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2715: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2716: }
2717: }
2718: else{
2719: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2720: /* 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]); */
2721:
2722: k=k+1;
2723: if (j >= jmax) {
2724: jmax=j;
2725: ijmax=i;
2726: }
2727: else if (j <= jmin){
2728: jmin=j;
2729: ijmin=i;
2730: }
2731: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2732: /*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]);*/
2733: if(j<0){
2734: nberr++;
2735: 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]);
2736: 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]);
2737: }
2738: sum=sum+j;
2739: }
2740: jk= j/stepm;
2741: jl= j -jk*stepm;
2742: ju= j -(jk+1)*stepm;
2743: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2744: if(jl==0){
2745: dh[mi][i]=jk;
2746: bh[mi][i]=0;
2747: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2748: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2749: dh[mi][i]=jk+1;
2750: bh[mi][i]=ju;
2751: }
2752: }else{
2753: if(jl <= -ju){
2754: dh[mi][i]=jk;
2755: bh[mi][i]=jl; /* bias is positive if real duration
2756: * is higher than the multiple of stepm and negative otherwise.
2757: */
2758: }
2759: else{
2760: dh[mi][i]=jk+1;
2761: bh[mi][i]=ju;
2762: }
2763: if(dh[mi][i]==0){
2764: dh[mi][i]=1; /* At least one step */
2765: bh[mi][i]=ju; /* At least one step */
2766: /* 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);*/
2767: }
2768: } /* end if mle */
2769: }
2770: } /* end wave */
2771: }
2772: jmean=sum/k;
2773: 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 2774: 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 2775: }
2776:
2777: /*********** Tricode ****************************/
1.145 brouard 2778: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2779: {
1.144 brouard 2780: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2781: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2782: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2783: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2784: /* nbcode[Tvar[j]][1]=
1.144 brouard 2785: */
1.130 brouard 2786:
1.145 brouard 2787: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2788: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2789: int cptcode=0; /* Modality max of covariates j */
2790: int modmincovj=0; /* Modality min of covariates j */
2791:
2792:
1.126 brouard 2793: cptcoveff=0;
2794:
1.145 brouard 2795: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2796: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2797:
1.145 brouard 2798: /* Loop on covariates without age and products */
2799: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2800: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2801: modality of this covariate Vj*/
1.145 brouard 2802: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2803: * If product of Vn*Vm, still boolean *:
2804: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2805: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2806: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2807: modality of the nth covariate of individual i. */
1.145 brouard 2808: if (ij > modmaxcovj)
2809: modmaxcovj=ij;
2810: else if (ij < modmincovj)
2811: modmincovj=ij;
2812: if ((ij < -1) && (ij > NCOVMAX)){
2813: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2814: exit(1);
2815: }else
1.136 brouard 2816: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2817: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2818: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2819: /* getting the maximum value of the modality of the covariate
2820: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2821: female is 1, then modmaxcovj=1.*/
1.126 brouard 2822: }
1.145 brouard 2823: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2824: cptcode=modmaxcovj;
1.137 brouard 2825: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2826: /*for (i=0; i<=cptcode; i++) {*/
2827: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2828: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2829: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2830: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2831: }
2832: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2833: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2834: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2835:
1.136 brouard 2836: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2837: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2838: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2839: modmincovj=3; modmaxcovj = 7;
2840: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2841: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2842: variables V1_1 and V1_2.
2843: nbcode[Tvar[j]][ij]=k;
2844: nbcode[Tvar[j]][1]=0;
2845: nbcode[Tvar[j]][2]=1;
2846: nbcode[Tvar[j]][3]=2;
2847: */
2848: ij=1; /* ij is similar to i but can jumps over null modalities */
2849: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2850: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2851: /*recode from 0 */
1.131 brouard 2852: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2853: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2854: k is a modality. If we have model=V1+V1*sex
2855: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2856: ij++;
2857: }
2858: if (ij > ncodemax[j]) break;
1.137 brouard 2859: } /* end of loop on */
2860: } /* end of loop on modality */
2861: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2862:
1.145 brouard 2863: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2864:
1.145 brouard 2865: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2866: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2867: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2868: Ndum[ij]++;
2869: }
1.126 brouard 2870:
2871: ij=1;
1.145 brouard 2872: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2873: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2874: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2875: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2876: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2877: ij++;
1.145 brouard 2878: }else
2879: Tvaraff[ij]=0;
1.126 brouard 2880: }
1.131 brouard 2881: ij--;
1.144 brouard 2882: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2883:
1.126 brouard 2884: }
2885:
1.145 brouard 2886:
1.126 brouard 2887: /*********** Health Expectancies ****************/
2888:
1.127 brouard 2889: 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 2890:
2891: {
2892: /* Health expectancies, no variances */
2893: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2894: int nhstepma, nstepma; /* Decreasing with age */
2895: double age, agelim, hf;
2896: double ***p3mat;
2897: double eip;
2898:
2899: pstamp(ficreseij);
2900: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2901: fprintf(ficreseij,"# Age");
2902: for(i=1; i<=nlstate;i++){
2903: for(j=1; j<=nlstate;j++){
2904: fprintf(ficreseij," e%1d%1d ",i,j);
2905: }
2906: fprintf(ficreseij," e%1d. ",i);
2907: }
2908: fprintf(ficreseij,"\n");
2909:
2910:
2911: if(estepm < stepm){
2912: printf ("Problem %d lower than %d\n",estepm, stepm);
2913: }
2914: else hstepm=estepm;
2915: /* We compute the life expectancy from trapezoids spaced every estepm months
2916: * This is mainly to measure the difference between two models: for example
2917: * if stepm=24 months pijx are given only every 2 years and by summing them
2918: * we are calculating an estimate of the Life Expectancy assuming a linear
2919: * progression in between and thus overestimating or underestimating according
2920: * to the curvature of the survival function. If, for the same date, we
2921: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2922: * to compare the new estimate of Life expectancy with the same linear
2923: * hypothesis. A more precise result, taking into account a more precise
2924: * curvature will be obtained if estepm is as small as stepm. */
2925:
2926: /* For example we decided to compute the life expectancy with the smallest unit */
2927: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2928: nhstepm is the number of hstepm from age to agelim
2929: nstepm is the number of stepm from age to agelin.
2930: Look at hpijx to understand the reason of that which relies in memory size
2931: and note for a fixed period like estepm months */
2932: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2933: survival function given by stepm (the optimization length). Unfortunately it
2934: means that if the survival funtion is printed only each two years of age and if
2935: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2936: results. So we changed our mind and took the option of the best precision.
2937: */
2938: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2939:
2940: agelim=AGESUP;
2941: /* If stepm=6 months */
2942: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2943: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2944:
2945: /* nhstepm age range expressed in number of stepm */
2946: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2947: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2948: /* if (stepm >= YEARM) hstepm=1;*/
2949: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2950: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2951:
2952: for (age=bage; age<=fage; age ++){
2953: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2954: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2955: /* if (stepm >= YEARM) hstepm=1;*/
2956: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2957:
2958: /* If stepm=6 months */
2959: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2960: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2961:
2962: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2963:
2964: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2965:
2966: printf("%d|",(int)age);fflush(stdout);
2967: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2968:
2969: /* Computing expectancies */
2970: for(i=1; i<=nlstate;i++)
2971: for(j=1; j<=nlstate;j++)
2972: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2973: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2974:
2975: /* 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]);*/
2976:
2977: }
2978:
2979: fprintf(ficreseij,"%3.0f",age );
2980: for(i=1; i<=nlstate;i++){
2981: eip=0;
2982: for(j=1; j<=nlstate;j++){
2983: eip +=eij[i][j][(int)age];
2984: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2985: }
2986: fprintf(ficreseij,"%9.4f", eip );
2987: }
2988: fprintf(ficreseij,"\n");
2989:
2990: }
2991: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2992: printf("\n");
2993: fprintf(ficlog,"\n");
2994:
2995: }
2996:
1.127 brouard 2997: 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 2998:
2999: {
3000: /* Covariances of health expectancies eij and of total life expectancies according
3001: to initial status i, ei. .
3002: */
3003: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3004: int nhstepma, nstepma; /* Decreasing with age */
3005: double age, agelim, hf;
3006: double ***p3matp, ***p3matm, ***varhe;
3007: double **dnewm,**doldm;
3008: double *xp, *xm;
3009: double **gp, **gm;
3010: double ***gradg, ***trgradg;
3011: int theta;
3012:
3013: double eip, vip;
3014:
3015: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3016: xp=vector(1,npar);
3017: xm=vector(1,npar);
3018: dnewm=matrix(1,nlstate*nlstate,1,npar);
3019: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3020:
3021: pstamp(ficresstdeij);
3022: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3023: fprintf(ficresstdeij,"# Age");
3024: for(i=1; i<=nlstate;i++){
3025: for(j=1; j<=nlstate;j++)
3026: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3027: fprintf(ficresstdeij," e%1d. ",i);
3028: }
3029: fprintf(ficresstdeij,"\n");
3030:
3031: pstamp(ficrescveij);
3032: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3033: fprintf(ficrescveij,"# Age");
3034: for(i=1; i<=nlstate;i++)
3035: for(j=1; j<=nlstate;j++){
3036: cptj= (j-1)*nlstate+i;
3037: for(i2=1; i2<=nlstate;i2++)
3038: for(j2=1; j2<=nlstate;j2++){
3039: cptj2= (j2-1)*nlstate+i2;
3040: if(cptj2 <= cptj)
3041: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3042: }
3043: }
3044: fprintf(ficrescveij,"\n");
3045:
3046: if(estepm < stepm){
3047: printf ("Problem %d lower than %d\n",estepm, stepm);
3048: }
3049: else hstepm=estepm;
3050: /* We compute the life expectancy from trapezoids spaced every estepm months
3051: * This is mainly to measure the difference between two models: for example
3052: * if stepm=24 months pijx are given only every 2 years and by summing them
3053: * we are calculating an estimate of the Life Expectancy assuming a linear
3054: * progression in between and thus overestimating or underestimating according
3055: * to the curvature of the survival function. If, for the same date, we
3056: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3057: * to compare the new estimate of Life expectancy with the same linear
3058: * hypothesis. A more precise result, taking into account a more precise
3059: * curvature will be obtained if estepm is as small as stepm. */
3060:
3061: /* For example we decided to compute the life expectancy with the smallest unit */
3062: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3063: nhstepm is the number of hstepm from age to agelim
3064: nstepm is the number of stepm from age to agelin.
3065: Look at hpijx to understand the reason of that which relies in memory size
3066: and note for a fixed period like estepm months */
3067: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3068: survival function given by stepm (the optimization length). Unfortunately it
3069: means that if the survival funtion is printed only each two years of age and if
3070: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3071: results. So we changed our mind and took the option of the best precision.
3072: */
3073: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3074:
3075: /* If stepm=6 months */
3076: /* nhstepm age range expressed in number of stepm */
3077: agelim=AGESUP;
3078: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3079: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3080: /* if (stepm >= YEARM) hstepm=1;*/
3081: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3082:
3083: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3084: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3085: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3086: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3087: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3088: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3089:
3090: for (age=bage; age<=fage; age ++){
3091: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3092: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3093: /* if (stepm >= YEARM) hstepm=1;*/
3094: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3095:
3096: /* If stepm=6 months */
3097: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3098: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3099:
3100: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3101:
3102: /* Computing Variances of health expectancies */
3103: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3104: decrease memory allocation */
3105: for(theta=1; theta <=npar; theta++){
3106: for(i=1; i<=npar; i++){
3107: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3108: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3109: }
3110: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3111: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3112:
3113: for(j=1; j<= nlstate; j++){
3114: for(i=1; i<=nlstate; i++){
3115: for(h=0; h<=nhstepm-1; h++){
3116: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3117: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3118: }
3119: }
3120: }
3121:
3122: for(ij=1; ij<= nlstate*nlstate; ij++)
3123: for(h=0; h<=nhstepm-1; h++){
3124: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3125: }
3126: }/* End theta */
3127:
3128:
3129: for(h=0; h<=nhstepm-1; h++)
3130: for(j=1; j<=nlstate*nlstate;j++)
3131: for(theta=1; theta <=npar; theta++)
3132: trgradg[h][j][theta]=gradg[h][theta][j];
3133:
3134:
3135: for(ij=1;ij<=nlstate*nlstate;ij++)
3136: for(ji=1;ji<=nlstate*nlstate;ji++)
3137: varhe[ij][ji][(int)age] =0.;
3138:
3139: printf("%d|",(int)age);fflush(stdout);
3140: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3141: for(h=0;h<=nhstepm-1;h++){
3142: for(k=0;k<=nhstepm-1;k++){
3143: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3144: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3145: for(ij=1;ij<=nlstate*nlstate;ij++)
3146: for(ji=1;ji<=nlstate*nlstate;ji++)
3147: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3148: }
3149: }
3150:
3151: /* Computing expectancies */
3152: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3153: for(i=1; i<=nlstate;i++)
3154: for(j=1; j<=nlstate;j++)
3155: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3156: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3157:
3158: /* 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]);*/
3159:
3160: }
3161:
3162: fprintf(ficresstdeij,"%3.0f",age );
3163: for(i=1; i<=nlstate;i++){
3164: eip=0.;
3165: vip=0.;
3166: for(j=1; j<=nlstate;j++){
3167: eip += eij[i][j][(int)age];
3168: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3169: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3170: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3171: }
3172: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3173: }
3174: fprintf(ficresstdeij,"\n");
3175:
3176: fprintf(ficrescveij,"%3.0f",age );
3177: for(i=1; i<=nlstate;i++)
3178: for(j=1; j<=nlstate;j++){
3179: cptj= (j-1)*nlstate+i;
3180: for(i2=1; i2<=nlstate;i2++)
3181: for(j2=1; j2<=nlstate;j2++){
3182: cptj2= (j2-1)*nlstate+i2;
3183: if(cptj2 <= cptj)
3184: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3185: }
3186: }
3187: fprintf(ficrescveij,"\n");
3188:
3189: }
3190: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3191: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3192: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3193: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3194: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3195: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3196: printf("\n");
3197: fprintf(ficlog,"\n");
3198:
3199: free_vector(xm,1,npar);
3200: free_vector(xp,1,npar);
3201: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3202: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3203: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3204: }
3205:
3206: /************ Variance ******************/
3207: 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[])
3208: {
3209: /* Variance of health expectancies */
3210: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3211: /* double **newm;*/
3212: double **dnewm,**doldm;
3213: double **dnewmp,**doldmp;
3214: int i, j, nhstepm, hstepm, h, nstepm ;
3215: int k, cptcode;
3216: double *xp;
3217: double **gp, **gm; /* for var eij */
3218: double ***gradg, ***trgradg; /*for var eij */
3219: double **gradgp, **trgradgp; /* for var p point j */
3220: double *gpp, *gmp; /* for var p point j */
3221: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3222: double ***p3mat;
3223: double age,agelim, hf;
3224: double ***mobaverage;
3225: int theta;
3226: char digit[4];
3227: char digitp[25];
3228:
3229: char fileresprobmorprev[FILENAMELENGTH];
3230:
3231: if(popbased==1){
3232: if(mobilav!=0)
3233: strcpy(digitp,"-populbased-mobilav-");
3234: else strcpy(digitp,"-populbased-nomobil-");
3235: }
3236: else
3237: strcpy(digitp,"-stablbased-");
3238:
3239: if (mobilav!=0) {
3240: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3241: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3242: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3243: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3244: }
3245: }
3246:
3247: strcpy(fileresprobmorprev,"prmorprev");
3248: sprintf(digit,"%-d",ij);
3249: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3250: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3251: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3252: strcat(fileresprobmorprev,fileres);
3253: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3254: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3255: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3256: }
3257: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3258:
3259: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3260: pstamp(ficresprobmorprev);
3261: 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);
3262: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3263: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3264: fprintf(ficresprobmorprev," p.%-d SE",j);
3265: for(i=1; i<=nlstate;i++)
3266: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3267: }
3268: fprintf(ficresprobmorprev,"\n");
3269: fprintf(ficgp,"\n# Routine varevsij");
3270: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3271: 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");
3272: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3273: /* } */
3274: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3275: pstamp(ficresvij);
3276: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3277: if(popbased==1)
1.128 brouard 3278: 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 3279: else
3280: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3281: fprintf(ficresvij,"# Age");
3282: for(i=1; i<=nlstate;i++)
3283: for(j=1; j<=nlstate;j++)
3284: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3285: fprintf(ficresvij,"\n");
3286:
3287: xp=vector(1,npar);
3288: dnewm=matrix(1,nlstate,1,npar);
3289: doldm=matrix(1,nlstate,1,nlstate);
3290: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3291: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3292:
3293: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3294: gpp=vector(nlstate+1,nlstate+ndeath);
3295: gmp=vector(nlstate+1,nlstate+ndeath);
3296: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3297:
3298: if(estepm < stepm){
3299: printf ("Problem %d lower than %d\n",estepm, stepm);
3300: }
3301: else hstepm=estepm;
3302: /* For example we decided to compute the life expectancy with the smallest unit */
3303: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3304: nhstepm is the number of hstepm from age to agelim
3305: nstepm is the number of stepm from age to agelin.
1.128 brouard 3306: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3307: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3308: survival function given by stepm (the optimization length). Unfortunately it
3309: means that if the survival funtion is printed every two years of age and if
3310: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3311: results. So we changed our mind and took the option of the best precision.
3312: */
3313: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3314: agelim = AGESUP;
3315: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3316: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3317: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3318: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3319: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3320: gp=matrix(0,nhstepm,1,nlstate);
3321: gm=matrix(0,nhstepm,1,nlstate);
3322:
3323:
3324: for(theta=1; theta <=npar; theta++){
3325: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3326: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3327: }
3328: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3329: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3330:
3331: if (popbased==1) {
3332: if(mobilav ==0){
3333: for(i=1; i<=nlstate;i++)
3334: prlim[i][i]=probs[(int)age][i][ij];
3335: }else{ /* mobilav */
3336: for(i=1; i<=nlstate;i++)
3337: prlim[i][i]=mobaverage[(int)age][i][ij];
3338: }
3339: }
3340:
3341: for(j=1; j<= nlstate; j++){
3342: for(h=0; h<=nhstepm; h++){
3343: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3344: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3345: }
3346: }
3347: /* This for computing probability of death (h=1 means
3348: computed over hstepm matrices product = hstepm*stepm months)
3349: as a weighted average of prlim.
3350: */
3351: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3352: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3353: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3354: }
3355: /* end probability of death */
3356:
3357: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3358: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3359: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3360: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3361:
3362: if (popbased==1) {
3363: if(mobilav ==0){
3364: for(i=1; i<=nlstate;i++)
3365: prlim[i][i]=probs[(int)age][i][ij];
3366: }else{ /* mobilav */
3367: for(i=1; i<=nlstate;i++)
3368: prlim[i][i]=mobaverage[(int)age][i][ij];
3369: }
3370: }
3371:
1.128 brouard 3372: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3373: for(h=0; h<=nhstepm; h++){
3374: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3375: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3376: }
3377: }
3378: /* This for computing probability of death (h=1 means
3379: computed over hstepm matrices product = hstepm*stepm months)
3380: as a weighted average of prlim.
3381: */
3382: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3383: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3384: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3385: }
3386: /* end probability of death */
3387:
3388: for(j=1; j<= nlstate; j++) /* vareij */
3389: for(h=0; h<=nhstepm; h++){
3390: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3391: }
3392:
3393: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3394: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3395: }
3396:
3397: } /* End theta */
3398:
3399: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3400:
3401: for(h=0; h<=nhstepm; h++) /* veij */
3402: for(j=1; j<=nlstate;j++)
3403: for(theta=1; theta <=npar; theta++)
3404: trgradg[h][j][theta]=gradg[h][theta][j];
3405:
3406: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3407: for(theta=1; theta <=npar; theta++)
3408: trgradgp[j][theta]=gradgp[theta][j];
3409:
3410:
3411: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3412: for(i=1;i<=nlstate;i++)
3413: for(j=1;j<=nlstate;j++)
3414: vareij[i][j][(int)age] =0.;
3415:
3416: for(h=0;h<=nhstepm;h++){
3417: for(k=0;k<=nhstepm;k++){
3418: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3419: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3420: for(i=1;i<=nlstate;i++)
3421: for(j=1;j<=nlstate;j++)
3422: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3423: }
3424: }
3425:
3426: /* pptj */
3427: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3428: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3429: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3430: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3431: varppt[j][i]=doldmp[j][i];
3432: /* end ppptj */
3433: /* x centered again */
3434: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3435: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3436:
3437: if (popbased==1) {
3438: if(mobilav ==0){
3439: for(i=1; i<=nlstate;i++)
3440: prlim[i][i]=probs[(int)age][i][ij];
3441: }else{ /* mobilav */
3442: for(i=1; i<=nlstate;i++)
3443: prlim[i][i]=mobaverage[(int)age][i][ij];
3444: }
3445: }
3446:
3447: /* This for computing probability of death (h=1 means
3448: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3449: as a weighted average of prlim.
3450: */
3451: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3452: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3453: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3454: }
3455: /* end probability of death */
3456:
3457: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3458: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3459: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3460: for(i=1; i<=nlstate;i++){
3461: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3462: }
3463: }
3464: fprintf(ficresprobmorprev,"\n");
3465:
3466: fprintf(ficresvij,"%.0f ",age );
3467: for(i=1; i<=nlstate;i++)
3468: for(j=1; j<=nlstate;j++){
3469: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3470: }
3471: fprintf(ficresvij,"\n");
3472: free_matrix(gp,0,nhstepm,1,nlstate);
3473: free_matrix(gm,0,nhstepm,1,nlstate);
3474: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3475: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3476: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3477: } /* End age */
3478: free_vector(gpp,nlstate+1,nlstate+ndeath);
3479: free_vector(gmp,nlstate+1,nlstate+ndeath);
3480: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3481: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3482: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3483: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3484: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3485: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3486: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3487: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3488: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3489: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3490: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3491: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3492: 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);
3493: /* 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);
3494: */
3495: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3496: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3497:
3498: free_vector(xp,1,npar);
3499: free_matrix(doldm,1,nlstate,1,nlstate);
3500: free_matrix(dnewm,1,nlstate,1,npar);
3501: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3502: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3503: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3504: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3505: fclose(ficresprobmorprev);
3506: fflush(ficgp);
3507: fflush(fichtm);
3508: } /* end varevsij */
3509:
3510: /************ Variance of prevlim ******************/
3511: 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[])
3512: {
3513: /* Variance of prevalence limit */
3514: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3515: double **newm;
3516: double **dnewm,**doldm;
3517: int i, j, nhstepm, hstepm;
3518: int k, cptcode;
3519: double *xp;
3520: double *gp, *gm;
3521: double **gradg, **trgradg;
3522: double age,agelim;
3523: int theta;
3524:
3525: pstamp(ficresvpl);
3526: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3527: fprintf(ficresvpl,"# Age");
3528: for(i=1; i<=nlstate;i++)
3529: fprintf(ficresvpl," %1d-%1d",i,i);
3530: fprintf(ficresvpl,"\n");
3531:
3532: xp=vector(1,npar);
3533: dnewm=matrix(1,nlstate,1,npar);
3534: doldm=matrix(1,nlstate,1,nlstate);
3535:
3536: hstepm=1*YEARM; /* Every year of age */
3537: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3538: agelim = AGESUP;
3539: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3540: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3541: if (stepm >= YEARM) hstepm=1;
3542: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3543: gradg=matrix(1,npar,1,nlstate);
3544: gp=vector(1,nlstate);
3545: gm=vector(1,nlstate);
3546:
3547: for(theta=1; theta <=npar; theta++){
3548: for(i=1; i<=npar; i++){ /* Computes gradient */
3549: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3550: }
3551: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3552: for(i=1;i<=nlstate;i++)
3553: gp[i] = prlim[i][i];
3554:
3555: for(i=1; i<=npar; i++) /* Computes gradient */
3556: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3557: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3558: for(i=1;i<=nlstate;i++)
3559: gm[i] = prlim[i][i];
3560:
3561: for(i=1;i<=nlstate;i++)
3562: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3563: } /* End theta */
3564:
3565: trgradg =matrix(1,nlstate,1,npar);
3566:
3567: for(j=1; j<=nlstate;j++)
3568: for(theta=1; theta <=npar; theta++)
3569: trgradg[j][theta]=gradg[theta][j];
3570:
3571: for(i=1;i<=nlstate;i++)
3572: varpl[i][(int)age] =0.;
3573: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3574: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3575: for(i=1;i<=nlstate;i++)
3576: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3577:
3578: fprintf(ficresvpl,"%.0f ",age );
3579: for(i=1; i<=nlstate;i++)
3580: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3581: fprintf(ficresvpl,"\n");
3582: free_vector(gp,1,nlstate);
3583: free_vector(gm,1,nlstate);
3584: free_matrix(gradg,1,npar,1,nlstate);
3585: free_matrix(trgradg,1,nlstate,1,npar);
3586: } /* End age */
3587:
3588: free_vector(xp,1,npar);
3589: free_matrix(doldm,1,nlstate,1,npar);
3590: free_matrix(dnewm,1,nlstate,1,nlstate);
3591:
3592: }
3593:
3594: /************ Variance of one-step probabilities ******************/
3595: 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[])
3596: {
3597: int i, j=0, i1, k1, l1, t, tj;
3598: int k2, l2, j1, z1;
3599: int k=0,l, cptcode;
1.145 brouard 3600: int first=1, first1, first2;
1.126 brouard 3601: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3602: double **dnewm,**doldm;
3603: double *xp;
3604: double *gp, *gm;
3605: double **gradg, **trgradg;
3606: double **mu;
1.145 brouard 3607: double age,agelim, cov[NCOVMAX+1];
1.126 brouard 3608: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3609: int theta;
3610: char fileresprob[FILENAMELENGTH];
3611: char fileresprobcov[FILENAMELENGTH];
3612: char fileresprobcor[FILENAMELENGTH];
3613: double ***varpij;
3614:
3615: strcpy(fileresprob,"prob");
3616: strcat(fileresprob,fileres);
3617: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3618: printf("Problem with resultfile: %s\n", fileresprob);
3619: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3620: }
3621: strcpy(fileresprobcov,"probcov");
3622: strcat(fileresprobcov,fileres);
3623: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3624: printf("Problem with resultfile: %s\n", fileresprobcov);
3625: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3626: }
3627: strcpy(fileresprobcor,"probcor");
3628: strcat(fileresprobcor,fileres);
3629: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3630: printf("Problem with resultfile: %s\n", fileresprobcor);
3631: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3632: }
3633: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3634: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3635: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3636: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3637: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3638: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3639: pstamp(ficresprob);
3640: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3641: fprintf(ficresprob,"# Age");
3642: pstamp(ficresprobcov);
3643: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3644: fprintf(ficresprobcov,"# Age");
3645: pstamp(ficresprobcor);
3646: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3647: fprintf(ficresprobcor,"# Age");
3648:
3649:
3650: for(i=1; i<=nlstate;i++)
3651: for(j=1; j<=(nlstate+ndeath);j++){
3652: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3653: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3654: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3655: }
3656: /* fprintf(ficresprob,"\n");
3657: fprintf(ficresprobcov,"\n");
3658: fprintf(ficresprobcor,"\n");
3659: */
1.131 brouard 3660: xp=vector(1,npar);
1.126 brouard 3661: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3662: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3663: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3664: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3665: first=1;
3666: fprintf(ficgp,"\n# Routine varprob");
3667: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3668: fprintf(fichtm,"\n");
3669:
3670: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3671: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3672: file %s<br>\n",optionfilehtmcov);
3673: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3674: and drawn. It helps understanding how is the covariance between two incidences.\
3675: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3676: 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. \
3677: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3678: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3679: standard deviations wide on each axis. <br>\
3680: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3681: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3682: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3683:
3684: cov[1]=1;
1.145 brouard 3685: /* tj=cptcoveff; */
3686: tj = (int) pow(2,cptcoveff);
1.126 brouard 3687: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3688: j1=0;
1.145 brouard 3689: for(j1=1; j1<=tj;j1++){
3690: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3691: /*j1++;*/
1.126 brouard 3692: if (cptcovn>0) {
3693: fprintf(ficresprob, "\n#********** Variable ");
3694: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3695: fprintf(ficresprob, "**********\n#\n");
3696: fprintf(ficresprobcov, "\n#********** Variable ");
3697: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3698: fprintf(ficresprobcov, "**********\n#\n");
3699:
3700: fprintf(ficgp, "\n#********** Variable ");
3701: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3702: fprintf(ficgp, "**********\n#\n");
3703:
3704:
3705: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3706: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3707: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3708:
3709: fprintf(ficresprobcor, "\n#********** Variable ");
3710: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3711: fprintf(ficresprobcor, "**********\n#");
3712: }
3713:
1.145 brouard 3714: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3715: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3716: gp=vector(1,(nlstate)*(nlstate+ndeath));
3717: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3718: for (age=bage; age<=fage; age ++){
3719: cov[2]=age;
3720: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3721: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3722: * 1 1 1 1 1
3723: * 2 2 1 1 1
3724: * 3 1 2 1 1
3725: */
3726: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3727: }
3728: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3729: for (k=1; k<=cptcovprod;k++)
3730: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3731:
3732:
3733: for(theta=1; theta <=npar; theta++){
3734: for(i=1; i<=npar; i++)
3735: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3736:
3737: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3738:
3739: k=0;
3740: for(i=1; i<= (nlstate); i++){
3741: for(j=1; j<=(nlstate+ndeath);j++){
3742: k=k+1;
3743: gp[k]=pmmij[i][j];
3744: }
3745: }
3746:
3747: for(i=1; i<=npar; i++)
3748: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3749:
3750: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3751: k=0;
3752: for(i=1; i<=(nlstate); i++){
3753: for(j=1; j<=(nlstate+ndeath);j++){
3754: k=k+1;
3755: gm[k]=pmmij[i][j];
3756: }
3757: }
3758:
3759: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3760: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3761: }
3762:
3763: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3764: for(theta=1; theta <=npar; theta++)
3765: trgradg[j][theta]=gradg[theta][j];
3766:
3767: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3768: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3769:
3770: pmij(pmmij,cov,ncovmodel,x,nlstate);
3771:
3772: k=0;
3773: for(i=1; i<=(nlstate); i++){
3774: for(j=1; j<=(nlstate+ndeath);j++){
3775: k=k+1;
3776: mu[k][(int) age]=pmmij[i][j];
3777: }
3778: }
3779: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3780: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3781: varpij[i][j][(int)age] = doldm[i][j];
3782:
3783: /*printf("\n%d ",(int)age);
3784: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3785: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3786: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3787: }*/
3788:
3789: fprintf(ficresprob,"\n%d ",(int)age);
3790: fprintf(ficresprobcov,"\n%d ",(int)age);
3791: fprintf(ficresprobcor,"\n%d ",(int)age);
3792:
3793: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3794: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3795: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3796: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3797: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3798: }
3799: i=0;
3800: for (k=1; k<=(nlstate);k++){
3801: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3802: i++;
1.126 brouard 3803: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3804: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3805: for (j=1; j<=i;j++){
1.145 brouard 3806: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3807: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3808: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3809: }
3810: }
3811: }/* end of loop for state */
3812: } /* end of loop for age */
1.145 brouard 3813: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3814: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3815: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3816: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3817:
1.126 brouard 3818: /* Confidence intervalle of pij */
3819: /*
1.131 brouard 3820: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3821: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3822: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3823: 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);
3824: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3825: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3826: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3827: */
3828:
3829: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3830: first1=1;first2=2;
1.126 brouard 3831: for (k2=1; k2<=(nlstate);k2++){
3832: for (l2=1; l2<=(nlstate+ndeath);l2++){
3833: if(l2==k2) continue;
3834: j=(k2-1)*(nlstate+ndeath)+l2;
3835: for (k1=1; k1<=(nlstate);k1++){
3836: for (l1=1; l1<=(nlstate+ndeath);l1++){
3837: if(l1==k1) continue;
3838: i=(k1-1)*(nlstate+ndeath)+l1;
3839: if(i<=j) continue;
3840: for (age=bage; age<=fage; age ++){
3841: if ((int)age %5==0){
3842: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3843: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3844: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3845: mu1=mu[i][(int) age]/stepm*YEARM ;
3846: mu2=mu[j][(int) age]/stepm*YEARM;
3847: c12=cv12/sqrt(v1*v2);
3848: /* Computing eigen value of matrix of covariance */
3849: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3850: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3851: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3852: if(first2==1){
3853: first1=0;
3854: 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);
3855: }
3856: 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);
3857: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3858: /* lc2=fabs(lc2); */
1.135 brouard 3859: }
3860:
1.126 brouard 3861: /* Eigen vectors */
3862: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3863: /*v21=sqrt(1.-v11*v11); *//* error */
3864: v21=(lc1-v1)/cv12*v11;
3865: v12=-v21;
3866: v22=v11;
3867: tnalp=v21/v11;
3868: if(first1==1){
3869: first1=0;
3870: 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);
3871: }
3872: 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);
3873: /*printf(fignu*/
3874: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3875: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3876: if(first==1){
3877: first=0;
3878: fprintf(ficgp,"\nset parametric;unset label");
3879: 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 3880: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3881: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3882: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3883: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3884: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3885: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3886: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3887: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3888: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3889: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3890: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3891: 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",\
3892: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3893: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3894: }else{
3895: first=0;
3896: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3897: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3898: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3899: 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",\
3900: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3901: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3902: }/* if first */
3903: } /* age mod 5 */
3904: } /* end loop age */
3905: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3906: first=1;
3907: } /*l12 */
3908: } /* k12 */
3909: } /*l1 */
3910: }/* k1 */
1.145 brouard 3911: /* } /* loop covariates */
1.126 brouard 3912: }
3913: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3914: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3915: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3916: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3917: free_vector(xp,1,npar);
3918: fclose(ficresprob);
3919: fclose(ficresprobcov);
3920: fclose(ficresprobcor);
3921: fflush(ficgp);
3922: fflush(fichtmcov);
3923: }
3924:
3925:
3926: /******************* Printing html file ***********/
3927: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3928: int lastpass, int stepm, int weightopt, char model[],\
3929: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3930: int popforecast, int estepm ,\
3931: double jprev1, double mprev1,double anprev1, \
3932: double jprev2, double mprev2,double anprev2){
3933: int jj1, k1, i1, cpt;
3934:
3935: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3936: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3937: </ul>");
3938: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3939: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3940: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3941: fprintf(fichtm,"\
3942: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3943: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3944: fprintf(fichtm,"\
3945: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3946: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3947: fprintf(fichtm,"\
1.128 brouard 3948: - (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 3949: <a href=\"%s\">%s</a> <br>\n",
3950: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3951: fprintf(fichtm,"\
3952: - Population projections by age and states: \
3953: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3954:
3955: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3956:
1.145 brouard 3957: m=pow(2,cptcoveff);
1.126 brouard 3958: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3959:
3960: jj1=0;
3961: for(k1=1; k1<=m;k1++){
3962: for(i1=1; i1<=ncodemax[k1];i1++){
3963: jj1++;
3964: if (cptcovn > 0) {
3965: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3966: for (cpt=1; cpt<=cptcoveff;cpt++)
3967: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3968: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3969: }
3970: /* Pij */
1.145 brouard 3971: 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> \
3972: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3973: /* Quasi-incidences */
3974: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 3975: 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> \
3976: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3977: /* Period (stable) prevalence in each health state */
1.154 brouard 3978: for(cpt=1; cpt<=nlstate;cpt++){
3979: 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> \
3980: <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 3981: }
3982: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 3983: 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> \
3984: <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 3985: }
3986: } /* end i1 */
3987: }/* End k1 */
3988: fprintf(fichtm,"</ul>");
3989:
3990:
3991: fprintf(fichtm,"\
3992: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3993: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3994:
3995: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3996: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3997: fprintf(fichtm,"\
3998: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3999: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4000:
4001: fprintf(fichtm,"\
4002: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4003: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4004: fprintf(fichtm,"\
4005: - 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): \
4006: <a href=\"%s\">%s</a> <br>\n</li>",
4007: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4008: fprintf(fichtm,"\
4009: - (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): \
4010: <a href=\"%s\">%s</a> <br>\n</li>",
4011: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4012: fprintf(fichtm,"\
1.128 brouard 4013: - 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 4014: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4015: fprintf(fichtm,"\
1.128 brouard 4016: - 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",
4017: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4018: fprintf(fichtm,"\
4019: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4020: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4021:
4022: /* if(popforecast==1) fprintf(fichtm,"\n */
4023: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4024: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4025: /* <br>",fileres,fileres,fileres,fileres); */
4026: /* else */
4027: /* 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); */
4028: fflush(fichtm);
4029: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4030:
1.145 brouard 4031: m=pow(2,cptcoveff);
1.126 brouard 4032: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4033:
4034: jj1=0;
4035: for(k1=1; k1<=m;k1++){
4036: for(i1=1; i1<=ncodemax[k1];i1++){
4037: jj1++;
4038: if (cptcovn > 0) {
4039: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4040: for (cpt=1; cpt<=cptcoveff;cpt++)
4041: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4042: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4043: }
4044: for(cpt=1; cpt<=nlstate;cpt++) {
4045: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4046: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4047: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4048: }
4049: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4050: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4051: true period expectancies (those weighted with period prevalences are also\
4052: drawn in addition to the population based expectancies computed using\
4053: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4054: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4055: } /* end i1 */
4056: }/* End k1 */
4057: fprintf(fichtm,"</ul>");
4058: fflush(fichtm);
4059: }
4060:
4061: /******************* Gnuplot file **************/
4062: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4063:
4064: char dirfileres[132],optfileres[132];
1.130 brouard 4065: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4066: int ng=0;
1.126 brouard 4067: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4068: /* printf("Problem with file %s",optionfilegnuplot); */
4069: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4070: /* } */
4071:
4072: /*#ifdef windows */
4073: fprintf(ficgp,"cd \"%s\" \n",pathc);
4074: /*#endif */
4075: m=pow(2,cptcoveff);
4076:
4077: strcpy(dirfileres,optionfilefiname);
4078: strcpy(optfileres,"vpl");
4079: /* 1eme*/
1.153 brouard 4080: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4081: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4082: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4083: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4084: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4085: fprintf(ficgp,"set xlabel \"Age\" \n\
4086: set ylabel \"Probability\" \n\
1.145 brouard 4087: set ter png small size 320, 240\n\
1.126 brouard 4088: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4089:
4090: for (i=1; i<= nlstate ; i ++) {
4091: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4092: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4093: }
1.145 brouard 4094: 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 4095: for (i=1; i<= nlstate ; i ++) {
4096: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4097: else fprintf(ficgp," \%%*lf (\%%*lf)");
4098: }
1.145 brouard 4099: 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 4100: for (i=1; i<= nlstate ; i ++) {
4101: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4102: else fprintf(ficgp," \%%*lf (\%%*lf)");
4103: }
1.145 brouard 4104: 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 4105: }
4106: }
4107: /*2 eme*/
1.153 brouard 4108: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4109: for (k1=1; k1<= m ; k1 ++) {
4110: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4111: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4112:
4113: for (i=1; i<= nlstate+1 ; i ++) {
4114: k=2*i;
4115: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4116: for (j=1; j<= nlstate+1 ; j ++) {
4117: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4118: else fprintf(ficgp," \%%*lf (\%%*lf)");
4119: }
4120: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4121: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4122: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4123: for (j=1; j<= nlstate+1 ; j ++) {
4124: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4125: else fprintf(ficgp," \%%*lf (\%%*lf)");
4126: }
1.145 brouard 4127: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4128: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4129: for (j=1; j<= nlstate+1 ; j ++) {
4130: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4131: else fprintf(ficgp," \%%*lf (\%%*lf)");
4132: }
1.145 brouard 4133: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4134: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4135: }
4136: }
4137:
4138: /*3eme*/
4139:
4140: for (k1=1; k1<= m ; k1 ++) {
4141: for (cpt=1; cpt<= nlstate ; cpt ++) {
4142: /* k=2+nlstate*(2*cpt-2); */
4143: k=2+(nlstate+1)*(cpt-1);
4144: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4145: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4146: 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);
4147: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4148: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4149: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4150: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4151: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4152: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4153:
4154: */
4155: for (i=1; i< nlstate ; i ++) {
4156: 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);
4157: /* 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);*/
4158:
4159: }
4160: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4161: }
4162: }
4163:
4164: /* CV preval stable (period) */
1.153 brouard 4165: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4166: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4167: k=3;
1.153 brouard 4168: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4169: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4170: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4171: set ter png small size 320, 240\n\
1.126 brouard 4172: unset log y\n\
1.153 brouard 4173: plot [%.f:%.f] ", ageminpar, agemaxpar);
4174: for (i=1; i<= nlstate ; i ++){
4175: if(i==1)
4176: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4177: else
4178: fprintf(ficgp,", '' ");
1.154 brouard 4179: l=(nlstate+ndeath)*(i-1)+1;
4180: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4181: for (j=1; j<= (nlstate-1) ; j ++)
4182: fprintf(ficgp,"+$%d",k+l+j);
4183: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4184: } /* nlstate */
4185: fprintf(ficgp,"\n");
4186: } /* end cpt state*/
4187: } /* end covariate */
1.126 brouard 4188:
4189: /* proba elementaires */
4190: for(i=1,jk=1; i <=nlstate; i++){
4191: for(k=1; k <=(nlstate+ndeath); k++){
4192: if (k != i) {
4193: for(j=1; j <=ncovmodel; j++){
4194: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4195: jk++;
4196: fprintf(ficgp,"\n");
4197: }
4198: }
4199: }
4200: }
1.145 brouard 4201: /*goto avoid;*/
1.126 brouard 4202: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4203: for(jk=1; jk <=m; jk++) {
1.145 brouard 4204: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4205: if (ng==2)
4206: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4207: else
4208: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4209: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4210: i=1;
4211: for(k2=1; k2<=nlstate; k2++) {
4212: k3=i;
4213: for(k=1; k<=(nlstate+ndeath); k++) {
4214: if (k != k2){
4215: if(ng==2)
4216: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4217: else
4218: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4219: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4220: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4221: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4222: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4223: /* ij++; */
4224: /* } */
4225: /* else */
1.126 brouard 4226: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4227: }
4228: fprintf(ficgp,")/(1");
4229:
4230: for(k1=1; k1 <=nlstate; k1++){
4231: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4232: ij=1;
4233: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4234: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4235: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4236: /* ij++; */
4237: /* } */
4238: /* else */
1.126 brouard 4239: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4240: }
4241: fprintf(ficgp,")");
4242: }
4243: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4244: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4245: i=i+ncovmodel;
4246: }
4247: } /* end k */
4248: } /* end k2 */
4249: } /* end jk */
4250: } /* end ng */
1.145 brouard 4251: avoid:
1.126 brouard 4252: fflush(ficgp);
4253: } /* end gnuplot */
4254:
4255:
4256: /*************** Moving average **************/
4257: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4258:
4259: int i, cpt, cptcod;
4260: int modcovmax =1;
4261: int mobilavrange, mob;
4262: double age;
4263:
4264: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4265: a covariate has 2 modalities */
4266: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4267:
4268: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4269: if(mobilav==1) mobilavrange=5; /* default */
4270: else mobilavrange=mobilav;
4271: for (age=bage; age<=fage; age++)
4272: for (i=1; i<=nlstate;i++)
4273: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4274: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4275: /* We keep the original values on the extreme ages bage, fage and for
4276: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4277: we use a 5 terms etc. until the borders are no more concerned.
4278: */
4279: for (mob=3;mob <=mobilavrange;mob=mob+2){
4280: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4281: for (i=1; i<=nlstate;i++){
4282: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4283: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4284: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4285: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4286: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4287: }
4288: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4289: }
4290: }
4291: }/* end age */
4292: }/* end mob */
4293: }else return -1;
4294: return 0;
4295: }/* End movingaverage */
4296:
4297:
4298: /************** Forecasting ******************/
4299: 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){
4300: /* proj1, year, month, day of starting projection
4301: agemin, agemax range of age
4302: dateprev1 dateprev2 range of dates during which prevalence is computed
4303: anproj2 year of en of projection (same day and month as proj1).
4304: */
4305: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4306: int *popage;
4307: double agec; /* generic age */
4308: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4309: double *popeffectif,*popcount;
4310: double ***p3mat;
4311: double ***mobaverage;
4312: char fileresf[FILENAMELENGTH];
4313:
4314: agelim=AGESUP;
4315: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4316:
4317: strcpy(fileresf,"f");
4318: strcat(fileresf,fileres);
4319: if((ficresf=fopen(fileresf,"w"))==NULL) {
4320: printf("Problem with forecast resultfile: %s\n", fileresf);
4321: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4322: }
4323: printf("Computing forecasting: result on file '%s' \n", fileresf);
4324: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4325:
4326: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4327:
4328: if (mobilav!=0) {
4329: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4330: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4331: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4332: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4333: }
4334: }
4335:
4336: stepsize=(int) (stepm+YEARM-1)/YEARM;
4337: if (stepm<=12) stepsize=1;
4338: if(estepm < stepm){
4339: printf ("Problem %d lower than %d\n",estepm, stepm);
4340: }
4341: else hstepm=estepm;
4342:
4343: hstepm=hstepm/stepm;
4344: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4345: fractional in yp1 */
4346: anprojmean=yp;
4347: yp2=modf((yp1*12),&yp);
4348: mprojmean=yp;
4349: yp1=modf((yp2*30.5),&yp);
4350: jprojmean=yp;
4351: if(jprojmean==0) jprojmean=1;
4352: if(mprojmean==0) jprojmean=1;
4353:
4354: i1=cptcoveff;
4355: if (cptcovn < 1){i1=1;}
4356:
4357: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4358:
4359: fprintf(ficresf,"#****** Routine prevforecast **\n");
4360:
4361: /* if (h==(int)(YEARM*yearp)){ */
4362: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4363: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4364: k=k+1;
4365: fprintf(ficresf,"\n#******");
4366: for(j=1;j<=cptcoveff;j++) {
4367: 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]]);
4368: }
4369: fprintf(ficresf,"******\n");
4370: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4371: for(j=1; j<=nlstate+ndeath;j++){
4372: for(i=1; i<=nlstate;i++)
4373: fprintf(ficresf," p%d%d",i,j);
4374: fprintf(ficresf," p.%d",j);
4375: }
4376: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4377: fprintf(ficresf,"\n");
4378: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4379:
4380: for (agec=fage; agec>=(ageminpar-1); agec--){
4381: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4382: nhstepm = nhstepm/hstepm;
4383: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4384: oldm=oldms;savm=savms;
4385: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4386:
4387: for (h=0; h<=nhstepm; h++){
4388: if (h*hstepm/YEARM*stepm ==yearp) {
4389: fprintf(ficresf,"\n");
4390: for(j=1;j<=cptcoveff;j++)
4391: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4392: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4393: }
4394: for(j=1; j<=nlstate+ndeath;j++) {
4395: ppij=0.;
4396: for(i=1; i<=nlstate;i++) {
4397: if (mobilav==1)
4398: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4399: else {
4400: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4401: }
4402: if (h*hstepm/YEARM*stepm== yearp) {
4403: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4404: }
4405: } /* end i */
4406: if (h*hstepm/YEARM*stepm==yearp) {
4407: fprintf(ficresf," %.3f", ppij);
4408: }
4409: }/* end j */
4410: } /* end h */
4411: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4412: } /* end agec */
4413: } /* end yearp */
4414: } /* end cptcod */
4415: } /* end cptcov */
4416:
4417: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4418:
4419: fclose(ficresf);
4420: }
4421:
4422: /************** Forecasting *****not tested NB*************/
4423: 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){
4424:
4425: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4426: int *popage;
4427: double calagedatem, agelim, kk1, kk2;
4428: double *popeffectif,*popcount;
4429: double ***p3mat,***tabpop,***tabpopprev;
4430: double ***mobaverage;
4431: char filerespop[FILENAMELENGTH];
4432:
4433: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4434: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4435: agelim=AGESUP;
4436: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4437:
4438: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4439:
4440:
4441: strcpy(filerespop,"pop");
4442: strcat(filerespop,fileres);
4443: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4444: printf("Problem with forecast resultfile: %s\n", filerespop);
4445: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4446: }
4447: printf("Computing forecasting: result on file '%s' \n", filerespop);
4448: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4449:
4450: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4451:
4452: if (mobilav!=0) {
4453: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4454: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4455: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4456: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4457: }
4458: }
4459:
4460: stepsize=(int) (stepm+YEARM-1)/YEARM;
4461: if (stepm<=12) stepsize=1;
4462:
4463: agelim=AGESUP;
4464:
4465: hstepm=1;
4466: hstepm=hstepm/stepm;
4467:
4468: if (popforecast==1) {
4469: if((ficpop=fopen(popfile,"r"))==NULL) {
4470: printf("Problem with population file : %s\n",popfile);exit(0);
4471: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4472: }
4473: popage=ivector(0,AGESUP);
4474: popeffectif=vector(0,AGESUP);
4475: popcount=vector(0,AGESUP);
4476:
4477: i=1;
4478: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4479:
4480: imx=i;
4481: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4482: }
4483:
4484: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4485: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4486: k=k+1;
4487: fprintf(ficrespop,"\n#******");
4488: for(j=1;j<=cptcoveff;j++) {
4489: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4490: }
4491: fprintf(ficrespop,"******\n");
4492: fprintf(ficrespop,"# Age");
4493: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4494: if (popforecast==1) fprintf(ficrespop," [Population]");
4495:
4496: for (cpt=0; cpt<=0;cpt++) {
4497: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4498:
4499: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4500: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4501: nhstepm = nhstepm/hstepm;
4502:
4503: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4504: oldm=oldms;savm=savms;
4505: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4506:
4507: for (h=0; h<=nhstepm; h++){
4508: if (h==(int) (calagedatem+YEARM*cpt)) {
4509: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4510: }
4511: for(j=1; j<=nlstate+ndeath;j++) {
4512: kk1=0.;kk2=0;
4513: for(i=1; i<=nlstate;i++) {
4514: if (mobilav==1)
4515: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4516: else {
4517: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4518: }
4519: }
4520: if (h==(int)(calagedatem+12*cpt)){
4521: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4522: /*fprintf(ficrespop," %.3f", kk1);
4523: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4524: }
4525: }
4526: for(i=1; i<=nlstate;i++){
4527: kk1=0.;
4528: for(j=1; j<=nlstate;j++){
4529: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4530: }
4531: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4532: }
4533:
4534: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4535: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4536: }
4537: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4538: }
4539: }
4540:
4541: /******/
4542:
4543: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4544: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4545: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4546: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4547: nhstepm = nhstepm/hstepm;
4548:
4549: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4550: oldm=oldms;savm=savms;
4551: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4552: for (h=0; h<=nhstepm; h++){
4553: if (h==(int) (calagedatem+YEARM*cpt)) {
4554: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4555: }
4556: for(j=1; j<=nlstate+ndeath;j++) {
4557: kk1=0.;kk2=0;
4558: for(i=1; i<=nlstate;i++) {
4559: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4560: }
4561: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4562: }
4563: }
4564: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4565: }
4566: }
4567: }
4568: }
4569:
4570: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4571:
4572: if (popforecast==1) {
4573: free_ivector(popage,0,AGESUP);
4574: free_vector(popeffectif,0,AGESUP);
4575: free_vector(popcount,0,AGESUP);
4576: }
4577: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4578: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4579: fclose(ficrespop);
4580: } /* End of popforecast */
4581:
4582: int fileappend(FILE *fichier, char *optionfich)
4583: {
4584: if((fichier=fopen(optionfich,"a"))==NULL) {
4585: printf("Problem with file: %s\n", optionfich);
4586: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4587: return (0);
4588: }
4589: fflush(fichier);
4590: return (1);
4591: }
4592:
4593:
4594: /**************** function prwizard **********************/
4595: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4596: {
4597:
4598: /* Wizard to print covariance matrix template */
4599:
4600: char ca[32], cb[32], cc[32];
4601: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4602: int numlinepar;
4603:
4604: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4605: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4606: for(i=1; i <=nlstate; i++){
4607: jj=0;
4608: for(j=1; j <=nlstate+ndeath; j++){
4609: if(j==i) continue;
4610: jj++;
4611: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4612: printf("%1d%1d",i,j);
4613: fprintf(ficparo,"%1d%1d",i,j);
4614: for(k=1; k<=ncovmodel;k++){
4615: /* printf(" %lf",param[i][j][k]); */
4616: /* fprintf(ficparo," %lf",param[i][j][k]); */
4617: printf(" 0.");
4618: fprintf(ficparo," 0.");
4619: }
4620: printf("\n");
4621: fprintf(ficparo,"\n");
4622: }
4623: }
4624: printf("# Scales (for hessian or gradient estimation)\n");
4625: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4626: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4627: for(i=1; i <=nlstate; i++){
4628: jj=0;
4629: for(j=1; j <=nlstate+ndeath; j++){
4630: if(j==i) continue;
4631: jj++;
4632: fprintf(ficparo,"%1d%1d",i,j);
4633: printf("%1d%1d",i,j);
4634: fflush(stdout);
4635: for(k=1; k<=ncovmodel;k++){
4636: /* printf(" %le",delti3[i][j][k]); */
4637: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4638: printf(" 0.");
4639: fprintf(ficparo," 0.");
4640: }
4641: numlinepar++;
4642: printf("\n");
4643: fprintf(ficparo,"\n");
4644: }
4645: }
4646: printf("# Covariance matrix\n");
4647: /* # 121 Var(a12)\n\ */
4648: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4649: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4650: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4651: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4652: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4653: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4654: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4655: fflush(stdout);
4656: fprintf(ficparo,"# Covariance matrix\n");
4657: /* # 121 Var(a12)\n\ */
4658: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4659: /* # ...\n\ */
4660: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4661:
4662: for(itimes=1;itimes<=2;itimes++){
4663: jj=0;
4664: for(i=1; i <=nlstate; i++){
4665: for(j=1; j <=nlstate+ndeath; j++){
4666: if(j==i) continue;
4667: for(k=1; k<=ncovmodel;k++){
4668: jj++;
4669: ca[0]= k+'a'-1;ca[1]='\0';
4670: if(itimes==1){
4671: printf("#%1d%1d%d",i,j,k);
4672: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4673: }else{
4674: printf("%1d%1d%d",i,j,k);
4675: fprintf(ficparo,"%1d%1d%d",i,j,k);
4676: /* printf(" %.5le",matcov[i][j]); */
4677: }
4678: ll=0;
4679: for(li=1;li <=nlstate; li++){
4680: for(lj=1;lj <=nlstate+ndeath; lj++){
4681: if(lj==li) continue;
4682: for(lk=1;lk<=ncovmodel;lk++){
4683: ll++;
4684: if(ll<=jj){
4685: cb[0]= lk +'a'-1;cb[1]='\0';
4686: if(ll<jj){
4687: if(itimes==1){
4688: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4689: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4690: }else{
4691: printf(" 0.");
4692: fprintf(ficparo," 0.");
4693: }
4694: }else{
4695: if(itimes==1){
4696: printf(" Var(%s%1d%1d)",ca,i,j);
4697: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4698: }else{
4699: printf(" 0.");
4700: fprintf(ficparo," 0.");
4701: }
4702: }
4703: }
4704: } /* end lk */
4705: } /* end lj */
4706: } /* end li */
4707: printf("\n");
4708: fprintf(ficparo,"\n");
4709: numlinepar++;
4710: } /* end k*/
4711: } /*end j */
4712: } /* end i */
4713: } /* end itimes */
4714:
4715: } /* end of prwizard */
4716: /******************* Gompertz Likelihood ******************************/
4717: double gompertz(double x[])
4718: {
4719: double A,B,L=0.0,sump=0.,num=0.;
4720: int i,n=0; /* n is the size of the sample */
4721:
4722: for (i=0;i<=imx-1 ; i++) {
4723: sump=sump+weight[i];
4724: /* sump=sump+1;*/
4725: num=num+1;
4726: }
4727:
4728:
4729: /* for (i=0; i<=imx; i++)
4730: 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]);*/
4731:
4732: for (i=1;i<=imx ; i++)
4733: {
4734: if (cens[i] == 1 && wav[i]>1)
4735: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4736:
4737: if (cens[i] == 0 && wav[i]>1)
4738: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4739: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4740:
4741: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4742: if (wav[i] > 1 ) { /* ??? */
4743: L=L+A*weight[i];
4744: /* 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]);*/
4745: }
4746: }
4747:
4748: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4749:
4750: return -2*L*num/sump;
4751: }
4752:
1.136 brouard 4753: #ifdef GSL
4754: /******************* Gompertz_f Likelihood ******************************/
4755: double gompertz_f(const gsl_vector *v, void *params)
4756: {
4757: double A,B,LL=0.0,sump=0.,num=0.;
4758: double *x= (double *) v->data;
4759: int i,n=0; /* n is the size of the sample */
4760:
4761: for (i=0;i<=imx-1 ; i++) {
4762: sump=sump+weight[i];
4763: /* sump=sump+1;*/
4764: num=num+1;
4765: }
4766:
4767:
4768: /* for (i=0; i<=imx; i++)
4769: 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]);*/
4770: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4771: for (i=1;i<=imx ; i++)
4772: {
4773: if (cens[i] == 1 && wav[i]>1)
4774: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4775:
4776: if (cens[i] == 0 && wav[i]>1)
4777: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4778: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4779:
4780: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4781: if (wav[i] > 1 ) { /* ??? */
4782: LL=LL+A*weight[i];
4783: /* 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]);*/
4784: }
4785: }
4786:
4787: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4788: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4789:
4790: return -2*LL*num/sump;
4791: }
4792: #endif
4793:
1.126 brouard 4794: /******************* Printing html file ***********/
4795: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4796: int lastpass, int stepm, int weightopt, char model[],\
4797: int imx, double p[],double **matcov,double agemortsup){
4798: int i,k;
4799:
4800: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4801: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4802: for (i=1;i<=2;i++)
4803: 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]));
4804: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4805: fprintf(fichtm,"</ul>");
4806:
4807: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4808:
4809: 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>");
4810:
4811: for (k=agegomp;k<(agemortsup-2);k++)
4812: 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]);
4813:
4814:
4815: fflush(fichtm);
4816: }
4817:
4818: /******************* Gnuplot file **************/
4819: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4820:
4821: char dirfileres[132],optfileres[132];
4822: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4823: int ng;
4824:
4825:
4826: /*#ifdef windows */
4827: fprintf(ficgp,"cd \"%s\" \n",pathc);
4828: /*#endif */
4829:
4830:
4831: strcpy(dirfileres,optionfilefiname);
4832: strcpy(optfileres,"vpl");
4833: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4834: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4835: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4836: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4837: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4838:
4839: }
4840:
1.136 brouard 4841: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4842: {
1.126 brouard 4843:
1.136 brouard 4844: /*-------- data file ----------*/
4845: FILE *fic;
4846: char dummy[]=" ";
4847: int i, j, n;
4848: int linei, month, year,iout;
4849: char line[MAXLINE], linetmp[MAXLINE];
4850: char stra[80], strb[80];
4851: char *stratrunc;
4852: int lstra;
1.126 brouard 4853:
4854:
1.136 brouard 4855: if((fic=fopen(datafile,"r"))==NULL) {
4856: printf("Problem while opening datafile: %s\n", datafile);return 1;
4857: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4858: }
1.126 brouard 4859:
1.136 brouard 4860: i=1;
4861: linei=0;
4862: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4863: linei=linei+1;
4864: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4865: if(line[j] == '\t')
4866: line[j] = ' ';
4867: }
4868: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4869: ;
4870: };
4871: line[j+1]=0; /* Trims blanks at end of line */
4872: if(line[0]=='#'){
4873: fprintf(ficlog,"Comment line\n%s\n",line);
4874: printf("Comment line\n%s\n",line);
4875: continue;
4876: }
4877: trimbb(linetmp,line); /* Trims multiple blanks in line */
4878: for (j=0; line[j]!='\0';j++){
4879: line[j]=linetmp[j];
4880: }
4881:
1.126 brouard 4882:
1.136 brouard 4883: for (j=maxwav;j>=1;j--){
1.137 brouard 4884: cutv(stra, strb, line, ' ');
1.136 brouard 4885: if(strb[0]=='.') { /* Missing status */
4886: lval=-1;
4887: }else{
4888: errno=0;
4889: lval=strtol(strb,&endptr,10);
4890: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4891: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4892: 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);
4893: 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 4894: return 1;
4895: }
4896: }
4897: s[j][i]=lval;
4898:
4899: strcpy(line,stra);
4900: cutv(stra, strb,line,' ');
4901: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4902: }
1.145 brouard 4903: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 4904: month=99;
4905: year=9999;
4906: }else{
1.141 brouard 4907: 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);
4908: 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 4909: return 1;
4910: }
4911: anint[j][i]= (double) year;
4912: mint[j][i]= (double)month;
4913: strcpy(line,stra);
4914: } /* ENd Waves */
4915:
4916: cutv(stra, strb,line,' ');
4917: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4918: }
4919: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4920: month=99;
4921: year=9999;
4922: }else{
1.141 brouard 4923: 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);
4924: 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 4925: return 1;
4926: }
4927: andc[i]=(double) year;
4928: moisdc[i]=(double) month;
4929: strcpy(line,stra);
4930:
4931: cutv(stra, strb,line,' ');
4932: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4933: }
1.145 brouard 4934: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 4935: month=99;
4936: year=9999;
4937: }else{
1.141 brouard 4938: 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);
4939: 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 4940: return 1;
4941: }
4942: if (year==9999) {
1.141 brouard 4943: 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);
4944: 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 4945: return 1;
1.126 brouard 4946:
1.136 brouard 4947: }
4948: annais[i]=(double)(year);
4949: moisnais[i]=(double)(month);
4950: strcpy(line,stra);
4951:
4952: cutv(stra, strb,line,' ');
4953: errno=0;
4954: dval=strtod(strb,&endptr);
4955: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4956: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4957: 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 4958: fflush(ficlog);
4959: return 1;
4960: }
4961: weight[i]=dval;
4962: strcpy(line,stra);
4963:
4964: for (j=ncovcol;j>=1;j--){
4965: cutv(stra, strb,line,' ');
4966: if(strb[0]=='.') { /* Missing status */
4967: lval=-1;
4968: }else{
4969: errno=0;
4970: lval=strtol(strb,&endptr,10);
4971: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4972: 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);
4973: 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 4974: return 1;
4975: }
4976: }
4977: if(lval <-1 || lval >1){
1.141 brouard 4978: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4979: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4980: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4981: For example, for multinomial values like 1, 2 and 3,\n \
4982: build V1=0 V2=0 for the reference value (1),\n \
4983: V1=1 V2=0 for (2) \n \
4984: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4985: output of IMaCh is often meaningless.\n \
4986: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 4987: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4988: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4989: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4990: For example, for multinomial values like 1, 2 and 3,\n \
4991: build V1=0 V2=0 for the reference value (1),\n \
4992: V1=1 V2=0 for (2) \n \
4993: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4994: output of IMaCh is often meaningless.\n \
4995: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
4996: return 1;
4997: }
4998: covar[j][i]=(double)(lval);
4999: strcpy(line,stra);
5000: }
5001: lstra=strlen(stra);
5002:
5003: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5004: stratrunc = &(stra[lstra-9]);
5005: num[i]=atol(stratrunc);
5006: }
5007: else
5008: num[i]=atol(stra);
5009: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5010: 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;}*/
5011:
5012: i=i+1;
5013: } /* End loop reading data */
1.126 brouard 5014:
1.136 brouard 5015: *imax=i-1; /* Number of individuals */
5016: fclose(fic);
5017:
5018: return (0);
5019: endread:
5020: printf("Exiting readdata: ");
5021: fclose(fic);
5022: return (1);
1.126 brouard 5023:
5024:
5025:
1.136 brouard 5026: }
1.145 brouard 5027: void removespace(char *str) {
5028: char *p1 = str, *p2 = str;
5029: do
5030: while (*p2 == ' ')
5031: p2++;
5032: while (*p1++ = *p2++);
5033: }
5034:
5035: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5036: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5037: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5038: * - cptcovn or number of covariates k of the models excluding age*products =6
5039: * - cptcovage number of covariates with age*products =2
5040: * - cptcovs number of simple covariates
5041: * - 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
5042: * which is a new column after the 9 (ncovcol) variables.
5043: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5044: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5045: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5046: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5047: */
1.136 brouard 5048: {
1.145 brouard 5049: int i, j, k, ks;
1.136 brouard 5050: int i1, j1, k1, k2;
5051: char modelsav[80];
1.145 brouard 5052: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5053:
1.145 brouard 5054: /*removespace(model);*/
1.136 brouard 5055: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5056: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5057: j=nbocc(model,'+'); /**< j=Number of '+' */
5058: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5059: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5060: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5061: /* including age products which are counted in cptcovage.
5062: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5063: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5064: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5065: strcpy(modelsav,model);
1.137 brouard 5066: if (strstr(model,"AGE") !=0){
5067: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5068: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5069: return 1;
5070: }
1.141 brouard 5071: if (strstr(model,"v") !=0){
5072: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5073: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5074: return 1;
5075: }
1.136 brouard 5076:
1.145 brouard 5077: /* Design
5078: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5079: * < ncovcol=8 >
5080: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5081: * k= 1 2 3 4 5 6 7 8
5082: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5083: * covar[k,i], value of kth covariate if not including age for individual i:
5084: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5085: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5086: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5087: * Tage[++cptcovage]=k
5088: * if products, new covar are created after ncovcol with k1
5089: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5090: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5091: * 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
5092: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5093: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5094: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5095: * < ncovcol=8 >
5096: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5097: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5098: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5099: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5100: * p Tprod[1]@2={ 6, 5}
5101: *p Tvard[1][1]@4= {7, 8, 5, 6}
5102: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5103: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5104: *How to reorganize?
5105: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5106: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5107: * {2, 1, 4, 8, 5, 6, 3, 7}
5108: * Struct []
5109: */
5110:
1.136 brouard 5111: /* This loop fills the array Tvar from the string 'model'.*/
5112: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5113: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5114: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5115: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5116: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5117: /* k=1 Tvar[1]=2 (from V2) */
5118: /* k=5 Tvar[5] */
5119: /* for (k=1; k<=cptcovn;k++) { */
5120: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5121: /* } */
5122: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5123: /*
5124: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5125: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5126: Tvar[k]=0;
5127: cptcovage=0;
5128: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5129: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5130: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5131: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5132: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5133: /*scanf("%d",i);*/
1.145 brouard 5134: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5135: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5136: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5137: /* covar is not filled and then is empty */
1.136 brouard 5138: cptcovprod--;
1.145 brouard 5139: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5140: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5141: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5142: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5143: /*printf("stre=%s ", stre);*/
1.137 brouard 5144: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5145: cptcovprod--;
1.145 brouard 5146: cutl(stre,strb,strc,'V');
1.136 brouard 5147: Tvar[k]=atoi(stre);
5148: cptcovage++;
5149: Tage[cptcovage]=k;
1.137 brouard 5150: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5151: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5152: cptcovn++;
5153: cptcovprodnoage++;k1++;
5154: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5155: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5156: because this model-covariate is a construction we invent a new column
5157: ncovcol + k1
5158: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5159: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5160: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5161: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5162: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5163: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5164: k2=k2+2;
5165: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5166: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5167: for (i=1; i<=lastobs;i++){
5168: /* Computes the new covariate which is a product of
1.145 brouard 5169: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5170: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5171: }
5172: } /* End age is not in the model */
5173: } /* End if model includes a product */
1.136 brouard 5174: else { /* no more sum */
5175: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5176: /* scanf("%d",i);*/
1.145 brouard 5177: cutl(strd,strc,strb,'V');
5178: ks++; /**< Number of simple covariates */
5179: cptcovn++;
5180: Tvar[k]=atoi(strd);
1.136 brouard 5181: }
1.137 brouard 5182: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5183: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5184: scanf("%d",i);*/
5185: } /* end of loop + */
5186: } /* end model */
5187:
5188: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5189: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5190:
5191: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5192: printf("cptcovprod=%d ", cptcovprod);
5193: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5194:
5195: scanf("%d ",i);*/
5196:
5197:
1.137 brouard 5198: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.136 brouard 5199: endread:
5200: printf("Exiting decodemodel: ");
5201: return (1);
5202: }
5203:
5204: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5205: {
5206: int i, m;
5207:
5208: for (i=1; i<=imx; i++) {
5209: for(m=2; (m<= maxwav); m++) {
5210: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5211: anint[m][i]=9999;
5212: s[m][i]=-1;
5213: }
5214: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5215: *nberr++;
5216: 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);
5217: 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);
5218: s[m][i]=-1;
5219: }
5220: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5221: *nberr++;
5222: 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]);
5223: 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]);
5224: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5225: }
5226: }
5227: }
5228:
5229: for (i=1; i<=imx; i++) {
5230: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5231: for(m=firstpass; (m<= lastpass); m++){
5232: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5233: if (s[m][i] >= nlstate+1) {
5234: if(agedc[i]>0)
5235: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5236: agev[m][i]=agedc[i];
5237: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5238: else {
5239: if ((int)andc[i]!=9999){
5240: nbwarn++;
5241: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5242: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5243: agev[m][i]=-1;
5244: }
5245: }
5246: }
5247: else if(s[m][i] !=9){ /* Standard case, age in fractional
5248: years but with the precision of a month */
5249: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5250: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5251: agev[m][i]=1;
5252: else if(agev[m][i] < *agemin){
5253: *agemin=agev[m][i];
5254: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5255: }
5256: else if(agev[m][i] >*agemax){
5257: *agemax=agev[m][i];
1.156 brouard 5258: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5259: }
5260: /*agev[m][i]=anint[m][i]-annais[i];*/
5261: /* agev[m][i] = age[i]+2*m;*/
5262: }
5263: else { /* =9 */
5264: agev[m][i]=1;
5265: s[m][i]=-1;
5266: }
5267: }
5268: else /*= 0 Unknown */
5269: agev[m][i]=1;
5270: }
5271:
5272: }
5273: for (i=1; i<=imx; i++) {
5274: for(m=firstpass; (m<=lastpass); m++){
5275: if (s[m][i] > (nlstate+ndeath)) {
5276: *nberr++;
5277: 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);
5278: 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);
5279: return 1;
5280: }
5281: }
5282: }
5283:
5284: /*for (i=1; i<=imx; i++){
5285: for (m=firstpass; (m<lastpass); m++){
5286: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5287: }
5288:
5289: }*/
5290:
5291:
1.139 brouard 5292: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5293: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5294:
5295: return (0);
5296: endread:
5297: printf("Exiting calandcheckages: ");
5298: return (1);
5299: }
5300:
5301:
5302: /***********************************************/
5303: /**************** Main Program *****************/
5304: /***********************************************/
5305:
5306: int main(int argc, char *argv[])
5307: {
5308: #ifdef GSL
5309: const gsl_multimin_fminimizer_type *T;
5310: size_t iteri = 0, it;
5311: int rval = GSL_CONTINUE;
5312: int status = GSL_SUCCESS;
5313: double ssval;
5314: #endif
5315: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5316: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5317: int linei, month, year,iout;
5318: int jj, ll, li, lj, lk, imk;
5319: int numlinepar=0; /* Current linenumber of parameter file */
5320: int itimes;
5321: int NDIM=2;
5322: int vpopbased=0;
5323:
5324: char ca[32], cb[32], cc[32];
5325: /* FILE *fichtm; *//* Html File */
5326: /* FILE *ficgp;*/ /*Gnuplot File */
5327: struct stat info;
5328: double agedeb, agefin,hf;
5329: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5330:
5331: double fret;
5332: double **xi,tmp,delta;
5333:
5334: double dum; /* Dummy variable */
5335: double ***p3mat;
5336: double ***mobaverage;
5337: int *indx;
5338: char line[MAXLINE], linepar[MAXLINE];
5339: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5340: char pathr[MAXLINE], pathimach[MAXLINE];
5341: char **bp, *tok, *val; /* pathtot */
5342: int firstobs=1, lastobs=10;
5343: int sdeb, sfin; /* Status at beginning and end */
5344: int c, h , cpt,l;
5345: int ju,jl, mi;
5346: int i1,j1, jk,aa,bb, stepsize, ij;
5347: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5348: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5349: int mobilav=0,popforecast=0;
5350: int hstepm, nhstepm;
5351: int agemortsup;
5352: float sumlpop=0.;
5353: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5354: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5355:
5356: double bage, fage, age, agelim, agebase;
5357: double ftolpl=FTOL;
5358: double **prlim;
5359: double ***param; /* Matrix of parameters */
5360: double *p;
5361: double **matcov; /* Matrix of covariance */
5362: double ***delti3; /* Scale */
5363: double *delti; /* Scale */
5364: double ***eij, ***vareij;
5365: double **varpl; /* Variances of prevalence limits by age */
5366: double *epj, vepp;
5367: double kk1, kk2;
5368: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5369: double **ximort;
1.145 brouard 5370: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5371: int *dcwave;
5372:
5373: char z[1]="c", occ;
5374:
5375: /*char *strt;*/
5376: char strtend[80];
1.126 brouard 5377:
5378: long total_usecs;
5379:
5380: /* setlocale (LC_ALL, ""); */
5381: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5382: /* textdomain (PACKAGE); */
5383: /* setlocale (LC_CTYPE, ""); */
5384: /* setlocale (LC_MESSAGES, ""); */
5385:
5386: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5387: rstart_time = time(NULL);
5388: /* (void) gettimeofday(&start_time,&tzp);*/
5389: start_time = *localtime(&rstart_time);
1.126 brouard 5390: curr_time=start_time;
1.157 brouard 5391: /*tml = *localtime(&start_time.tm_sec);*/
5392: /* strcpy(strstart,asctime(&tml)); */
5393: strcpy(strstart,asctime(&start_time));
1.126 brouard 5394:
5395: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5396: /* tp.tm_sec = tp.tm_sec +86400; */
5397: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5398: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5399: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5400: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5401: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5402: /* strt=asctime(&tmg); */
5403: /* printf("Time(after) =%s",strstart); */
5404: /* (void) time (&time_value);
5405: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5406: * tm = *localtime(&time_value);
5407: * strstart=asctime(&tm);
5408: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5409: */
5410:
5411: nberr=0; /* Number of errors and warnings */
5412: nbwarn=0;
5413: getcwd(pathcd, size);
5414:
5415: printf("\n%s\n%s",version,fullversion);
5416: if(argc <=1){
5417: printf("\nEnter the parameter file name: ");
5418: fgets(pathr,FILENAMELENGTH,stdin);
5419: i=strlen(pathr);
5420: if(pathr[i-1]=='\n')
5421: pathr[i-1]='\0';
1.156 brouard 5422: i=strlen(pathr);
5423: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5424: pathr[i-1]='\0';
1.126 brouard 5425: for (tok = pathr; tok != NULL; ){
5426: printf("Pathr |%s|\n",pathr);
5427: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5428: printf("val= |%s| pathr=%s\n",val,pathr);
5429: strcpy (pathtot, val);
5430: if(pathr[0] == '\0') break; /* Dirty */
5431: }
5432: }
5433: else{
5434: strcpy(pathtot,argv[1]);
5435: }
5436: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5437: /*cygwin_split_path(pathtot,path,optionfile);
5438: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5439: /* cutv(path,optionfile,pathtot,'\\');*/
5440:
5441: /* Split argv[0], imach program to get pathimach */
5442: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5443: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5444: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5445: /* strcpy(pathimach,argv[0]); */
5446: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5447: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5448: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5449: chdir(path); /* Can be a relative path */
5450: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5451: printf("Current directory %s!\n",pathcd);
5452: strcpy(command,"mkdir ");
5453: strcat(command,optionfilefiname);
5454: if((outcmd=system(command)) != 0){
5455: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5456: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5457: /* fclose(ficlog); */
5458: /* exit(1); */
5459: }
5460: /* if((imk=mkdir(optionfilefiname))<0){ */
5461: /* perror("mkdir"); */
5462: /* } */
5463:
5464: /*-------- arguments in the command line --------*/
5465:
5466: /* Log file */
5467: strcat(filelog, optionfilefiname);
5468: strcat(filelog,".log"); /* */
5469: if((ficlog=fopen(filelog,"w"))==NULL) {
5470: printf("Problem with logfile %s\n",filelog);
5471: goto end;
5472: }
5473: fprintf(ficlog,"Log filename:%s\n",filelog);
5474: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5475: fprintf(ficlog,"\nEnter the parameter file name: \n");
5476: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5477: path=%s \n\
5478: optionfile=%s\n\
5479: optionfilext=%s\n\
1.156 brouard 5480: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5481:
5482: printf("Local time (at start):%s",strstart);
5483: fprintf(ficlog,"Local time (at start): %s",strstart);
5484: fflush(ficlog);
5485: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5486: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5487:
5488: /* */
5489: strcpy(fileres,"r");
5490: strcat(fileres, optionfilefiname);
5491: strcat(fileres,".txt"); /* Other files have txt extension */
5492:
5493: /*---------arguments file --------*/
5494:
5495: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5496: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5497: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5498: fflush(ficlog);
1.149 brouard 5499: /* goto end; */
5500: exit(70);
1.126 brouard 5501: }
5502:
5503:
5504:
5505: strcpy(filereso,"o");
5506: strcat(filereso,fileres);
5507: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5508: printf("Problem with Output resultfile: %s\n", filereso);
5509: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5510: fflush(ficlog);
5511: goto end;
5512: }
5513:
5514: /* Reads comments: lines beginning with '#' */
5515: numlinepar=0;
5516: while((c=getc(ficpar))=='#' && c!= EOF){
5517: ungetc(c,ficpar);
5518: fgets(line, MAXLINE, ficpar);
5519: numlinepar++;
1.141 brouard 5520: fputs(line,stdout);
1.126 brouard 5521: fputs(line,ficparo);
5522: fputs(line,ficlog);
5523: }
5524: ungetc(c,ficpar);
5525:
5526: 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);
5527: numlinepar++;
5528: 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);
5529: 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);
5530: 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);
5531: fflush(ficlog);
5532: while((c=getc(ficpar))=='#' && c!= EOF){
5533: ungetc(c,ficpar);
5534: fgets(line, MAXLINE, ficpar);
5535: numlinepar++;
1.141 brouard 5536: fputs(line, stdout);
5537: //puts(line);
1.126 brouard 5538: fputs(line,ficparo);
5539: fputs(line,ficlog);
5540: }
5541: ungetc(c,ficpar);
5542:
5543:
1.145 brouard 5544: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5545: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5546: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5547: v1+v2*age+v2*v3 makes cptcovn = 3
5548: */
5549: if (strlen(model)>1)
1.145 brouard 5550: 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*/
5551: else
5552: ncovmodel=2;
1.126 brouard 5553: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5554: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5555: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5556: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5557: 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);
5558: 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);
5559: fflush(stdout);
5560: fclose (ficlog);
5561: goto end;
5562: }
1.126 brouard 5563: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5564: delti=delti3[1][1];
5565: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5566: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5567: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5568: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5569: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5570: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5571: fclose (ficparo);
5572: fclose (ficlog);
5573: goto end;
5574: exit(0);
5575: }
5576: else if(mle==-3) {
5577: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5578: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5579: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5580: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5581: matcov=matrix(1,npar,1,npar);
5582: }
5583: else{
1.145 brouard 5584: /* Read guessed parameters */
1.126 brouard 5585: /* Reads comments: lines beginning with '#' */
5586: while((c=getc(ficpar))=='#' && c!= EOF){
5587: ungetc(c,ficpar);
5588: fgets(line, MAXLINE, ficpar);
5589: numlinepar++;
1.141 brouard 5590: fputs(line,stdout);
1.126 brouard 5591: fputs(line,ficparo);
5592: fputs(line,ficlog);
5593: }
5594: ungetc(c,ficpar);
5595:
5596: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5597: for(i=1; i <=nlstate; i++){
5598: j=0;
5599: for(jj=1; jj <=nlstate+ndeath; jj++){
5600: if(jj==i) continue;
5601: j++;
5602: fscanf(ficpar,"%1d%1d",&i1,&j1);
5603: if ((i1 != i) && (j1 != j)){
5604: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5605: It might be a problem of design; if ncovcol and the model are correct\n \
5606: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5607: exit(1);
5608: }
5609: fprintf(ficparo,"%1d%1d",i1,j1);
5610: if(mle==1)
5611: printf("%1d%1d",i,j);
5612: fprintf(ficlog,"%1d%1d",i,j);
5613: for(k=1; k<=ncovmodel;k++){
5614: fscanf(ficpar," %lf",¶m[i][j][k]);
5615: if(mle==1){
5616: printf(" %lf",param[i][j][k]);
5617: fprintf(ficlog," %lf",param[i][j][k]);
5618: }
5619: else
5620: fprintf(ficlog," %lf",param[i][j][k]);
5621: fprintf(ficparo," %lf",param[i][j][k]);
5622: }
5623: fscanf(ficpar,"\n");
5624: numlinepar++;
5625: if(mle==1)
5626: printf("\n");
5627: fprintf(ficlog,"\n");
5628: fprintf(ficparo,"\n");
5629: }
5630: }
5631: fflush(ficlog);
5632:
1.145 brouard 5633: /* Reads scales values */
1.126 brouard 5634: p=param[1][1];
5635:
5636: /* Reads comments: lines beginning with '#' */
5637: while((c=getc(ficpar))=='#' && c!= EOF){
5638: ungetc(c,ficpar);
5639: fgets(line, MAXLINE, ficpar);
5640: numlinepar++;
1.141 brouard 5641: fputs(line,stdout);
1.126 brouard 5642: fputs(line,ficparo);
5643: fputs(line,ficlog);
5644: }
5645: ungetc(c,ficpar);
5646:
5647: for(i=1; i <=nlstate; i++){
5648: for(j=1; j <=nlstate+ndeath-1; j++){
5649: fscanf(ficpar,"%1d%1d",&i1,&j1);
5650: if ((i1-i)*(j1-j)!=0){
5651: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5652: exit(1);
5653: }
5654: printf("%1d%1d",i,j);
5655: fprintf(ficparo,"%1d%1d",i1,j1);
5656: fprintf(ficlog,"%1d%1d",i1,j1);
5657: for(k=1; k<=ncovmodel;k++){
5658: fscanf(ficpar,"%le",&delti3[i][j][k]);
5659: printf(" %le",delti3[i][j][k]);
5660: fprintf(ficparo," %le",delti3[i][j][k]);
5661: fprintf(ficlog," %le",delti3[i][j][k]);
5662: }
5663: fscanf(ficpar,"\n");
5664: numlinepar++;
5665: printf("\n");
5666: fprintf(ficparo,"\n");
5667: fprintf(ficlog,"\n");
5668: }
5669: }
5670: fflush(ficlog);
5671:
1.145 brouard 5672: /* Reads covariance matrix */
1.126 brouard 5673: delti=delti3[1][1];
5674:
5675:
5676: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5677:
5678: /* Reads comments: lines beginning with '#' */
5679: while((c=getc(ficpar))=='#' && c!= EOF){
5680: ungetc(c,ficpar);
5681: fgets(line, MAXLINE, ficpar);
5682: numlinepar++;
1.141 brouard 5683: fputs(line,stdout);
1.126 brouard 5684: fputs(line,ficparo);
5685: fputs(line,ficlog);
5686: }
5687: ungetc(c,ficpar);
5688:
5689: matcov=matrix(1,npar,1,npar);
1.131 brouard 5690: for(i=1; i <=npar; i++)
5691: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5692:
1.126 brouard 5693: for(i=1; i <=npar; i++){
1.145 brouard 5694: fscanf(ficpar,"%s",str);
1.126 brouard 5695: if(mle==1)
5696: printf("%s",str);
5697: fprintf(ficlog,"%s",str);
5698: fprintf(ficparo,"%s",str);
5699: for(j=1; j <=i; j++){
5700: fscanf(ficpar," %le",&matcov[i][j]);
5701: if(mle==1){
5702: printf(" %.5le",matcov[i][j]);
5703: }
5704: fprintf(ficlog," %.5le",matcov[i][j]);
5705: fprintf(ficparo," %.5le",matcov[i][j]);
5706: }
5707: fscanf(ficpar,"\n");
5708: numlinepar++;
5709: if(mle==1)
5710: printf("\n");
5711: fprintf(ficlog,"\n");
5712: fprintf(ficparo,"\n");
5713: }
5714: for(i=1; i <=npar; i++)
5715: for(j=i+1;j<=npar;j++)
5716: matcov[i][j]=matcov[j][i];
5717:
5718: if(mle==1)
5719: printf("\n");
5720: fprintf(ficlog,"\n");
5721:
5722: fflush(ficlog);
5723:
5724: /*-------- Rewriting parameter file ----------*/
5725: strcpy(rfileres,"r"); /* "Rparameterfile */
5726: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5727: strcat(rfileres,"."); /* */
5728: strcat(rfileres,optionfilext); /* Other files have txt extension */
5729: if((ficres =fopen(rfileres,"w"))==NULL) {
5730: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5731: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5732: }
5733: fprintf(ficres,"#%s\n",version);
5734: } /* End of mle != -3 */
5735:
5736:
5737: n= lastobs;
5738: num=lvector(1,n);
5739: moisnais=vector(1,n);
5740: annais=vector(1,n);
5741: moisdc=vector(1,n);
5742: andc=vector(1,n);
5743: agedc=vector(1,n);
5744: cod=ivector(1,n);
5745: weight=vector(1,n);
5746: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5747: mint=matrix(1,maxwav,1,n);
5748: anint=matrix(1,maxwav,1,n);
1.131 brouard 5749: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5750: tab=ivector(1,NCOVMAX);
1.144 brouard 5751: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5752:
1.136 brouard 5753: /* Reads data from file datafile */
5754: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5755: goto end;
5756:
5757: /* Calculation of the number of parameters from char model */
1.137 brouard 5758: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5759: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5760: k=3 V4 Tvar[k=3]= 4 (from V4)
5761: k=2 V1 Tvar[k=2]= 1 (from V1)
5762: k=1 Tvar[1]=2 (from V2)
5763: */
5764: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5765: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5766: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5767: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5768: */
5769: /* For model-covariate k tells which data-covariate to use but
5770: because this model-covariate is a construction we invent a new column
5771: ncovcol + k1
5772: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5773: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5774: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5775: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5776: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5777: */
1.145 brouard 5778: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5779: 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 5780: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5781: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5782: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5783: 4 covariates (3 plus signs)
5784: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5785: */
1.136 brouard 5786:
5787: if(decodemodel(model, lastobs) == 1)
5788: goto end;
5789:
1.137 brouard 5790: if((double)(lastobs-imx)/(double)imx > 1.10){
5791: nbwarn++;
5792: 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);
5793: 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);
5794: }
1.136 brouard 5795: /* if(mle==1){*/
1.137 brouard 5796: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5797: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5798: }
5799:
5800: /*-calculation of age at interview from date of interview and age at death -*/
5801: agev=matrix(1,maxwav,1,imx);
5802:
5803: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5804: goto end;
5805:
1.126 brouard 5806:
1.136 brouard 5807: agegomp=(int)agemin;
5808: free_vector(moisnais,1,n);
5809: free_vector(annais,1,n);
1.126 brouard 5810: /* free_matrix(mint,1,maxwav,1,n);
5811: free_matrix(anint,1,maxwav,1,n);*/
5812: free_vector(moisdc,1,n);
5813: free_vector(andc,1,n);
1.145 brouard 5814: /* */
5815:
1.126 brouard 5816: wav=ivector(1,imx);
5817: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5818: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5819: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5820:
5821: /* Concatenates waves */
5822: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5823: /* */
5824:
1.126 brouard 5825: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5826:
5827: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5828: ncodemax[1]=1;
1.145 brouard 5829: Ndum =ivector(-1,NCOVMAX);
5830: if (ncovmodel > 2)
5831: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5832:
5833: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5834: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5835: h=0;
5836:
5837:
5838: /*if (cptcovn > 0) */
1.126 brouard 5839:
1.145 brouard 5840:
1.126 brouard 5841: m=pow(2,cptcoveff);
5842:
1.131 brouard 5843: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5844: 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 */
5845: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5846: 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 5847: h++;
1.141 brouard 5848: if (h>m)
1.136 brouard 5849: h=1;
1.144 brouard 5850: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5851: * h 1 2 3 4
5852: *______________________________
5853: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5854: * 2 2 1 1 1
5855: * 3 i=2 1 2 1 1
5856: * 4 2 2 1 1
5857: * 5 i=3 1 i=2 1 2 1
5858: * 6 2 1 2 1
5859: * 7 i=4 1 2 2 1
5860: * 8 2 2 2 1
5861: * 9 i=5 1 i=3 1 i=2 1 1
5862: * 10 2 1 1 1
5863: * 11 i=6 1 2 1 1
5864: * 12 2 2 1 1
5865: * 13 i=7 1 i=4 1 2 1
5866: * 14 2 1 2 1
5867: * 15 i=8 1 2 2 1
5868: * 16 2 2 2 1
5869: */
1.141 brouard 5870: codtab[h][k]=j;
1.145 brouard 5871: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5872: 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 5873: }
5874: }
5875: }
5876: }
5877: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5878: codtab[1][2]=1;codtab[2][2]=2; */
5879: /* for(i=1; i <=m ;i++){
5880: for(k=1; k <=cptcovn; k++){
1.131 brouard 5881: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5882: }
5883: printf("\n");
5884: }
5885: scanf("%d",i);*/
1.145 brouard 5886:
5887: free_ivector(Ndum,-1,NCOVMAX);
5888:
5889:
1.126 brouard 5890:
5891: /*------------ gnuplot -------------*/
5892: strcpy(optionfilegnuplot,optionfilefiname);
5893: if(mle==-3)
5894: strcat(optionfilegnuplot,"-mort");
5895: strcat(optionfilegnuplot,".gp");
5896:
5897: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5898: printf("Problem with file %s",optionfilegnuplot);
5899: }
5900: else{
5901: fprintf(ficgp,"\n# %s\n", version);
5902: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 5903: //fprintf(ficgp,"set missing 'NaNq'\n");
5904: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 5905: }
5906: /* fclose(ficgp);*/
5907: /*--------- index.htm --------*/
5908:
5909: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5910: if(mle==-3)
5911: strcat(optionfilehtm,"-mort");
5912: strcat(optionfilehtm,".htm");
5913: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 5914: printf("Problem with %s \n",optionfilehtm);
5915: exit(0);
1.126 brouard 5916: }
5917:
5918: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5919: strcat(optionfilehtmcov,"-cov.htm");
5920: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5921: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5922: }
5923: else{
5924: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5925: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5926: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5927: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5928: }
5929:
5930: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5931: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5932: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5933: \n\
5934: <hr size=\"2\" color=\"#EC5E5E\">\
5935: <ul><li><h4>Parameter files</h4>\n\
5936: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5937: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5938: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5939: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5940: - Date and time at start: %s</ul>\n",\
5941: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5942: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5943: fileres,fileres,\
5944: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5945: fflush(fichtm);
5946:
5947: strcpy(pathr,path);
5948: strcat(pathr,optionfilefiname);
5949: chdir(optionfilefiname); /* Move to directory named optionfile */
5950:
5951: /* Calculates basic frequencies. Computes observed prevalence at single age
5952: and prints on file fileres'p'. */
5953: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5954:
5955: fprintf(fichtm,"\n");
5956: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5957: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5958: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5959: imx,agemin,agemax,jmin,jmax,jmean);
5960: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5961: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5962: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5963: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5964: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5965:
5966:
5967: /* For Powell, parameters are in a vector p[] starting at p[1]
5968: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5969: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5970:
5971: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5972:
5973: if (mle==-3){
1.136 brouard 5974: ximort=matrix(1,NDIM,1,NDIM);
5975: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 5976: cens=ivector(1,n);
5977: ageexmed=vector(1,n);
5978: agecens=vector(1,n);
5979: dcwave=ivector(1,n);
5980:
5981: for (i=1; i<=imx; i++){
5982: dcwave[i]=-1;
5983: for (m=firstpass; m<=lastpass; m++)
5984: if (s[m][i]>nlstate) {
5985: dcwave[i]=m;
5986: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5987: break;
5988: }
5989: }
5990:
5991: for (i=1; i<=imx; i++) {
5992: if (wav[i]>0){
5993: ageexmed[i]=agev[mw[1][i]][i];
5994: j=wav[i];
5995: agecens[i]=1.;
5996:
5997: if (ageexmed[i]> 1 && wav[i] > 0){
5998: agecens[i]=agev[mw[j][i]][i];
5999: cens[i]= 1;
6000: }else if (ageexmed[i]< 1)
6001: cens[i]= -1;
6002: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6003: cens[i]=0 ;
6004: }
6005: else cens[i]=-1;
6006: }
6007:
6008: for (i=1;i<=NDIM;i++) {
6009: for (j=1;j<=NDIM;j++)
6010: ximort[i][j]=(i == j ? 1.0 : 0.0);
6011: }
6012:
1.145 brouard 6013: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6014: /*printf("%lf %lf", p[1], p[2]);*/
6015:
6016:
1.136 brouard 6017: #ifdef GSL
6018: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6019: #elsedef
1.126 brouard 6020: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6021: #endif
1.126 brouard 6022: strcpy(filerespow,"pow-mort");
6023: strcat(filerespow,fileres);
6024: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6025: printf("Problem with resultfile: %s\n", filerespow);
6026: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6027: }
1.136 brouard 6028: #ifdef GSL
6029: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6030: #elsedef
1.126 brouard 6031: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6032: #endif
1.126 brouard 6033: /* for (i=1;i<=nlstate;i++)
6034: for(j=1;j<=nlstate+ndeath;j++)
6035: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6036: */
6037: fprintf(ficrespow,"\n");
1.136 brouard 6038: #ifdef GSL
6039: /* gsl starts here */
6040: T = gsl_multimin_fminimizer_nmsimplex;
6041: gsl_multimin_fminimizer *sfm = NULL;
6042: gsl_vector *ss, *x;
6043: gsl_multimin_function minex_func;
6044:
6045: /* Initial vertex size vector */
6046: ss = gsl_vector_alloc (NDIM);
6047:
6048: if (ss == NULL){
6049: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6050: }
6051: /* Set all step sizes to 1 */
6052: gsl_vector_set_all (ss, 0.001);
6053:
6054: /* Starting point */
1.126 brouard 6055:
1.136 brouard 6056: x = gsl_vector_alloc (NDIM);
6057:
6058: if (x == NULL){
6059: gsl_vector_free(ss);
6060: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6061: }
6062:
6063: /* Initialize method and iterate */
6064: /* p[1]=0.0268; p[NDIM]=0.083; */
6065: /* gsl_vector_set(x, 0, 0.0268); */
6066: /* gsl_vector_set(x, 1, 0.083); */
6067: gsl_vector_set(x, 0, p[1]);
6068: gsl_vector_set(x, 1, p[2]);
6069:
6070: minex_func.f = &gompertz_f;
6071: minex_func.n = NDIM;
6072: minex_func.params = (void *)&p; /* ??? */
6073:
6074: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6075: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6076:
6077: printf("Iterations beginning .....\n\n");
6078: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6079:
6080: iteri=0;
6081: while (rval == GSL_CONTINUE){
6082: iteri++;
6083: status = gsl_multimin_fminimizer_iterate(sfm);
6084:
6085: if (status) printf("error: %s\n", gsl_strerror (status));
6086: fflush(0);
6087:
6088: if (status)
6089: break;
6090:
6091: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6092: ssval = gsl_multimin_fminimizer_size (sfm);
6093:
6094: if (rval == GSL_SUCCESS)
6095: printf ("converged to a local maximum at\n");
6096:
6097: printf("%5d ", iteri);
6098: for (it = 0; it < NDIM; it++){
6099: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6100: }
6101: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6102: }
6103:
6104: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6105:
6106: gsl_vector_free(x); /* initial values */
6107: gsl_vector_free(ss); /* inital step size */
6108: for (it=0; it<NDIM; it++){
6109: p[it+1]=gsl_vector_get(sfm->x,it);
6110: fprintf(ficrespow," %.12lf", p[it]);
6111: }
6112: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6113: #endif
6114: #ifdef POWELL
6115: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6116: #endif
1.126 brouard 6117: fclose(ficrespow);
6118:
6119: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6120:
6121: for(i=1; i <=NDIM; i++)
6122: for(j=i+1;j<=NDIM;j++)
6123: matcov[i][j]=matcov[j][i];
6124:
6125: printf("\nCovariance matrix\n ");
6126: for(i=1; i <=NDIM; i++) {
6127: for(j=1;j<=NDIM;j++){
6128: printf("%f ",matcov[i][j]);
6129: }
6130: printf("\n ");
6131: }
6132:
6133: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6134: for (i=1;i<=NDIM;i++)
6135: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6136:
6137: lsurv=vector(1,AGESUP);
6138: lpop=vector(1,AGESUP);
6139: tpop=vector(1,AGESUP);
6140: lsurv[agegomp]=100000;
6141:
6142: for (k=agegomp;k<=AGESUP;k++) {
6143: agemortsup=k;
6144: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6145: }
6146:
6147: for (k=agegomp;k<agemortsup;k++)
6148: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6149:
6150: for (k=agegomp;k<agemortsup;k++){
6151: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6152: sumlpop=sumlpop+lpop[k];
6153: }
6154:
6155: tpop[agegomp]=sumlpop;
6156: for (k=agegomp;k<(agemortsup-3);k++){
6157: /* tpop[k+1]=2;*/
6158: tpop[k+1]=tpop[k]-lpop[k];
6159: }
6160:
6161:
6162: printf("\nAge lx qx dx Lx Tx e(x)\n");
6163: for (k=agegomp;k<(agemortsup-2);k++)
6164: 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]);
6165:
6166:
6167: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6168: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6169:
6170: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6171: stepm, weightopt,\
6172: model,imx,p,matcov,agemortsup);
6173:
6174: free_vector(lsurv,1,AGESUP);
6175: free_vector(lpop,1,AGESUP);
6176: free_vector(tpop,1,AGESUP);
1.136 brouard 6177: #ifdef GSL
6178: free_ivector(cens,1,n);
6179: free_vector(agecens,1,n);
6180: free_ivector(dcwave,1,n);
6181: free_matrix(ximort,1,NDIM,1,NDIM);
6182: #endif
1.126 brouard 6183: } /* Endof if mle==-3 */
6184:
6185: else{ /* For mle >=1 */
1.132 brouard 6186: globpr=0;/* debug */
6187: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6188: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6189: for (k=1; k<=npar;k++)
6190: printf(" %d %8.5f",k,p[k]);
6191: printf("\n");
6192: globpr=1; /* to print the contributions */
6193: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6194: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6195: for (k=1; k<=npar;k++)
6196: printf(" %d %8.5f",k,p[k]);
6197: printf("\n");
6198: if(mle>=1){ /* Could be 1 or 2 */
6199: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6200: }
6201:
6202: /*--------- results files --------------*/
6203: 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);
6204:
6205:
6206: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6207: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6208: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6209: for(i=1,jk=1; i <=nlstate; i++){
6210: for(k=1; k <=(nlstate+ndeath); k++){
6211: if (k != i) {
6212: printf("%d%d ",i,k);
6213: fprintf(ficlog,"%d%d ",i,k);
6214: fprintf(ficres,"%1d%1d ",i,k);
6215: for(j=1; j <=ncovmodel; j++){
6216: printf("%lf ",p[jk]);
6217: fprintf(ficlog,"%lf ",p[jk]);
6218: fprintf(ficres,"%lf ",p[jk]);
6219: jk++;
6220: }
6221: printf("\n");
6222: fprintf(ficlog,"\n");
6223: fprintf(ficres,"\n");
6224: }
6225: }
6226: }
6227: if(mle!=0){
6228: /* Computing hessian and covariance matrix */
6229: ftolhess=ftol; /* Usually correct */
6230: hesscov(matcov, p, npar, delti, ftolhess, func);
6231: }
6232: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6233: printf("# Scales (for hessian or gradient estimation)\n");
6234: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6235: for(i=1,jk=1; i <=nlstate; i++){
6236: for(j=1; j <=nlstate+ndeath; j++){
6237: if (j!=i) {
6238: fprintf(ficres,"%1d%1d",i,j);
6239: printf("%1d%1d",i,j);
6240: fprintf(ficlog,"%1d%1d",i,j);
6241: for(k=1; k<=ncovmodel;k++){
6242: printf(" %.5e",delti[jk]);
6243: fprintf(ficlog," %.5e",delti[jk]);
6244: fprintf(ficres," %.5e",delti[jk]);
6245: jk++;
6246: }
6247: printf("\n");
6248: fprintf(ficlog,"\n");
6249: fprintf(ficres,"\n");
6250: }
6251: }
6252: }
6253:
6254: 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");
6255: if(mle>=1)
6256: 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");
6257: 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");
6258: /* # 121 Var(a12)\n\ */
6259: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6260: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6261: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6262: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6263: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6264: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6265: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6266:
6267:
6268: /* Just to have a covariance matrix which will be more understandable
6269: even is we still don't want to manage dictionary of variables
6270: */
6271: for(itimes=1;itimes<=2;itimes++){
6272: jj=0;
6273: for(i=1; i <=nlstate; i++){
6274: for(j=1; j <=nlstate+ndeath; j++){
6275: if(j==i) continue;
6276: for(k=1; k<=ncovmodel;k++){
6277: jj++;
6278: ca[0]= k+'a'-1;ca[1]='\0';
6279: if(itimes==1){
6280: if(mle>=1)
6281: printf("#%1d%1d%d",i,j,k);
6282: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6283: fprintf(ficres,"#%1d%1d%d",i,j,k);
6284: }else{
6285: if(mle>=1)
6286: printf("%1d%1d%d",i,j,k);
6287: fprintf(ficlog,"%1d%1d%d",i,j,k);
6288: fprintf(ficres,"%1d%1d%d",i,j,k);
6289: }
6290: ll=0;
6291: for(li=1;li <=nlstate; li++){
6292: for(lj=1;lj <=nlstate+ndeath; lj++){
6293: if(lj==li) continue;
6294: for(lk=1;lk<=ncovmodel;lk++){
6295: ll++;
6296: if(ll<=jj){
6297: cb[0]= lk +'a'-1;cb[1]='\0';
6298: if(ll<jj){
6299: if(itimes==1){
6300: if(mle>=1)
6301: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6302: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6303: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6304: }else{
6305: if(mle>=1)
6306: printf(" %.5e",matcov[jj][ll]);
6307: fprintf(ficlog," %.5e",matcov[jj][ll]);
6308: fprintf(ficres," %.5e",matcov[jj][ll]);
6309: }
6310: }else{
6311: if(itimes==1){
6312: if(mle>=1)
6313: printf(" Var(%s%1d%1d)",ca,i,j);
6314: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6315: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6316: }else{
6317: if(mle>=1)
6318: printf(" %.5e",matcov[jj][ll]);
6319: fprintf(ficlog," %.5e",matcov[jj][ll]);
6320: fprintf(ficres," %.5e",matcov[jj][ll]);
6321: }
6322: }
6323: }
6324: } /* end lk */
6325: } /* end lj */
6326: } /* end li */
6327: if(mle>=1)
6328: printf("\n");
6329: fprintf(ficlog,"\n");
6330: fprintf(ficres,"\n");
6331: numlinepar++;
6332: } /* end k*/
6333: } /*end j */
6334: } /* end i */
6335: } /* end itimes */
6336:
6337: fflush(ficlog);
6338: fflush(ficres);
6339:
6340: while((c=getc(ficpar))=='#' && c!= EOF){
6341: ungetc(c,ficpar);
6342: fgets(line, MAXLINE, ficpar);
1.141 brouard 6343: fputs(line,stdout);
1.126 brouard 6344: fputs(line,ficparo);
6345: }
6346: ungetc(c,ficpar);
6347:
6348: estepm=0;
6349: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6350: if (estepm==0 || estepm < stepm) estepm=stepm;
6351: if (fage <= 2) {
6352: bage = ageminpar;
6353: fage = agemaxpar;
6354: }
6355:
6356: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6357: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6358: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6359:
6360: while((c=getc(ficpar))=='#' && c!= EOF){
6361: ungetc(c,ficpar);
6362: fgets(line, MAXLINE, ficpar);
1.141 brouard 6363: fputs(line,stdout);
1.126 brouard 6364: fputs(line,ficparo);
6365: }
6366: ungetc(c,ficpar);
6367:
6368: 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);
6369: 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);
6370: 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);
6371: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6372: 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);
6373:
6374: while((c=getc(ficpar))=='#' && c!= EOF){
6375: ungetc(c,ficpar);
6376: fgets(line, MAXLINE, ficpar);
1.141 brouard 6377: fputs(line,stdout);
1.126 brouard 6378: fputs(line,ficparo);
6379: }
6380: ungetc(c,ficpar);
6381:
6382:
6383: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6384: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6385:
6386: fscanf(ficpar,"pop_based=%d\n",&popbased);
6387: fprintf(ficparo,"pop_based=%d\n",popbased);
6388: fprintf(ficres,"pop_based=%d\n",popbased);
6389:
6390: while((c=getc(ficpar))=='#' && c!= EOF){
6391: ungetc(c,ficpar);
6392: fgets(line, MAXLINE, ficpar);
1.141 brouard 6393: fputs(line,stdout);
1.126 brouard 6394: fputs(line,ficparo);
6395: }
6396: ungetc(c,ficpar);
6397:
6398: 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);
6399: 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);
6400: 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);
6401: 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);
6402: 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);
6403: /* day and month of proj2 are not used but only year anproj2.*/
6404:
6405:
6406:
1.145 brouard 6407: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6408: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6409:
6410: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6411: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6412:
6413: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6414: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6415: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6416:
6417: /*------------ free_vector -------------*/
6418: /* chdir(path); */
6419:
6420: free_ivector(wav,1,imx);
6421: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6422: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6423: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6424: free_lvector(num,1,n);
6425: free_vector(agedc,1,n);
6426: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6427: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6428: fclose(ficparo);
6429: fclose(ficres);
6430:
6431:
6432: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6433: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6434: fclose(ficrespl);
6435:
1.145 brouard 6436: #ifdef FREEEXIT2
6437: #include "freeexit2.h"
6438: #endif
6439:
1.126 brouard 6440: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6441: #include "hpijx.h"
6442: fclose(ficrespij);
1.126 brouard 6443:
1.145 brouard 6444: /*-------------- Variance of one-step probabilities---*/
6445: k=1;
1.126 brouard 6446: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6447:
6448:
6449: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6450: for(i=1;i<=AGESUP;i++)
6451: for(j=1;j<=NCOVMAX;j++)
6452: for(k=1;k<=NCOVMAX;k++)
6453: probs[i][j][k]=0.;
6454:
6455: /*---------- Forecasting ------------------*/
6456: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6457: if(prevfcast==1){
6458: /* if(stepm ==1){*/
6459: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6460: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6461: /* } */
6462: /* else{ */
6463: /* erreur=108; */
6464: /* 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); */
6465: /* 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); */
6466: /* } */
6467: }
6468:
6469:
1.127 brouard 6470: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6471:
6472: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6473: /* 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",\
6474: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6475: */
1.126 brouard 6476:
1.127 brouard 6477: if (mobilav!=0) {
6478: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6479: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6480: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6481: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6482: }
1.126 brouard 6483: }
6484:
6485:
1.127 brouard 6486: /*---------- Health expectancies, no variances ------------*/
6487:
1.126 brouard 6488: strcpy(filerese,"e");
6489: strcat(filerese,fileres);
6490: if((ficreseij=fopen(filerese,"w"))==NULL) {
6491: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6492: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6493: }
6494: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6495: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6496: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6497: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6498:
6499: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6500: fprintf(ficreseij,"\n#****** ");
6501: for(j=1;j<=cptcoveff;j++) {
6502: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6503: }
6504: fprintf(ficreseij,"******\n");
6505:
6506: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6507: oldm=oldms;savm=savms;
6508: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6509:
6510: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6511: /*}*/
1.127 brouard 6512: }
6513: fclose(ficreseij);
6514:
6515:
6516: /*---------- Health expectancies and variances ------------*/
6517:
6518:
6519: strcpy(filerest,"t");
6520: strcat(filerest,fileres);
6521: if((ficrest=fopen(filerest,"w"))==NULL) {
6522: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6523: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6524: }
6525: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6526: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6527:
1.126 brouard 6528:
6529: strcpy(fileresstde,"stde");
6530: strcat(fileresstde,fileres);
6531: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6532: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6533: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6534: }
6535: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6536: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6537:
6538: strcpy(filerescve,"cve");
6539: strcat(filerescve,fileres);
6540: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6541: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6542: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6543: }
6544: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6545: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6546:
6547: strcpy(fileresv,"v");
6548: strcat(fileresv,fileres);
6549: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6550: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6551: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6552: }
6553: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6554: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6555:
1.145 brouard 6556: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6557: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6558:
6559: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6560: fprintf(ficrest,"\n#****** ");
1.126 brouard 6561: for(j=1;j<=cptcoveff;j++)
6562: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6563: fprintf(ficrest,"******\n");
6564:
6565: fprintf(ficresstdeij,"\n#****** ");
6566: fprintf(ficrescveij,"\n#****** ");
6567: for(j=1;j<=cptcoveff;j++) {
6568: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6569: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6570: }
6571: fprintf(ficresstdeij,"******\n");
6572: fprintf(ficrescveij,"******\n");
6573:
6574: fprintf(ficresvij,"\n#****** ");
6575: for(j=1;j<=cptcoveff;j++)
6576: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6577: fprintf(ficresvij,"******\n");
6578:
6579: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6580: oldm=oldms;savm=savms;
1.127 brouard 6581: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6582: /*
6583: */
6584: /* goto endfree; */
1.126 brouard 6585:
6586: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6587: pstamp(ficrest);
1.145 brouard 6588:
6589:
1.128 brouard 6590: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6591: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 ! brouard 6592: cptcod= 0; /* To be deleted */
! 6593: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145 brouard 6594: 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 6595: if(vpopbased==1)
6596: 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);
6597: else
6598: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6599: fprintf(ficrest,"# Age e.. (std) ");
6600: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6601: fprintf(ficrest,"\n");
1.126 brouard 6602:
1.128 brouard 6603: epj=vector(1,nlstate+1);
6604: for(age=bage; age <=fage ;age++){
6605: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6606: if (vpopbased==1) {
6607: if(mobilav ==0){
6608: for(i=1; i<=nlstate;i++)
6609: prlim[i][i]=probs[(int)age][i][k];
6610: }else{ /* mobilav */
6611: for(i=1; i<=nlstate;i++)
6612: prlim[i][i]=mobaverage[(int)age][i][k];
6613: }
1.126 brouard 6614: }
6615:
1.128 brouard 6616: fprintf(ficrest," %4.0f",age);
6617: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6618: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6619: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6620: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6621: }
6622: epj[nlstate+1] +=epj[j];
1.126 brouard 6623: }
6624:
1.128 brouard 6625: for(i=1, vepp=0.;i <=nlstate;i++)
6626: for(j=1;j <=nlstate;j++)
6627: vepp += vareij[i][j][(int)age];
6628: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6629: for(j=1;j <=nlstate;j++){
6630: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6631: }
6632: fprintf(ficrest,"\n");
1.126 brouard 6633: }
6634: }
6635: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6636: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6637: free_vector(epj,1,nlstate+1);
1.145 brouard 6638: /*}*/
1.126 brouard 6639: }
6640: free_vector(weight,1,n);
1.145 brouard 6641: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6642: free_imatrix(s,1,maxwav+1,1,n);
6643: free_matrix(anint,1,maxwav,1,n);
6644: free_matrix(mint,1,maxwav,1,n);
6645: free_ivector(cod,1,n);
6646: free_ivector(tab,1,NCOVMAX);
6647: fclose(ficresstdeij);
6648: fclose(ficrescveij);
6649: fclose(ficresvij);
6650: fclose(ficrest);
6651: fclose(ficpar);
6652:
6653: /*------- Variance of period (stable) prevalence------*/
6654:
6655: strcpy(fileresvpl,"vpl");
6656: strcat(fileresvpl,fileres);
6657: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6658: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6659: exit(0);
6660: }
6661: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6662:
1.145 brouard 6663: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6664: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6665:
6666: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6667: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6668: for(j=1;j<=cptcoveff;j++)
6669: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6670: fprintf(ficresvpl,"******\n");
6671:
6672: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6673: oldm=oldms;savm=savms;
6674: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6675: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6676: /*}*/
1.126 brouard 6677: }
6678:
6679: fclose(ficresvpl);
6680:
6681: /*---------- End : free ----------------*/
6682: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6683: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6684: } /* mle==-3 arrives here for freeing */
1.131 brouard 6685: endfree:
1.141 brouard 6686: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6687: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6688: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6689: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6690: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6691: free_matrix(covar,0,NCOVMAX,1,n);
6692: free_matrix(matcov,1,npar,1,npar);
6693: /*free_vector(delti,1,npar);*/
6694: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6695: free_matrix(agev,1,maxwav,1,imx);
6696: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6697:
1.145 brouard 6698: free_ivector(ncodemax,1,NCOVMAX);
6699: free_ivector(Tvar,1,NCOVMAX);
6700: free_ivector(Tprod,1,NCOVMAX);
6701: free_ivector(Tvaraff,1,NCOVMAX);
6702: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6703:
6704: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6705: free_imatrix(codtab,1,100,1,10);
6706: fflush(fichtm);
6707: fflush(ficgp);
6708:
6709:
6710: if((nberr >0) || (nbwarn>0)){
6711: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6712: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6713: }else{
6714: printf("End of Imach\n");
6715: fprintf(ficlog,"End of Imach\n");
6716: }
6717: printf("See log file on %s\n",filelog);
6718: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6719: /*(void) gettimeofday(&end_time,&tzp);*/
6720: rend_time = time(NULL);
6721: end_time = *localtime(&rend_time);
6722: /* tml = *localtime(&end_time.tm_sec); */
6723: strcpy(strtend,asctime(&end_time));
1.126 brouard 6724: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6725: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6726: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6727:
1.157 brouard 6728: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6729: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6730: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6731: /* printf("Total time was %d uSec.\n", total_usecs);*/
6732: /* if(fileappend(fichtm,optionfilehtm)){ */
6733: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6734: fclose(fichtm);
6735: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6736: fclose(fichtmcov);
6737: fclose(ficgp);
6738: fclose(ficlog);
6739: /*------ End -----------*/
6740:
6741:
6742: printf("Before Current directory %s!\n",pathcd);
6743: if(chdir(pathcd) != 0)
6744: printf("Can't move to directory %s!\n",path);
6745: if(getcwd(pathcd,MAXLINE) > 0)
6746: printf("Current directory %s!\n",pathcd);
6747: /*strcat(plotcmd,CHARSEPARATOR);*/
6748: sprintf(plotcmd,"gnuplot");
1.157 brouard 6749: #ifdef _WIN32
1.126 brouard 6750: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6751: #endif
6752: if(!stat(plotcmd,&info)){
1.158 brouard 6753: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6754: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6755: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6756: }else
6757: strcpy(pplotcmd,plotcmd);
1.157 brouard 6758: #ifdef __unix
1.126 brouard 6759: strcpy(plotcmd,GNUPLOTPROGRAM);
6760: if(!stat(plotcmd,&info)){
1.158 brouard 6761: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6762: }else
6763: strcpy(pplotcmd,plotcmd);
6764: #endif
6765: }else
6766: strcpy(pplotcmd,plotcmd);
6767:
6768: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6769: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6770:
6771: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6772: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6773: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6774: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6775: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6776: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6777: }
1.158 brouard 6778: printf(" Successful, please wait...");
1.126 brouard 6779: while (z[0] != 'q') {
6780: /* chdir(path); */
1.154 brouard 6781: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6782: scanf("%s",z);
6783: /* if (z[0] == 'c') system("./imach"); */
6784: if (z[0] == 'e') {
1.158 brouard 6785: #ifdef __APPLE__
1.152 brouard 6786: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6787: #elif __linux
6788: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6789: #else
1.152 brouard 6790: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6791: #endif
6792: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6793: system(pplotcmd);
1.126 brouard 6794: }
6795: else if (z[0] == 'g') system(plotcmd);
6796: else if (z[0] == 'q') exit(0);
6797: }
6798: end:
6799: while (z[0] != 'q') {
6800: printf("\nType q for exiting: ");
6801: scanf("%s",z);
6802: }
6803: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>