Annotation of imach/src/imach.c, revision 1.160
1.160 ! brouard 1: /* $Id: imach.c,v 1.159 2014/09/01 10:34:10 brouard Exp $
1.126 brouard 2: $State: Exp $
3: $Log: imach.c,v $
1.160 ! brouard 4: Revision 1.159 2014/09/01 10:34:10 brouard
! 5: Summary: WIN32
! 6: Author: Brouard
! 7:
1.159 brouard 8: Revision 1.158 2014/08/27 17:11:51 brouard
9: *** empty log message ***
10:
1.158 brouard 11: Revision 1.157 2014/08/27 16:26:55 brouard
12: Summary: Preparing windows Visual studio version
13: Author: Brouard
14:
15: In order to compile on Visual studio, time.h is now correct and time_t
16: and tm struct should be used. difftime should be used but sometimes I
17: just make the differences in raw time format (time(&now).
18: Trying to suppress #ifdef LINUX
19: Add xdg-open for __linux in order to open default browser.
20:
1.157 brouard 21: Revision 1.156 2014/08/25 20:10:10 brouard
22: *** empty log message ***
23:
1.156 brouard 24: Revision 1.155 2014/08/25 18:32:34 brouard
25: Summary: New compile, minor changes
26: Author: Brouard
27:
1.155 brouard 28: Revision 1.154 2014/06/20 17:32:08 brouard
29: Summary: Outputs now all graphs of convergence to period prevalence
30:
1.154 brouard 31: Revision 1.153 2014/06/20 16:45:46 brouard
32: Summary: If 3 live state, convergence to period prevalence on same graph
33: Author: Brouard
34:
1.153 brouard 35: Revision 1.152 2014/06/18 17:54:09 brouard
36: Summary: open browser, use gnuplot on same dir than imach if not found in the path
37:
1.152 brouard 38: Revision 1.151 2014/06/18 16:43:30 brouard
39: *** empty log message ***
40:
1.151 brouard 41: Revision 1.150 2014/06/18 16:42:35 brouard
42: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
43: Author: brouard
44:
1.150 brouard 45: Revision 1.149 2014/06/18 15:51:14 brouard
46: Summary: Some fixes in parameter files errors
47: Author: Nicolas Brouard
48:
1.149 brouard 49: Revision 1.148 2014/06/17 17:38:48 brouard
50: Summary: Nothing new
51: Author: Brouard
52:
53: Just a new packaging for OS/X version 0.98nS
54:
1.148 brouard 55: Revision 1.147 2014/06/16 10:33:11 brouard
56: *** empty log message ***
57:
1.147 brouard 58: Revision 1.146 2014/06/16 10:20:28 brouard
59: Summary: Merge
60: Author: Brouard
61:
62: Merge, before building revised version.
63:
1.146 brouard 64: Revision 1.145 2014/06/10 21:23:15 brouard
65: Summary: Debugging with valgrind
66: Author: Nicolas Brouard
67:
68: Lot of changes in order to output the results with some covariates
69: After the Edimburgh REVES conference 2014, it seems mandatory to
70: improve the code.
71: No more memory valgrind error but a lot has to be done in order to
72: continue the work of splitting the code into subroutines.
73: Also, decodemodel has been improved. Tricode is still not
74: optimal. nbcode should be improved. Documentation has been added in
75: the source code.
76:
1.144 brouard 77: Revision 1.143 2014/01/26 09:45:38 brouard
78: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
79:
80: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
81: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
82:
1.143 brouard 83: Revision 1.142 2014/01/26 03:57:36 brouard
84: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
85:
86: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
87:
1.142 brouard 88: Revision 1.141 2014/01/26 02:42:01 brouard
89: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
90:
1.141 brouard 91: Revision 1.140 2011/09/02 10:37:54 brouard
92: Summary: times.h is ok with mingw32 now.
93:
1.140 brouard 94: Revision 1.139 2010/06/14 07:50:17 brouard
95: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
96: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
97:
1.139 brouard 98: Revision 1.138 2010/04/30 18:19:40 brouard
99: *** empty log message ***
100:
1.138 brouard 101: Revision 1.137 2010/04/29 18:11:38 brouard
102: (Module): Checking covariates for more complex models
103: than V1+V2. A lot of change to be done. Unstable.
104:
1.137 brouard 105: Revision 1.136 2010/04/26 20:30:53 brouard
106: (Module): merging some libgsl code. Fixing computation
107: of likelione (using inter/intrapolation if mle = 0) in order to
108: get same likelihood as if mle=1.
109: Some cleaning of code and comments added.
110:
1.136 brouard 111: Revision 1.135 2009/10/29 15:33:14 brouard
112: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
113:
1.135 brouard 114: Revision 1.134 2009/10/29 13:18:53 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.134 brouard 117: Revision 1.133 2009/07/06 10:21:25 brouard
118: just nforces
119:
1.133 brouard 120: Revision 1.132 2009/07/06 08:22:05 brouard
121: Many tings
122:
1.132 brouard 123: Revision 1.131 2009/06/20 16:22:47 brouard
124: Some dimensions resccaled
125:
1.131 brouard 126: Revision 1.130 2009/05/26 06:44:34 brouard
127: (Module): Max Covariate is now set to 20 instead of 8. A
128: lot of cleaning with variables initialized to 0. Trying to make
129: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
130:
1.130 brouard 131: Revision 1.129 2007/08/31 13:49:27 lievre
132: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
133:
1.129 lievre 134: Revision 1.128 2006/06/30 13:02:05 brouard
135: (Module): Clarifications on computing e.j
136:
1.128 brouard 137: Revision 1.127 2006/04/28 18:11:50 brouard
138: (Module): Yes the sum of survivors was wrong since
139: imach-114 because nhstepm was no more computed in the age
140: loop. Now we define nhstepma in the age loop.
141: (Module): In order to speed up (in case of numerous covariates) we
142: compute health expectancies (without variances) in a first step
143: and then all the health expectancies with variances or standard
144: deviation (needs data from the Hessian matrices) which slows the
145: computation.
146: In the future we should be able to stop the program is only health
147: expectancies and graph are needed without standard deviations.
148:
1.127 brouard 149: Revision 1.126 2006/04/28 17:23:28 brouard
150: (Module): Yes the sum of survivors was wrong since
151: imach-114 because nhstepm was no more computed in the age
152: loop. Now we define nhstepma in the age loop.
153: Version 0.98h
154:
1.126 brouard 155: Revision 1.125 2006/04/04 15:20:31 lievre
156: Errors in calculation of health expectancies. Age was not initialized.
157: Forecasting file added.
158:
159: Revision 1.124 2006/03/22 17:13:53 lievre
160: Parameters are printed with %lf instead of %f (more numbers after the comma).
161: The log-likelihood is printed in the log file
162:
163: Revision 1.123 2006/03/20 10:52:43 brouard
164: * imach.c (Module): <title> changed, corresponds to .htm file
165: name. <head> headers where missing.
166:
167: * imach.c (Module): Weights can have a decimal point as for
168: English (a comma might work with a correct LC_NUMERIC environment,
169: otherwise the weight is truncated).
170: Modification of warning when the covariates values are not 0 or
171: 1.
172: Version 0.98g
173:
174: Revision 1.122 2006/03/20 09:45:41 brouard
175: (Module): Weights can have a decimal point as for
176: English (a comma might work with a correct LC_NUMERIC environment,
177: otherwise the weight is truncated).
178: Modification of warning when the covariates values are not 0 or
179: 1.
180: Version 0.98g
181:
182: Revision 1.121 2006/03/16 17:45:01 lievre
183: * imach.c (Module): Comments concerning covariates added
184:
185: * imach.c (Module): refinements in the computation of lli if
186: status=-2 in order to have more reliable computation if stepm is
187: not 1 month. Version 0.98f
188:
189: Revision 1.120 2006/03/16 15:10:38 lievre
190: (Module): refinements in the computation of lli if
191: status=-2 in order to have more reliable computation if stepm is
192: not 1 month. Version 0.98f
193:
194: Revision 1.119 2006/03/15 17:42:26 brouard
195: (Module): Bug if status = -2, the loglikelihood was
196: computed as likelihood omitting the logarithm. Version O.98e
197:
198: Revision 1.118 2006/03/14 18:20:07 brouard
199: (Module): varevsij Comments added explaining the second
200: table of variances if popbased=1 .
201: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
202: (Module): Function pstamp added
203: (Module): Version 0.98d
204:
205: Revision 1.117 2006/03/14 17:16:22 brouard
206: (Module): varevsij Comments added explaining the second
207: table of variances if popbased=1 .
208: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
209: (Module): Function pstamp added
210: (Module): Version 0.98d
211:
212: Revision 1.116 2006/03/06 10:29:27 brouard
213: (Module): Variance-covariance wrong links and
214: varian-covariance of ej. is needed (Saito).
215:
216: Revision 1.115 2006/02/27 12:17:45 brouard
217: (Module): One freematrix added in mlikeli! 0.98c
218:
219: Revision 1.114 2006/02/26 12:57:58 brouard
220: (Module): Some improvements in processing parameter
221: filename with strsep.
222:
223: Revision 1.113 2006/02/24 14:20:24 brouard
224: (Module): Memory leaks checks with valgrind and:
225: datafile was not closed, some imatrix were not freed and on matrix
226: allocation too.
227:
228: Revision 1.112 2006/01/30 09:55:26 brouard
229: (Module): Back to gnuplot.exe instead of wgnuplot.exe
230:
231: Revision 1.111 2006/01/25 20:38:18 brouard
232: (Module): Lots of cleaning and bugs added (Gompertz)
233: (Module): Comments can be added in data file. Missing date values
234: can be a simple dot '.'.
235:
236: Revision 1.110 2006/01/25 00:51:50 brouard
237: (Module): Lots of cleaning and bugs added (Gompertz)
238:
239: Revision 1.109 2006/01/24 19:37:15 brouard
240: (Module): Comments (lines starting with a #) are allowed in data.
241:
242: Revision 1.108 2006/01/19 18:05:42 lievre
243: Gnuplot problem appeared...
244: To be fixed
245:
246: Revision 1.107 2006/01/19 16:20:37 brouard
247: Test existence of gnuplot in imach path
248:
249: Revision 1.106 2006/01/19 13:24:36 brouard
250: Some cleaning and links added in html output
251:
252: Revision 1.105 2006/01/05 20:23:19 lievre
253: *** empty log message ***
254:
255: Revision 1.104 2005/09/30 16:11:43 lievre
256: (Module): sump fixed, loop imx fixed, and simplifications.
257: (Module): If the status is missing at the last wave but we know
258: that the person is alive, then we can code his/her status as -2
259: (instead of missing=-1 in earlier versions) and his/her
260: contributions to the likelihood is 1 - Prob of dying from last
261: health status (= 1-p13= p11+p12 in the easiest case of somebody in
262: the healthy state at last known wave). Version is 0.98
263:
264: Revision 1.103 2005/09/30 15:54:49 lievre
265: (Module): sump fixed, loop imx fixed, and simplifications.
266:
267: Revision 1.102 2004/09/15 17:31:30 brouard
268: Add the possibility to read data file including tab characters.
269:
270: Revision 1.101 2004/09/15 10:38:38 brouard
271: Fix on curr_time
272:
273: Revision 1.100 2004/07/12 18:29:06 brouard
274: Add version for Mac OS X. Just define UNIX in Makefile
275:
276: Revision 1.99 2004/06/05 08:57:40 brouard
277: *** empty log message ***
278:
279: Revision 1.98 2004/05/16 15:05:56 brouard
280: New version 0.97 . First attempt to estimate force of mortality
281: directly from the data i.e. without the need of knowing the health
282: state at each age, but using a Gompertz model: log u =a + b*age .
283: This is the basic analysis of mortality and should be done before any
284: other analysis, in order to test if the mortality estimated from the
285: cross-longitudinal survey is different from the mortality estimated
286: from other sources like vital statistic data.
287:
288: The same imach parameter file can be used but the option for mle should be -3.
289:
1.133 brouard 290: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 291: former routines in order to include the new code within the former code.
292:
293: The output is very simple: only an estimate of the intercept and of
294: the slope with 95% confident intervals.
295:
296: Current limitations:
297: A) Even if you enter covariates, i.e. with the
298: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
299: B) There is no computation of Life Expectancy nor Life Table.
300:
301: Revision 1.97 2004/02/20 13:25:42 lievre
302: Version 0.96d. Population forecasting command line is (temporarily)
303: suppressed.
304:
305: Revision 1.96 2003/07/15 15:38:55 brouard
306: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
307: rewritten within the same printf. Workaround: many printfs.
308:
309: Revision 1.95 2003/07/08 07:54:34 brouard
310: * imach.c (Repository):
311: (Repository): Using imachwizard code to output a more meaningful covariance
312: matrix (cov(a12,c31) instead of numbers.
313:
314: Revision 1.94 2003/06/27 13:00:02 brouard
315: Just cleaning
316:
317: Revision 1.93 2003/06/25 16:33:55 brouard
318: (Module): On windows (cygwin) function asctime_r doesn't
319: exist so I changed back to asctime which exists.
320: (Module): Version 0.96b
321:
322: Revision 1.92 2003/06/25 16:30:45 brouard
323: (Module): On windows (cygwin) function asctime_r doesn't
324: exist so I changed back to asctime which exists.
325:
326: Revision 1.91 2003/06/25 15:30:29 brouard
327: * imach.c (Repository): Duplicated warning errors corrected.
328: (Repository): Elapsed time after each iteration is now output. It
329: helps to forecast when convergence will be reached. Elapsed time
330: is stamped in powell. We created a new html file for the graphs
331: concerning matrix of covariance. It has extension -cov.htm.
332:
333: Revision 1.90 2003/06/24 12:34:15 brouard
334: (Module): Some bugs corrected for windows. Also, when
335: mle=-1 a template is output in file "or"mypar.txt with the design
336: of the covariance matrix to be input.
337:
338: Revision 1.89 2003/06/24 12:30:52 brouard
339: (Module): Some bugs corrected for windows. Also, when
340: mle=-1 a template is output in file "or"mypar.txt with the design
341: of the covariance matrix to be input.
342:
343: Revision 1.88 2003/06/23 17:54:56 brouard
344: * 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.
345:
346: Revision 1.87 2003/06/18 12:26:01 brouard
347: Version 0.96
348:
349: Revision 1.86 2003/06/17 20:04:08 brouard
350: (Module): Change position of html and gnuplot routines and added
351: routine fileappend.
352:
353: Revision 1.85 2003/06/17 13:12:43 brouard
354: * imach.c (Repository): Check when date of death was earlier that
355: current date of interview. It may happen when the death was just
356: prior to the death. In this case, dh was negative and likelihood
357: was wrong (infinity). We still send an "Error" but patch by
358: assuming that the date of death was just one stepm after the
359: interview.
360: (Repository): Because some people have very long ID (first column)
361: we changed int to long in num[] and we added a new lvector for
362: memory allocation. But we also truncated to 8 characters (left
363: truncation)
364: (Repository): No more line truncation errors.
365:
366: Revision 1.84 2003/06/13 21:44:43 brouard
367: * imach.c (Repository): Replace "freqsummary" at a correct
368: place. It differs from routine "prevalence" which may be called
369: many times. Probs is memory consuming and must be used with
370: parcimony.
371: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
372:
373: Revision 1.83 2003/06/10 13:39:11 lievre
374: *** empty log message ***
375:
376: Revision 1.82 2003/06/05 15:57:20 brouard
377: Add log in imach.c and fullversion number is now printed.
378:
379: */
380: /*
381: Interpolated Markov Chain
382:
383: Short summary of the programme:
384:
385: This program computes Healthy Life Expectancies from
386: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
387: first survey ("cross") where individuals from different ages are
388: interviewed on their health status or degree of disability (in the
389: case of a health survey which is our main interest) -2- at least a
390: second wave of interviews ("longitudinal") which measure each change
391: (if any) in individual health status. Health expectancies are
392: computed from the time spent in each health state according to a
393: model. More health states you consider, more time is necessary to reach the
394: Maximum Likelihood of the parameters involved in the model. The
395: simplest model is the multinomial logistic model where pij is the
396: probability to be observed in state j at the second wave
397: conditional to be observed in state i at the first wave. Therefore
398: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
399: 'age' is age and 'sex' is a covariate. If you want to have a more
400: complex model than "constant and age", you should modify the program
401: where the markup *Covariates have to be included here again* invites
402: you to do it. More covariates you add, slower the
403: convergence.
404:
405: The advantage of this computer programme, compared to a simple
406: multinomial logistic model, is clear when the delay between waves is not
407: identical for each individual. Also, if a individual missed an
408: intermediate interview, the information is lost, but taken into
409: account using an interpolation or extrapolation.
410:
411: hPijx is the probability to be observed in state i at age x+h
412: conditional to the observed state i at age x. The delay 'h' can be
413: split into an exact number (nh*stepm) of unobserved intermediate
414: states. This elementary transition (by month, quarter,
415: semester or year) is modelled as a multinomial logistic. The hPx
416: matrix is simply the matrix product of nh*stepm elementary matrices
417: and the contribution of each individual to the likelihood is simply
418: hPijx.
419:
420: Also this programme outputs the covariance matrix of the parameters but also
421: of the life expectancies. It also computes the period (stable) prevalence.
422:
1.133 brouard 423: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
424: Institut national d'études démographiques, Paris.
1.126 brouard 425: This software have been partly granted by Euro-REVES, a concerted action
426: from the European Union.
427: It is copyrighted identically to a GNU software product, ie programme and
428: software can be distributed freely for non commercial use. Latest version
429: can be accessed at http://euroreves.ined.fr/imach .
430:
431: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
432: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
433:
434: **********************************************************************/
435: /*
436: main
437: read parameterfile
438: read datafile
439: concatwav
440: freqsummary
441: if (mle >= 1)
442: mlikeli
443: print results files
444: if mle==1
445: computes hessian
446: read end of parameter file: agemin, agemax, bage, fage, estepm
447: begin-prev-date,...
448: open gnuplot file
449: open html file
1.145 brouard 450: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
451: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
452: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
453: freexexit2 possible for memory heap.
454:
455: h Pij x | pij_nom ficrestpij
456: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
457: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
458: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
459:
460: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
461: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
462: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
463: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
464: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
465:
1.126 brouard 466: forecasting if prevfcast==1 prevforecast call prevalence()
467: health expectancies
468: Variance-covariance of DFLE
469: prevalence()
470: movingaverage()
471: varevsij()
472: if popbased==1 varevsij(,popbased)
473: total life expectancies
474: Variance of period (stable) prevalence
475: end
476: */
477:
478:
479:
480:
481: #include <math.h>
482: #include <stdio.h>
483: #include <stdlib.h>
484: #include <string.h>
1.159 brouard 485:
486: #ifdef _WIN32
487: #include <io.h>
488: #else
1.126 brouard 489: #include <unistd.h>
1.159 brouard 490: #endif
1.126 brouard 491:
492: #include <limits.h>
493: #include <sys/types.h>
494: #include <sys/stat.h>
495: #include <errno.h>
1.159 brouard 496: /* extern int errno; */
1.126 brouard 497:
1.157 brouard 498: /* #ifdef LINUX */
499: /* #include <time.h> */
500: /* #include "timeval.h" */
501: /* #else */
502: /* #include <sys/time.h> */
503: /* #endif */
504:
1.126 brouard 505: #include <time.h>
506:
1.136 brouard 507: #ifdef GSL
508: #include <gsl/gsl_errno.h>
509: #include <gsl/gsl_multimin.h>
510: #endif
511:
1.126 brouard 512: /* #include <libintl.h> */
513: /* #define _(String) gettext (String) */
514:
1.141 brouard 515: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 516:
517: #define GNUPLOTPROGRAM "gnuplot"
518: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
519: #define FILENAMELENGTH 132
520:
521: #define GLOCK_ERROR_NOPATH -1 /* empty path */
522: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
523:
1.144 brouard 524: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
525: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 526:
527: #define NINTERVMAX 8
1.144 brouard 528: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
529: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
530: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 531: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 532: #define MAXN 20000
1.144 brouard 533: #define YEARM 12. /**< Number of months per year */
1.126 brouard 534: #define AGESUP 130
535: #define AGEBASE 40
1.144 brouard 536: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.157 brouard 537: #ifdef _WIN32
538: #define DIRSEPARATOR '\\'
539: #define CHARSEPARATOR "\\"
540: #define ODIRSEPARATOR '/'
541: #else
1.126 brouard 542: #define DIRSEPARATOR '/'
543: #define CHARSEPARATOR "/"
544: #define ODIRSEPARATOR '\\'
545: #endif
546:
1.160 ! brouard 547: /* $Id: imach.c,v 1.159 2014/09/01 10:34:10 brouard Exp $ */
1.126 brouard 548: /* $State: Exp $ */
549:
1.157 brouard 550: 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.160 ! brouard 551: char fullversion[]="$Revision: 1.159 $ $Date: 2014/09/01 10:34:10 $";
1.126 brouard 552: char strstart[80];
553: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 554: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 555: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 556: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
557: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
558: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
559: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
560: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
561: int cptcovprodnoage=0; /**< Number of covariate products without age */
562: int cptcoveff=0; /* Total number of covariates to vary for printing results */
563: int cptcov=0; /* Working variable */
1.126 brouard 564: int npar=NPARMAX;
565: int nlstate=2; /* Number of live states */
566: int ndeath=1; /* Number of dead states */
1.130 brouard 567: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 568: int popbased=0;
569:
570: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 571: int maxwav=0; /* Maxim number of waves */
572: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
573: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
574: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 575: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 576: int mle=1, weightopt=0;
1.126 brouard 577: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
578: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
579: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
580: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130 brouard 581: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 582: double **matprod2(); /* test */
1.126 brouard 583: double **oldm, **newm, **savm; /* Working pointers to matrices */
584: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 585: /*FILE *fic ; */ /* Used in readdata only */
586: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 587: FILE *ficlog, *ficrespow;
1.130 brouard 588: int globpr=0; /* Global variable for printing or not */
1.126 brouard 589: double fretone; /* Only one call to likelihood */
1.130 brouard 590: long ipmx=0; /* Number of contributions */
1.126 brouard 591: double sw; /* Sum of weights */
592: char filerespow[FILENAMELENGTH];
593: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
594: FILE *ficresilk;
595: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
596: FILE *ficresprobmorprev;
597: FILE *fichtm, *fichtmcov; /* Html File */
598: FILE *ficreseij;
599: char filerese[FILENAMELENGTH];
600: FILE *ficresstdeij;
601: char fileresstde[FILENAMELENGTH];
602: FILE *ficrescveij;
603: char filerescve[FILENAMELENGTH];
604: FILE *ficresvij;
605: char fileresv[FILENAMELENGTH];
606: FILE *ficresvpl;
607: char fileresvpl[FILENAMELENGTH];
608: char title[MAXLINE];
609: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
610: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
611: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
612: char command[FILENAMELENGTH];
613: int outcmd=0;
614:
615: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
616:
617: char filelog[FILENAMELENGTH]; /* Log file */
618: char filerest[FILENAMELENGTH];
619: char fileregp[FILENAMELENGTH];
620: char popfile[FILENAMELENGTH];
621:
622: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
623:
1.157 brouard 624: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
625: /* struct timezone tzp; */
626: /* extern int gettimeofday(); */
627: struct tm tml, *gmtime(), *localtime();
628:
629: extern time_t time();
630:
631: struct tm start_time, end_time, curr_time, last_time, forecast_time;
632: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
633: struct tm tm;
634:
1.126 brouard 635: char strcurr[80], strfor[80];
636:
637: char *endptr;
638: long lval;
639: double dval;
640:
641: #define NR_END 1
642: #define FREE_ARG char*
643: #define FTOL 1.0e-10
644:
645: #define NRANSI
646: #define ITMAX 200
647:
648: #define TOL 2.0e-4
649:
650: #define CGOLD 0.3819660
651: #define ZEPS 1.0e-10
652: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
653:
654: #define GOLD 1.618034
655: #define GLIMIT 100.0
656: #define TINY 1.0e-20
657:
658: static double maxarg1,maxarg2;
659: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
660: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
661:
662: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
663: #define rint(a) floor(a+0.5)
664:
665: static double sqrarg;
666: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
667: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
668: int agegomp= AGEGOMP;
669:
670: int imx;
671: int stepm=1;
672: /* Stepm, step in month: minimum step interpolation*/
673:
674: int estepm;
675: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
676:
677: int m,nb;
678: long *num;
679: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
680: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
681: double **pmmij, ***probs;
682: double *ageexmed,*agecens;
683: double dateintmean=0;
684:
685: double *weight;
686: int **s; /* Status */
1.141 brouard 687: double *agedc;
1.145 brouard 688: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 689: * covar=matrix(0,NCOVMAX,1,n);
690: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
691: double idx;
692: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 693: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 694: int **codtab; /**< codtab=imatrix(1,100,1,10); */
695: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 696: double *lsurv, *lpop, *tpop;
697:
1.143 brouard 698: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
699: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 700:
701: /**************** split *************************/
702: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
703: {
704: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
705: the name of the file (name), its extension only (ext) and its first part of the name (finame)
706: */
707: char *ss; /* pointer */
708: int l1, l2; /* length counters */
709:
710: l1 = strlen(path ); /* length of path */
711: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
712: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
713: if ( ss == NULL ) { /* no directory, so determine current directory */
714: strcpy( name, path ); /* we got the fullname name because no directory */
715: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
716: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
717: /* get current working directory */
718: /* extern char* getcwd ( char *buf , int len);*/
719: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
720: return( GLOCK_ERROR_GETCWD );
721: }
722: /* got dirc from getcwd*/
723: printf(" DIRC = %s \n",dirc);
724: } else { /* strip direcotry from path */
725: ss++; /* after this, the filename */
726: l2 = strlen( ss ); /* length of filename */
727: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
728: strcpy( name, ss ); /* save file name */
729: strncpy( dirc, path, l1 - l2 ); /* now the directory */
730: dirc[l1-l2] = 0; /* add zero */
731: printf(" DIRC2 = %s \n",dirc);
732: }
733: /* We add a separator at the end of dirc if not exists */
734: l1 = strlen( dirc ); /* length of directory */
735: if( dirc[l1-1] != DIRSEPARATOR ){
736: dirc[l1] = DIRSEPARATOR;
737: dirc[l1+1] = 0;
738: printf(" DIRC3 = %s \n",dirc);
739: }
740: ss = strrchr( name, '.' ); /* find last / */
741: if (ss >0){
742: ss++;
743: strcpy(ext,ss); /* save extension */
744: l1= strlen( name);
745: l2= strlen(ss)+1;
746: strncpy( finame, name, l1-l2);
747: finame[l1-l2]= 0;
748: }
749:
750: return( 0 ); /* we're done */
751: }
752:
753:
754: /******************************************/
755:
756: void replace_back_to_slash(char *s, char*t)
757: {
758: int i;
759: int lg=0;
760: i=0;
761: lg=strlen(t);
762: for(i=0; i<= lg; i++) {
763: (s[i] = t[i]);
764: if (t[i]== '\\') s[i]='/';
765: }
766: }
767:
1.132 brouard 768: char *trimbb(char *out, char *in)
1.137 brouard 769: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 770: char *s;
771: s=out;
772: while (*in != '\0'){
1.137 brouard 773: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 774: in++;
775: }
776: *out++ = *in++;
777: }
778: *out='\0';
779: return s;
780: }
781:
1.145 brouard 782: char *cutl(char *blocc, char *alocc, char *in, char occ)
783: {
784: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
785: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
786: gives blocc="abcdef2ghi" and alocc="j".
787: If occ is not found blocc is null and alocc is equal to in. Returns blocc
788: */
1.160 ! brouard 789: char *s, *t;
1.145 brouard 790: t=in;s=in;
791: while ((*in != occ) && (*in != '\0')){
792: *alocc++ = *in++;
793: }
794: if( *in == occ){
795: *(alocc)='\0';
796: s=++in;
797: }
798:
799: if (s == t) {/* occ not found */
800: *(alocc-(in-s))='\0';
801: in=s;
802: }
803: while ( *in != '\0'){
804: *blocc++ = *in++;
805: }
806:
807: *blocc='\0';
808: return t;
809: }
1.137 brouard 810: char *cutv(char *blocc, char *alocc, char *in, char occ)
811: {
812: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
813: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
814: gives blocc="abcdef2ghi" and alocc="j".
815: If occ is not found blocc is null and alocc is equal to in. Returns alocc
816: */
817: char *s, *t;
818: t=in;s=in;
819: while (*in != '\0'){
820: while( *in == occ){
821: *blocc++ = *in++;
822: s=in;
823: }
824: *blocc++ = *in++;
825: }
826: if (s == t) /* occ not found */
827: *(blocc-(in-s))='\0';
828: else
829: *(blocc-(in-s)-1)='\0';
830: in=s;
831: while ( *in != '\0'){
832: *alocc++ = *in++;
833: }
834:
835: *alocc='\0';
836: return s;
837: }
838:
1.126 brouard 839: int nbocc(char *s, char occ)
840: {
841: int i,j=0;
842: int lg=20;
843: i=0;
844: lg=strlen(s);
845: for(i=0; i<= lg; i++) {
846: if (s[i] == occ ) j++;
847: }
848: return j;
849: }
850:
1.137 brouard 851: /* void cutv(char *u,char *v, char*t, char occ) */
852: /* { */
853: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
854: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
855: /* gives u="abcdef2ghi" and v="j" *\/ */
856: /* int i,lg,j,p=0; */
857: /* i=0; */
858: /* lg=strlen(t); */
859: /* for(j=0; j<=lg-1; j++) { */
860: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
861: /* } */
1.126 brouard 862:
1.137 brouard 863: /* for(j=0; j<p; j++) { */
864: /* (u[j] = t[j]); */
865: /* } */
866: /* u[p]='\0'; */
1.126 brouard 867:
1.137 brouard 868: /* for(j=0; j<= lg; j++) { */
869: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
870: /* } */
871: /* } */
1.126 brouard 872:
1.160 ! brouard 873: #ifdef _WIN32
! 874: char * strsep(char **pp, const char *delim)
! 875: {
! 876: char *p, *q;
! 877:
! 878: if ((p = *pp) == NULL)
! 879: return 0;
! 880: if ((q = strpbrk (p, delim)) != NULL)
! 881: {
! 882: *pp = q + 1;
! 883: *q = '\0';
! 884: }
! 885: else
! 886: *pp = 0;
! 887: return p;
! 888: }
! 889: #endif
! 890:
1.126 brouard 891: /********************** nrerror ********************/
892:
893: void nrerror(char error_text[])
894: {
895: fprintf(stderr,"ERREUR ...\n");
896: fprintf(stderr,"%s\n",error_text);
897: exit(EXIT_FAILURE);
898: }
899: /*********************** vector *******************/
900: double *vector(int nl, int nh)
901: {
902: double *v;
903: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
904: if (!v) nrerror("allocation failure in vector");
905: return v-nl+NR_END;
906: }
907:
908: /************************ free vector ******************/
909: void free_vector(double*v, int nl, int nh)
910: {
911: free((FREE_ARG)(v+nl-NR_END));
912: }
913:
914: /************************ivector *******************************/
915: int *ivector(long nl,long nh)
916: {
917: int *v;
918: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
919: if (!v) nrerror("allocation failure in ivector");
920: return v-nl+NR_END;
921: }
922:
923: /******************free ivector **************************/
924: void free_ivector(int *v, long nl, long nh)
925: {
926: free((FREE_ARG)(v+nl-NR_END));
927: }
928:
929: /************************lvector *******************************/
930: long *lvector(long nl,long nh)
931: {
932: long *v;
933: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
934: if (!v) nrerror("allocation failure in ivector");
935: return v-nl+NR_END;
936: }
937:
938: /******************free lvector **************************/
939: void free_lvector(long *v, long nl, long nh)
940: {
941: free((FREE_ARG)(v+nl-NR_END));
942: }
943:
944: /******************* imatrix *******************************/
945: int **imatrix(long nrl, long nrh, long ncl, long nch)
946: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
947: {
948: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
949: int **m;
950:
951: /* allocate pointers to rows */
952: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
953: if (!m) nrerror("allocation failure 1 in matrix()");
954: m += NR_END;
955: m -= nrl;
956:
957:
958: /* allocate rows and set pointers to them */
959: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
960: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
961: m[nrl] += NR_END;
962: m[nrl] -= ncl;
963:
964: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
965:
966: /* return pointer to array of pointers to rows */
967: return m;
968: }
969:
970: /****************** free_imatrix *************************/
971: void free_imatrix(m,nrl,nrh,ncl,nch)
972: int **m;
973: long nch,ncl,nrh,nrl;
974: /* free an int matrix allocated by imatrix() */
975: {
976: free((FREE_ARG) (m[nrl]+ncl-NR_END));
977: free((FREE_ARG) (m+nrl-NR_END));
978: }
979:
980: /******************* matrix *******************************/
981: double **matrix(long nrl, long nrh, long ncl, long nch)
982: {
983: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
984: double **m;
985:
986: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
987: if (!m) nrerror("allocation failure 1 in matrix()");
988: m += NR_END;
989: m -= nrl;
990:
991: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
992: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
993: m[nrl] += NR_END;
994: m[nrl] -= ncl;
995:
996: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
997: return m;
1.145 brouard 998: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
999: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1000: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1001: */
1002: }
1003:
1004: /*************************free matrix ************************/
1005: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1006: {
1007: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1008: free((FREE_ARG)(m+nrl-NR_END));
1009: }
1010:
1011: /******************* ma3x *******************************/
1012: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1013: {
1014: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1015: double ***m;
1016:
1017: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1018: if (!m) nrerror("allocation failure 1 in matrix()");
1019: m += NR_END;
1020: m -= nrl;
1021:
1022: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1023: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1024: m[nrl] += NR_END;
1025: m[nrl] -= ncl;
1026:
1027: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1028:
1029: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1030: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1031: m[nrl][ncl] += NR_END;
1032: m[nrl][ncl] -= nll;
1033: for (j=ncl+1; j<=nch; j++)
1034: m[nrl][j]=m[nrl][j-1]+nlay;
1035:
1036: for (i=nrl+1; i<=nrh; i++) {
1037: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1038: for (j=ncl+1; j<=nch; j++)
1039: m[i][j]=m[i][j-1]+nlay;
1040: }
1041: return m;
1042: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1043: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1044: */
1045: }
1046:
1047: /*************************free ma3x ************************/
1048: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1049: {
1050: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1051: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1052: free((FREE_ARG)(m+nrl-NR_END));
1053: }
1054:
1055: /*************** function subdirf ***********/
1056: char *subdirf(char fileres[])
1057: {
1058: /* Caution optionfilefiname is hidden */
1059: strcpy(tmpout,optionfilefiname);
1060: strcat(tmpout,"/"); /* Add to the right */
1061: strcat(tmpout,fileres);
1062: return tmpout;
1063: }
1064:
1065: /*************** function subdirf2 ***********/
1066: char *subdirf2(char fileres[], char *preop)
1067: {
1068:
1069: /* Caution optionfilefiname is hidden */
1070: strcpy(tmpout,optionfilefiname);
1071: strcat(tmpout,"/");
1072: strcat(tmpout,preop);
1073: strcat(tmpout,fileres);
1074: return tmpout;
1075: }
1076:
1077: /*************** function subdirf3 ***********/
1078: char *subdirf3(char fileres[], char *preop, char *preop2)
1079: {
1080:
1081: /* Caution optionfilefiname is hidden */
1082: strcpy(tmpout,optionfilefiname);
1083: strcat(tmpout,"/");
1084: strcat(tmpout,preop);
1085: strcat(tmpout,preop2);
1086: strcat(tmpout,fileres);
1087: return tmpout;
1088: }
1089:
1090: /***************** f1dim *************************/
1091: extern int ncom;
1092: extern double *pcom,*xicom;
1093: extern double (*nrfunc)(double []);
1094:
1095: double f1dim(double x)
1096: {
1097: int j;
1098: double f;
1099: double *xt;
1100:
1101: xt=vector(1,ncom);
1102: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1103: f=(*nrfunc)(xt);
1104: free_vector(xt,1,ncom);
1105: return f;
1106: }
1107:
1108: /*****************brent *************************/
1109: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1110: {
1111: int iter;
1112: double a,b,d,etemp;
1.159 brouard 1113: double fu=0,fv,fw,fx;
1.126 brouard 1114: double ftemp;
1115: double p,q,r,tol1,tol2,u,v,w,x,xm;
1116: double e=0.0;
1117:
1118: a=(ax < cx ? ax : cx);
1119: b=(ax > cx ? ax : cx);
1120: x=w=v=bx;
1121: fw=fv=fx=(*f)(x);
1122: for (iter=1;iter<=ITMAX;iter++) {
1123: xm=0.5*(a+b);
1124: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1125: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1126: printf(".");fflush(stdout);
1127: fprintf(ficlog,".");fflush(ficlog);
1128: #ifdef DEBUG
1129: 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);
1130: 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);
1131: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1132: #endif
1133: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1134: *xmin=x;
1135: return fx;
1136: }
1137: ftemp=fu;
1138: if (fabs(e) > tol1) {
1139: r=(x-w)*(fx-fv);
1140: q=(x-v)*(fx-fw);
1141: p=(x-v)*q-(x-w)*r;
1142: q=2.0*(q-r);
1143: if (q > 0.0) p = -p;
1144: q=fabs(q);
1145: etemp=e;
1146: e=d;
1147: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1148: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1149: else {
1150: d=p/q;
1151: u=x+d;
1152: if (u-a < tol2 || b-u < tol2)
1153: d=SIGN(tol1,xm-x);
1154: }
1155: } else {
1156: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1157: }
1158: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1159: fu=(*f)(u);
1160: if (fu <= fx) {
1161: if (u >= x) a=x; else b=x;
1162: SHFT(v,w,x,u)
1163: SHFT(fv,fw,fx,fu)
1164: } else {
1165: if (u < x) a=u; else b=u;
1166: if (fu <= fw || w == x) {
1167: v=w;
1168: w=u;
1169: fv=fw;
1170: fw=fu;
1171: } else if (fu <= fv || v == x || v == w) {
1172: v=u;
1173: fv=fu;
1174: }
1175: }
1176: }
1177: nrerror("Too many iterations in brent");
1178: *xmin=x;
1179: return fx;
1180: }
1181:
1182: /****************** mnbrak ***********************/
1183:
1184: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1185: double (*func)(double))
1186: {
1187: double ulim,u,r,q, dum;
1188: double fu;
1189:
1190: *fa=(*func)(*ax);
1191: *fb=(*func)(*bx);
1192: if (*fb > *fa) {
1193: SHFT(dum,*ax,*bx,dum)
1194: SHFT(dum,*fb,*fa,dum)
1195: }
1196: *cx=(*bx)+GOLD*(*bx-*ax);
1197: *fc=(*func)(*cx);
1198: while (*fb > *fc) {
1199: r=(*bx-*ax)*(*fb-*fc);
1200: q=(*bx-*cx)*(*fb-*fa);
1201: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1202: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
1203: ulim=(*bx)+GLIMIT*(*cx-*bx);
1204: if ((*bx-u)*(u-*cx) > 0.0) {
1205: fu=(*func)(u);
1206: } else if ((*cx-u)*(u-ulim) > 0.0) {
1207: fu=(*func)(u);
1208: if (fu < *fc) {
1209: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1210: SHFT(*fb,*fc,fu,(*func)(u))
1211: }
1212: } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
1213: u=ulim;
1214: fu=(*func)(u);
1215: } else {
1216: u=(*cx)+GOLD*(*cx-*bx);
1217: fu=(*func)(u);
1218: }
1219: SHFT(*ax,*bx,*cx,u)
1220: SHFT(*fa,*fb,*fc,fu)
1221: }
1222: }
1223:
1224: /*************** linmin ************************/
1225:
1226: int ncom;
1227: double *pcom,*xicom;
1228: double (*nrfunc)(double []);
1229:
1230: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1231: {
1232: double brent(double ax, double bx, double cx,
1233: double (*f)(double), double tol, double *xmin);
1234: double f1dim(double x);
1235: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1236: double *fc, double (*func)(double));
1237: int j;
1238: double xx,xmin,bx,ax;
1239: double fx,fb,fa;
1240:
1241: ncom=n;
1242: pcom=vector(1,n);
1243: xicom=vector(1,n);
1244: nrfunc=func;
1245: for (j=1;j<=n;j++) {
1246: pcom[j]=p[j];
1247: xicom[j]=xi[j];
1248: }
1249: ax=0.0;
1250: xx=1.0;
1251: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
1252: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
1253: #ifdef DEBUG
1254: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1255: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1256: #endif
1257: for (j=1;j<=n;j++) {
1258: xi[j] *= xmin;
1259: p[j] += xi[j];
1260: }
1261: free_vector(xicom,1,n);
1262: free_vector(pcom,1,n);
1263: }
1264:
1265: char *asc_diff_time(long time_sec, char ascdiff[])
1266: {
1267: long sec_left, days, hours, minutes;
1268: days = (time_sec) / (60*60*24);
1269: sec_left = (time_sec) % (60*60*24);
1270: hours = (sec_left) / (60*60) ;
1271: sec_left = (sec_left) %(60*60);
1272: minutes = (sec_left) /60;
1273: sec_left = (sec_left) % (60);
1.141 brouard 1274: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1.126 brouard 1275: return ascdiff;
1276: }
1277:
1278: /*************** powell ************************/
1279: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1280: double (*func)(double []))
1281: {
1282: void linmin(double p[], double xi[], int n, double *fret,
1283: double (*func)(double []));
1284: int i,ibig,j;
1285: double del,t,*pt,*ptt,*xit;
1286: double fp,fptt;
1287: double *xits;
1288: int niterf, itmp;
1289:
1290: pt=vector(1,n);
1291: ptt=vector(1,n);
1292: xit=vector(1,n);
1293: xits=vector(1,n);
1294: *fret=(*func)(p);
1295: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1296: rcurr_time = time(NULL);
1.126 brouard 1297: for (*iter=1;;++(*iter)) {
1298: fp=(*fret);
1299: ibig=0;
1300: del=0.0;
1.157 brouard 1301: rlast_time=rcurr_time;
1302: /* (void) gettimeofday(&curr_time,&tzp); */
1303: rcurr_time = time(NULL);
1304: curr_time = *localtime(&rcurr_time);
1305: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1306: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1307: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1308: for (i=1;i<=n;i++) {
1309: printf(" %d %.12f",i, p[i]);
1310: fprintf(ficlog," %d %.12lf",i, p[i]);
1311: fprintf(ficrespow," %.12lf", p[i]);
1312: }
1313: printf("\n");
1314: fprintf(ficlog,"\n");
1315: fprintf(ficrespow,"\n");fflush(ficrespow);
1316: if(*iter <=3){
1.157 brouard 1317: tml = *localtime(&rcurr_time);
1318: strcpy(strcurr,asctime(&tml));
1.126 brouard 1319: /* asctime_r(&tm,strcurr); */
1.157 brouard 1320: rforecast_time=rcurr_time;
1.126 brouard 1321: itmp = strlen(strcurr);
1322: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1323: strcurr[itmp-1]='\0';
1.157 brouard 1324: printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1325: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1326: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1327: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1328: forecast_time = *localtime(&rforecast_time);
1.126 brouard 1329: /* asctime_r(&tmf,strfor); */
1.157 brouard 1330: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1331: itmp = strlen(strfor);
1332: if(strfor[itmp-1]=='\n')
1333: strfor[itmp-1]='\0';
1.157 brouard 1334: 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);
1335: 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 1336: }
1337: }
1338: for (i=1;i<=n;i++) {
1339: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1340: fptt=(*fret);
1341: #ifdef DEBUG
1342: printf("fret=%lf \n",*fret);
1343: fprintf(ficlog,"fret=%lf \n",*fret);
1344: #endif
1345: printf("%d",i);fflush(stdout);
1346: fprintf(ficlog,"%d",i);fflush(ficlog);
1347: linmin(p,xit,n,fret,func);
1348: if (fabs(fptt-(*fret)) > del) {
1349: del=fabs(fptt-(*fret));
1350: ibig=i;
1351: }
1352: #ifdef DEBUG
1353: printf("%d %.12e",i,(*fret));
1354: fprintf(ficlog,"%d %.12e",i,(*fret));
1355: for (j=1;j<=n;j++) {
1356: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1357: printf(" x(%d)=%.12e",j,xit[j]);
1358: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1359: }
1360: for(j=1;j<=n;j++) {
1361: printf(" p=%.12e",p[j]);
1362: fprintf(ficlog," p=%.12e",p[j]);
1363: }
1364: printf("\n");
1365: fprintf(ficlog,"\n");
1366: #endif
1367: }
1368: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1369: #ifdef DEBUG
1370: int k[2],l;
1371: k[0]=1;
1372: k[1]=-1;
1373: printf("Max: %.12e",(*func)(p));
1374: fprintf(ficlog,"Max: %.12e",(*func)(p));
1375: for (j=1;j<=n;j++) {
1376: printf(" %.12e",p[j]);
1377: fprintf(ficlog," %.12e",p[j]);
1378: }
1379: printf("\n");
1380: fprintf(ficlog,"\n");
1381: for(l=0;l<=1;l++) {
1382: for (j=1;j<=n;j++) {
1383: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1384: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1385: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1386: }
1387: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1388: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1389: }
1390: #endif
1391:
1392:
1393: free_vector(xit,1,n);
1394: free_vector(xits,1,n);
1395: free_vector(ptt,1,n);
1396: free_vector(pt,1,n);
1397: return;
1398: }
1399: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1400: for (j=1;j<=n;j++) {
1401: ptt[j]=2.0*p[j]-pt[j];
1402: xit[j]=p[j]-pt[j];
1403: pt[j]=p[j];
1404: }
1405: fptt=(*func)(ptt);
1406: if (fptt < fp) {
1407: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
1408: if (t < 0.0) {
1409: linmin(p,xit,n,fret,func);
1410: for (j=1;j<=n;j++) {
1411: xi[j][ibig]=xi[j][n];
1412: xi[j][n]=xit[j];
1413: }
1414: #ifdef DEBUG
1415: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1416: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1417: for(j=1;j<=n;j++){
1418: printf(" %.12e",xit[j]);
1419: fprintf(ficlog," %.12e",xit[j]);
1420: }
1421: printf("\n");
1422: fprintf(ficlog,"\n");
1423: #endif
1424: }
1425: }
1426: }
1427: }
1428:
1429: /**** Prevalence limit (stable or period prevalence) ****************/
1430:
1431: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1432: {
1433: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1434: matrix by transitions matrix until convergence is reached */
1435:
1436: int i, ii,j,k;
1437: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1438: /* double **matprod2(); */ /* test */
1.131 brouard 1439: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1440: double **newm;
1441: double agefin, delaymax=50 ; /* Max number of years to converge */
1442:
1443: for (ii=1;ii<=nlstate+ndeath;ii++)
1444: for (j=1;j<=nlstate+ndeath;j++){
1445: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1446: }
1447:
1448: cov[1]=1.;
1449:
1450: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1451: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1452: newm=savm;
1453: /* Covariates have to be included here again */
1.138 brouard 1454: cov[2]=agefin;
1455:
1456: for (k=1; k<=cptcovn;k++) {
1457: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1458: /*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 1459: }
1.145 brouard 1460: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1461: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1462: /* 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 1463:
1464: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1465: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1466: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1467: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1468: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1469: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1470:
1.126 brouard 1471: savm=oldm;
1472: oldm=newm;
1473: maxmax=0.;
1474: for(j=1;j<=nlstate;j++){
1475: min=1.;
1476: max=0.;
1477: for(i=1; i<=nlstate; i++) {
1478: sumnew=0;
1479: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1480: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1481: /*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 1482: max=FMAX(max,prlim[i][j]);
1483: min=FMIN(min,prlim[i][j]);
1484: }
1485: maxmin=max-min;
1486: maxmax=FMAX(maxmax,maxmin);
1487: }
1488: if(maxmax < ftolpl){
1489: return prlim;
1490: }
1491: }
1492: }
1493:
1494: /*************** transition probabilities ***************/
1495:
1496: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1497: {
1.138 brouard 1498: /* According to parameters values stored in x and the covariate's values stored in cov,
1499: computes the probability to be observed in state j being in state i by appying the
1500: model to the ncovmodel covariates (including constant and age).
1501: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1502: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1503: ncth covariate in the global vector x is given by the formula:
1504: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1505: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1506: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1507: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1508: Outputs ps[i][j] the probability to be observed in j being in j according to
1509: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1510: */
1511: double s1, lnpijopii;
1.126 brouard 1512: /*double t34;*/
1513: int i,j,j1, nc, ii, jj;
1514:
1515: for(i=1; i<= nlstate; i++){
1516: for(j=1; j<i;j++){
1.138 brouard 1517: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1518: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1519: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1520: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1521: }
1.138 brouard 1522: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1523: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1524: }
1525: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1526: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1527: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1528: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1529: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1530: }
1.138 brouard 1531: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1532: }
1533: }
1534:
1535: for(i=1; i<= nlstate; i++){
1536: s1=0;
1.131 brouard 1537: for(j=1; j<i; j++){
1.138 brouard 1538: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1539: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1540: }
1541: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1542: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1543: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1544: }
1.138 brouard 1545: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1546: ps[i][i]=1./(s1+1.);
1.138 brouard 1547: /* Computing other pijs */
1.126 brouard 1548: for(j=1; j<i; j++)
1549: ps[i][j]= exp(ps[i][j])*ps[i][i];
1550: for(j=i+1; j<=nlstate+ndeath; j++)
1551: ps[i][j]= exp(ps[i][j])*ps[i][i];
1552: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1553: } /* end i */
1554:
1555: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1556: for(jj=1; jj<= nlstate+ndeath; jj++){
1557: ps[ii][jj]=0;
1558: ps[ii][ii]=1;
1559: }
1560: }
1561:
1.145 brouard 1562:
1563: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1564: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1565: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1566: /* } */
1567: /* printf("\n "); */
1568: /* } */
1569: /* printf("\n ");printf("%lf ",cov[2]);*/
1570: /*
1.126 brouard 1571: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1572: goto end;*/
1573: return ps;
1574: }
1575:
1576: /**************** Product of 2 matrices ******************/
1577:
1.145 brouard 1578: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1579: {
1580: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1581: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1582: /* in, b, out are matrice of pointers which should have been initialized
1583: before: only the contents of out is modified. The function returns
1584: a pointer to pointers identical to out */
1.145 brouard 1585: int i, j, k;
1.126 brouard 1586: for(i=nrl; i<= nrh; i++)
1.145 brouard 1587: for(k=ncolol; k<=ncoloh; k++){
1588: out[i][k]=0.;
1589: for(j=ncl; j<=nch; j++)
1590: out[i][k] +=in[i][j]*b[j][k];
1591: }
1.126 brouard 1592: return out;
1593: }
1594:
1595:
1596: /************* Higher Matrix Product ***************/
1597:
1598: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1599: {
1600: /* Computes the transition matrix starting at age 'age' over
1601: 'nhstepm*hstepm*stepm' months (i.e. until
1602: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1603: nhstepm*hstepm matrices.
1604: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1605: (typically every 2 years instead of every month which is too big
1606: for the memory).
1607: Model is determined by parameters x and covariates have to be
1608: included manually here.
1609:
1610: */
1611:
1612: int i, j, d, h, k;
1.131 brouard 1613: double **out, cov[NCOVMAX+1];
1.126 brouard 1614: double **newm;
1615:
1616: /* Hstepm could be zero and should return the unit matrix */
1617: for (i=1;i<=nlstate+ndeath;i++)
1618: for (j=1;j<=nlstate+ndeath;j++){
1619: oldm[i][j]=(i==j ? 1.0 : 0.0);
1620: po[i][j][0]=(i==j ? 1.0 : 0.0);
1621: }
1622: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1623: for(h=1; h <=nhstepm; h++){
1624: for(d=1; d <=hstepm; d++){
1625: newm=savm;
1626: /* Covariates have to be included here again */
1627: cov[1]=1.;
1628: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1629: for (k=1; k<=cptcovn;k++)
1630: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1631: for (k=1; k<=cptcovage;k++)
1632: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1633: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1634: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1635:
1636:
1637: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1638: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1639: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1640: pmij(pmmij,cov,ncovmodel,x,nlstate));
1641: savm=oldm;
1642: oldm=newm;
1643: }
1644: for(i=1; i<=nlstate+ndeath; i++)
1645: for(j=1;j<=nlstate+ndeath;j++) {
1646: po[i][j][h]=newm[i][j];
1.128 brouard 1647: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1648: }
1.128 brouard 1649: /*printf("h=%d ",h);*/
1.126 brouard 1650: } /* end h */
1.128 brouard 1651: /* printf("\n H=%d \n",h); */
1.126 brouard 1652: return po;
1653: }
1654:
1655:
1656: /*************** log-likelihood *************/
1657: double func( double *x)
1658: {
1659: int i, ii, j, k, mi, d, kk;
1.131 brouard 1660: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1661: double **out;
1662: double sw; /* Sum of weights */
1663: double lli; /* Individual log likelihood */
1664: int s1, s2;
1665: double bbh, survp;
1666: long ipmx;
1667: /*extern weight */
1668: /* We are differentiating ll according to initial status */
1669: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1670: /*for(i=1;i<imx;i++)
1671: printf(" %d\n",s[4][i]);
1672: */
1673: cov[1]=1.;
1674:
1675: for(k=1; k<=nlstate; k++) ll[k]=0.;
1676:
1677: if(mle==1){
1678: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1679: /* Computes the values of the ncovmodel covariates of the model
1680: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1681: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1682: to be observed in j being in i according to the model.
1683: */
1.145 brouard 1684: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1685: cov[2+k]=covar[Tvar[k]][i];
1686: }
1.137 brouard 1687: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1688: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1689: has been calculated etc */
1.126 brouard 1690: for(mi=1; mi<= wav[i]-1; mi++){
1691: for (ii=1;ii<=nlstate+ndeath;ii++)
1692: for (j=1;j<=nlstate+ndeath;j++){
1693: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1694: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1695: }
1696: for(d=0; d<dh[mi][i]; d++){
1697: newm=savm;
1698: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1699: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1700: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1701: }
1702: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1703: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1704: savm=oldm;
1705: oldm=newm;
1706: } /* end mult */
1707:
1708: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1709: /* But now since version 0.9 we anticipate for bias at large stepm.
1710: * If stepm is larger than one month (smallest stepm) and if the exact delay
1711: * (in months) between two waves is not a multiple of stepm, we rounded to
1712: * the nearest (and in case of equal distance, to the lowest) interval but now
1713: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1714: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1715: * probability in order to take into account the bias as a fraction of the way
1716: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1717: * -stepm/2 to stepm/2 .
1718: * For stepm=1 the results are the same as for previous versions of Imach.
1719: * For stepm > 1 the results are less biased than in previous versions.
1720: */
1721: s1=s[mw[mi][i]][i];
1722: s2=s[mw[mi+1][i]][i];
1723: bbh=(double)bh[mi][i]/(double)stepm;
1724: /* bias bh is positive if real duration
1725: * is higher than the multiple of stepm and negative otherwise.
1726: */
1727: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1728: if( s2 > nlstate){
1729: /* i.e. if s2 is a death state and if the date of death is known
1730: then the contribution to the likelihood is the probability to
1731: die between last step unit time and current step unit time,
1732: which is also equal to probability to die before dh
1733: minus probability to die before dh-stepm .
1734: In version up to 0.92 likelihood was computed
1735: as if date of death was unknown. Death was treated as any other
1736: health state: the date of the interview describes the actual state
1737: and not the date of a change in health state. The former idea was
1738: to consider that at each interview the state was recorded
1739: (healthy, disable or death) and IMaCh was corrected; but when we
1740: introduced the exact date of death then we should have modified
1741: the contribution of an exact death to the likelihood. This new
1742: contribution is smaller and very dependent of the step unit
1743: stepm. It is no more the probability to die between last interview
1744: and month of death but the probability to survive from last
1745: interview up to one month before death multiplied by the
1746: probability to die within a month. Thanks to Chris
1747: Jackson for correcting this bug. Former versions increased
1748: mortality artificially. The bad side is that we add another loop
1749: which slows down the processing. The difference can be up to 10%
1750: lower mortality.
1751: */
1752: lli=log(out[s1][s2] - savm[s1][s2]);
1753:
1754:
1755: } else if (s2==-2) {
1756: for (j=1,survp=0. ; j<=nlstate; j++)
1757: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1758: /*survp += out[s1][j]; */
1759: lli= log(survp);
1760: }
1761:
1762: else if (s2==-4) {
1763: for (j=3,survp=0. ; j<=nlstate; j++)
1764: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1765: lli= log(survp);
1766: }
1767:
1768: else if (s2==-5) {
1769: for (j=1,survp=0. ; j<=2; j++)
1770: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1771: lli= log(survp);
1772: }
1773:
1774: else{
1775: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1776: /* 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 */
1777: }
1778: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1779: /*if(lli ==000.0)*/
1780: /*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); */
1781: ipmx +=1;
1782: sw += weight[i];
1783: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1784: } /* end of wave */
1785: } /* end of individual */
1786: } else if(mle==2){
1787: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1788: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1789: for(mi=1; mi<= wav[i]-1; mi++){
1790: for (ii=1;ii<=nlstate+ndeath;ii++)
1791: for (j=1;j<=nlstate+ndeath;j++){
1792: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1793: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1794: }
1795: for(d=0; d<=dh[mi][i]; d++){
1796: newm=savm;
1797: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1798: for (kk=1; kk<=cptcovage;kk++) {
1799: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1800: }
1801: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1802: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1803: savm=oldm;
1804: oldm=newm;
1805: } /* end mult */
1806:
1807: s1=s[mw[mi][i]][i];
1808: s2=s[mw[mi+1][i]][i];
1809: bbh=(double)bh[mi][i]/(double)stepm;
1810: lli= (savm[s1][s2]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
1811: ipmx +=1;
1812: sw += weight[i];
1813: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1814: } /* end of wave */
1815: } /* end of individual */
1816: } else if(mle==3){ /* exponential inter-extrapolation */
1817: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1818: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1819: for(mi=1; mi<= wav[i]-1; mi++){
1820: for (ii=1;ii<=nlstate+ndeath;ii++)
1821: for (j=1;j<=nlstate+ndeath;j++){
1822: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1823: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1824: }
1825: for(d=0; d<dh[mi][i]; d++){
1826: newm=savm;
1827: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1828: for (kk=1; kk<=cptcovage;kk++) {
1829: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1830: }
1831: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1832: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1833: savm=oldm;
1834: oldm=newm;
1835: } /* end mult */
1836:
1837: s1=s[mw[mi][i]][i];
1838: s2=s[mw[mi+1][i]][i];
1839: bbh=(double)bh[mi][i]/(double)stepm;
1840: 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 */
1841: ipmx +=1;
1842: sw += weight[i];
1843: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1844: } /* end of wave */
1845: } /* end of individual */
1846: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1847: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1848: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1849: for(mi=1; mi<= wav[i]-1; mi++){
1850: for (ii=1;ii<=nlstate+ndeath;ii++)
1851: for (j=1;j<=nlstate+ndeath;j++){
1852: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1853: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1854: }
1855: for(d=0; d<dh[mi][i]; d++){
1856: newm=savm;
1857: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1858: for (kk=1; kk<=cptcovage;kk++) {
1859: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1860: }
1861:
1862: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1863: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1864: savm=oldm;
1865: oldm=newm;
1866: } /* end mult */
1867:
1868: s1=s[mw[mi][i]][i];
1869: s2=s[mw[mi+1][i]][i];
1870: if( s2 > nlstate){
1871: lli=log(out[s1][s2] - savm[s1][s2]);
1872: }else{
1873: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1874: }
1875: ipmx +=1;
1876: sw += weight[i];
1877: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1878: /* 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]); */
1879: } /* end of wave */
1880: } /* end of individual */
1881: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1882: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1883: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1884: for(mi=1; mi<= wav[i]-1; mi++){
1885: for (ii=1;ii<=nlstate+ndeath;ii++)
1886: for (j=1;j<=nlstate+ndeath;j++){
1887: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1888: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1889: }
1890: for(d=0; d<dh[mi][i]; d++){
1891: newm=savm;
1892: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1893: for (kk=1; kk<=cptcovage;kk++) {
1894: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1895: }
1896:
1897: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1898: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1899: savm=oldm;
1900: oldm=newm;
1901: } /* end mult */
1902:
1903: s1=s[mw[mi][i]][i];
1904: s2=s[mw[mi+1][i]][i];
1905: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1906: ipmx +=1;
1907: sw += weight[i];
1908: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1909: /*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]);*/
1910: } /* end of wave */
1911: } /* end of individual */
1912: } /* End of if */
1913: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1914: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1915: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1916: return -l;
1917: }
1918:
1919: /*************** log-likelihood *************/
1920: double funcone( double *x)
1921: {
1922: /* Same as likeli but slower because of a lot of printf and if */
1923: int i, ii, j, k, mi, d, kk;
1.131 brouard 1924: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1925: double **out;
1926: double lli; /* Individual log likelihood */
1927: double llt;
1928: int s1, s2;
1929: double bbh, survp;
1930: /*extern weight */
1931: /* We are differentiating ll according to initial status */
1932: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1933: /*for(i=1;i<imx;i++)
1934: printf(" %d\n",s[4][i]);
1935: */
1936: cov[1]=1.;
1937:
1938: for(k=1; k<=nlstate; k++) ll[k]=0.;
1939:
1940: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1941: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1942: for(mi=1; mi<= wav[i]-1; mi++){
1943: for (ii=1;ii<=nlstate+ndeath;ii++)
1944: for (j=1;j<=nlstate+ndeath;j++){
1945: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1946: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1947: }
1948: for(d=0; d<dh[mi][i]; d++){
1949: newm=savm;
1950: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1951: for (kk=1; kk<=cptcovage;kk++) {
1952: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1953: }
1.145 brouard 1954: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 1955: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1956: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 1957: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
1958: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 1959: savm=oldm;
1960: oldm=newm;
1961: } /* end mult */
1962:
1963: s1=s[mw[mi][i]][i];
1964: s2=s[mw[mi+1][i]][i];
1965: bbh=(double)bh[mi][i]/(double)stepm;
1966: /* bias is positive if real duration
1967: * is higher than the multiple of stepm and negative otherwise.
1968: */
1969: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1970: lli=log(out[s1][s2] - savm[s1][s2]);
1971: } else if (s2==-2) {
1972: for (j=1,survp=0. ; j<=nlstate; j++)
1973: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1974: lli= log(survp);
1975: }else if (mle==1){
1976: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1977: } else if(mle==2){
1978: 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 */
1979: } else if(mle==3){ /* exponential inter-extrapolation */
1980: 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 */
1981: } else if (mle==4){ /* mle=4 no inter-extrapolation */
1982: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 1983: } else{ /* mle=0 back to 1 */
1984: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1985: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 1986: } /* End of if */
1987: ipmx +=1;
1988: sw += weight[i];
1989: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 1990: /*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 1991: if(globpr){
1.141 brouard 1992: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 1993: %11.6f %11.6f %11.6f ", \
1994: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1995: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
1996: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
1997: llt +=ll[k]*gipmx/gsw;
1998: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1999: }
2000: fprintf(ficresilk," %10.6f\n", -llt);
2001: }
2002: } /* end of wave */
2003: } /* end of individual */
2004: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2005: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2006: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2007: if(globpr==0){ /* First time we count the contributions and weights */
2008: gipmx=ipmx;
2009: gsw=sw;
2010: }
2011: return -l;
2012: }
2013:
2014:
2015: /*************** function likelione ***********/
2016: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2017: {
2018: /* This routine should help understanding what is done with
2019: the selection of individuals/waves and
2020: to check the exact contribution to the likelihood.
2021: Plotting could be done.
2022: */
2023: int k;
2024:
2025: if(*globpri !=0){ /* Just counts and sums, no printings */
2026: strcpy(fileresilk,"ilk");
2027: strcat(fileresilk,fileres);
2028: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2029: printf("Problem with resultfile: %s\n", fileresilk);
2030: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2031: }
2032: 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");
2033: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2034: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2035: for(k=1; k<=nlstate; k++)
2036: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2037: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2038: }
2039:
2040: *fretone=(*funcone)(p);
2041: if(*globpri !=0){
2042: fclose(ficresilk);
2043: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2044: fflush(fichtm);
2045: }
2046: return;
2047: }
2048:
2049:
2050: /*********** Maximum Likelihood Estimation ***************/
2051:
2052: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2053: {
2054: int i,j, iter;
2055: double **xi;
2056: double fret;
2057: double fretone; /* Only one call to likelihood */
2058: /* char filerespow[FILENAMELENGTH];*/
2059: xi=matrix(1,npar,1,npar);
2060: for (i=1;i<=npar;i++)
2061: for (j=1;j<=npar;j++)
2062: xi[i][j]=(i==j ? 1.0 : 0.0);
2063: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2064: strcpy(filerespow,"pow");
2065: strcat(filerespow,fileres);
2066: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2067: printf("Problem with resultfile: %s\n", filerespow);
2068: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2069: }
2070: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2071: for (i=1;i<=nlstate;i++)
2072: for(j=1;j<=nlstate+ndeath;j++)
2073: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2074: fprintf(ficrespow,"\n");
2075:
2076: powell(p,xi,npar,ftol,&iter,&fret,func);
2077:
2078: free_matrix(xi,1,npar,1,npar);
2079: fclose(ficrespow);
2080: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
2081: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2082: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2083:
2084: }
2085:
2086: /**** Computes Hessian and covariance matrix ***/
2087: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2088: {
2089: double **a,**y,*x,pd;
2090: double **hess;
2091: int i, j,jk;
2092: int *indx;
2093:
2094: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2095: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2096: void lubksb(double **a, int npar, int *indx, double b[]) ;
2097: void ludcmp(double **a, int npar, int *indx, double *d) ;
2098: double gompertz(double p[]);
2099: hess=matrix(1,npar,1,npar);
2100:
2101: printf("\nCalculation of the hessian matrix. Wait...\n");
2102: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2103: for (i=1;i<=npar;i++){
2104: printf("%d",i);fflush(stdout);
2105: fprintf(ficlog,"%d",i);fflush(ficlog);
2106:
2107: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2108:
2109: /* printf(" %f ",p[i]);
2110: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2111: }
2112:
2113: for (i=1;i<=npar;i++) {
2114: for (j=1;j<=npar;j++) {
2115: if (j>i) {
2116: printf(".%d%d",i,j);fflush(stdout);
2117: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2118: hess[i][j]=hessij(p,delti,i,j,func,npar);
2119:
2120: hess[j][i]=hess[i][j];
2121: /*printf(" %lf ",hess[i][j]);*/
2122: }
2123: }
2124: }
2125: printf("\n");
2126: fprintf(ficlog,"\n");
2127:
2128: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2129: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2130:
2131: a=matrix(1,npar,1,npar);
2132: y=matrix(1,npar,1,npar);
2133: x=vector(1,npar);
2134: indx=ivector(1,npar);
2135: for (i=1;i<=npar;i++)
2136: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2137: ludcmp(a,npar,indx,&pd);
2138:
2139: for (j=1;j<=npar;j++) {
2140: for (i=1;i<=npar;i++) x[i]=0;
2141: x[j]=1;
2142: lubksb(a,npar,indx,x);
2143: for (i=1;i<=npar;i++){
2144: matcov[i][j]=x[i];
2145: }
2146: }
2147:
2148: printf("\n#Hessian matrix#\n");
2149: fprintf(ficlog,"\n#Hessian matrix#\n");
2150: for (i=1;i<=npar;i++) {
2151: for (j=1;j<=npar;j++) {
2152: printf("%.3e ",hess[i][j]);
2153: fprintf(ficlog,"%.3e ",hess[i][j]);
2154: }
2155: printf("\n");
2156: fprintf(ficlog,"\n");
2157: }
2158:
2159: /* Recompute Inverse */
2160: for (i=1;i<=npar;i++)
2161: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2162: ludcmp(a,npar,indx,&pd);
2163:
2164: /* printf("\n#Hessian matrix recomputed#\n");
2165:
2166: for (j=1;j<=npar;j++) {
2167: for (i=1;i<=npar;i++) x[i]=0;
2168: x[j]=1;
2169: lubksb(a,npar,indx,x);
2170: for (i=1;i<=npar;i++){
2171: y[i][j]=x[i];
2172: printf("%.3e ",y[i][j]);
2173: fprintf(ficlog,"%.3e ",y[i][j]);
2174: }
2175: printf("\n");
2176: fprintf(ficlog,"\n");
2177: }
2178: */
2179:
2180: free_matrix(a,1,npar,1,npar);
2181: free_matrix(y,1,npar,1,npar);
2182: free_vector(x,1,npar);
2183: free_ivector(indx,1,npar);
2184: free_matrix(hess,1,npar,1,npar);
2185:
2186:
2187: }
2188:
2189: /*************** hessian matrix ****************/
2190: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2191: {
2192: int i;
2193: int l=1, lmax=20;
2194: double k1,k2;
1.132 brouard 2195: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2196: double res;
2197: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2198: double fx;
2199: int k=0,kmax=10;
2200: double l1;
2201:
2202: fx=func(x);
2203: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2204: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2205: l1=pow(10,l);
2206: delts=delt;
2207: for(k=1 ; k <kmax; k=k+1){
2208: delt = delta*(l1*k);
2209: p2[theta]=x[theta] +delt;
1.145 brouard 2210: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2211: p2[theta]=x[theta]-delt;
2212: k2=func(p2)-fx;
2213: /*res= (k1-2.0*fx+k2)/delt/delt; */
2214: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2215:
1.132 brouard 2216: #ifdef DEBUGHESS
1.126 brouard 2217: 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);
2218: 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);
2219: #endif
2220: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2221: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2222: k=kmax;
2223: }
2224: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2225: k=kmax; l=lmax*10.;
2226: }
2227: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2228: delts=delt;
2229: }
2230: }
2231: }
2232: delti[theta]=delts;
2233: return res;
2234:
2235: }
2236:
2237: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2238: {
2239: int i;
2240: int l=1, l1, lmax=20;
2241: double k1,k2,k3,k4,res,fx;
1.132 brouard 2242: double p2[MAXPARM+1];
1.126 brouard 2243: int k;
2244:
2245: fx=func(x);
2246: for (k=1; k<=2; k++) {
2247: for (i=1;i<=npar;i++) p2[i]=x[i];
2248: p2[thetai]=x[thetai]+delti[thetai]/k;
2249: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2250: k1=func(p2)-fx;
2251:
2252: p2[thetai]=x[thetai]+delti[thetai]/k;
2253: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2254: k2=func(p2)-fx;
2255:
2256: p2[thetai]=x[thetai]-delti[thetai]/k;
2257: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2258: k3=func(p2)-fx;
2259:
2260: p2[thetai]=x[thetai]-delti[thetai]/k;
2261: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2262: k4=func(p2)-fx;
2263: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2264: #ifdef DEBUG
2265: 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);
2266: 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);
2267: #endif
2268: }
2269: return res;
2270: }
2271:
2272: /************** Inverse of matrix **************/
2273: void ludcmp(double **a, int n, int *indx, double *d)
2274: {
2275: int i,imax,j,k;
2276: double big,dum,sum,temp;
2277: double *vv;
2278:
2279: vv=vector(1,n);
2280: *d=1.0;
2281: for (i=1;i<=n;i++) {
2282: big=0.0;
2283: for (j=1;j<=n;j++)
2284: if ((temp=fabs(a[i][j])) > big) big=temp;
2285: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2286: vv[i]=1.0/big;
2287: }
2288: for (j=1;j<=n;j++) {
2289: for (i=1;i<j;i++) {
2290: sum=a[i][j];
2291: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2292: a[i][j]=sum;
2293: }
2294: big=0.0;
2295: for (i=j;i<=n;i++) {
2296: sum=a[i][j];
2297: for (k=1;k<j;k++)
2298: sum -= a[i][k]*a[k][j];
2299: a[i][j]=sum;
2300: if ( (dum=vv[i]*fabs(sum)) >= big) {
2301: big=dum;
2302: imax=i;
2303: }
2304: }
2305: if (j != imax) {
2306: for (k=1;k<=n;k++) {
2307: dum=a[imax][k];
2308: a[imax][k]=a[j][k];
2309: a[j][k]=dum;
2310: }
2311: *d = -(*d);
2312: vv[imax]=vv[j];
2313: }
2314: indx[j]=imax;
2315: if (a[j][j] == 0.0) a[j][j]=TINY;
2316: if (j != n) {
2317: dum=1.0/(a[j][j]);
2318: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2319: }
2320: }
2321: free_vector(vv,1,n); /* Doesn't work */
2322: ;
2323: }
2324:
2325: void lubksb(double **a, int n, int *indx, double b[])
2326: {
2327: int i,ii=0,ip,j;
2328: double sum;
2329:
2330: for (i=1;i<=n;i++) {
2331: ip=indx[i];
2332: sum=b[ip];
2333: b[ip]=b[i];
2334: if (ii)
2335: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2336: else if (sum) ii=i;
2337: b[i]=sum;
2338: }
2339: for (i=n;i>=1;i--) {
2340: sum=b[i];
2341: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2342: b[i]=sum/a[i][i];
2343: }
2344: }
2345:
2346: void pstamp(FILE *fichier)
2347: {
2348: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2349: }
2350:
2351: /************ Frequencies ********************/
2352: 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[])
2353: { /* Some frequencies */
2354:
1.130 brouard 2355: int i, m, jk, k1,i1, j1, bool, z1,j;
1.126 brouard 2356: int first;
2357: double ***freq; /* Frequencies */
2358: double *pp, **prop;
2359: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2360: char fileresp[FILENAMELENGTH];
2361:
2362: pp=vector(1,nlstate);
2363: prop=matrix(1,nlstate,iagemin,iagemax+3);
2364: strcpy(fileresp,"p");
2365: strcat(fileresp,fileres);
2366: if((ficresp=fopen(fileresp,"w"))==NULL) {
2367: printf("Problem with prevalence resultfile: %s\n", fileresp);
2368: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2369: exit(0);
2370: }
2371: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2372: j1=0;
2373:
2374: j=cptcoveff;
2375: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2376:
2377: first=1;
2378:
1.145 brouard 2379: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2380: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2381: /* j1++;
2382: */
2383: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2384: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2385: scanf("%d", i);*/
2386: for (i=-5; i<=nlstate+ndeath; i++)
2387: for (jk=-5; jk<=nlstate+ndeath; jk++)
2388: for(m=iagemin; m <= iagemax+3; m++)
2389: freq[i][jk][m]=0;
1.143 brouard 2390:
2391: for (i=1; i<=nlstate; i++)
2392: for(m=iagemin; m <= iagemax+3; m++)
2393: prop[i][m]=0;
1.126 brouard 2394:
2395: dateintsum=0;
2396: k2cpt=0;
2397: for (i=1; i<=imx; i++) {
2398: bool=1;
1.144 brouard 2399: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2400: for (z1=1; z1<=cptcoveff; z1++)
2401: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2402: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2403: bool=0;
1.145 brouard 2404: /* 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",
2405: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2406: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2407: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2408: }
1.126 brouard 2409: }
1.144 brouard 2410:
1.126 brouard 2411: if (bool==1){
2412: for(m=firstpass; m<=lastpass; m++){
2413: k2=anint[m][i]+(mint[m][i]/12.);
2414: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2415: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2416: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2417: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2418: if (m<lastpass) {
2419: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2420: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2421: }
2422:
2423: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2424: dateintsum=dateintsum+k2;
2425: k2cpt++;
2426: }
2427: /*}*/
2428: }
2429: }
1.145 brouard 2430: } /* end i */
1.126 brouard 2431:
2432: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2433: pstamp(ficresp);
2434: if (cptcovn>0) {
2435: fprintf(ficresp, "\n#********** Variable ");
2436: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2437: fprintf(ficresp, "**********\n#");
1.143 brouard 2438: fprintf(ficlog, "\n#********** Variable ");
2439: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2440: fprintf(ficlog, "**********\n#");
1.126 brouard 2441: }
2442: for(i=1; i<=nlstate;i++)
2443: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2444: fprintf(ficresp, "\n");
2445:
2446: for(i=iagemin; i <= iagemax+3; i++){
2447: if(i==iagemax+3){
2448: fprintf(ficlog,"Total");
2449: }else{
2450: if(first==1){
2451: first=0;
2452: printf("See log file for details...\n");
2453: }
2454: fprintf(ficlog,"Age %d", i);
2455: }
2456: for(jk=1; jk <=nlstate ; jk++){
2457: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2458: pp[jk] += freq[jk][m][i];
2459: }
2460: for(jk=1; jk <=nlstate ; jk++){
2461: for(m=-1, pos=0; m <=0 ; m++)
2462: pos += freq[jk][m][i];
2463: if(pp[jk]>=1.e-10){
2464: if(first==1){
1.132 brouard 2465: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2466: }
2467: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2468: }else{
2469: if(first==1)
2470: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2471: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2472: }
2473: }
2474:
2475: for(jk=1; jk <=nlstate ; jk++){
2476: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2477: pp[jk] += freq[jk][m][i];
2478: }
2479: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2480: pos += pp[jk];
2481: posprop += prop[jk][i];
2482: }
2483: for(jk=1; jk <=nlstate ; jk++){
2484: if(pos>=1.e-5){
2485: if(first==1)
2486: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2487: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2488: }else{
2489: if(first==1)
2490: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2491: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2492: }
2493: if( i <= iagemax){
2494: if(pos>=1.e-5){
2495: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2496: /*probs[i][jk][j1]= pp[jk]/pos;*/
2497: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2498: }
2499: else
2500: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2501: }
2502: }
2503:
2504: for(jk=-1; jk <=nlstate+ndeath; jk++)
2505: for(m=-1; m <=nlstate+ndeath; m++)
2506: if(freq[jk][m][i] !=0 ) {
2507: if(first==1)
2508: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2509: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2510: }
2511: if(i <= iagemax)
2512: fprintf(ficresp,"\n");
2513: if(first==1)
2514: printf("Others in log...\n");
2515: fprintf(ficlog,"\n");
2516: }
1.145 brouard 2517: /*}*/
1.126 brouard 2518: }
2519: dateintmean=dateintsum/k2cpt;
2520:
2521: fclose(ficresp);
2522: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2523: free_vector(pp,1,nlstate);
2524: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2525: /* End of Freq */
2526: }
2527:
2528: /************ Prevalence ********************/
2529: 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)
2530: {
2531: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2532: in each health status at the date of interview (if between dateprev1 and dateprev2).
2533: We still use firstpass and lastpass as another selection.
2534: */
2535:
1.130 brouard 2536: int i, m, jk, k1, i1, j1, bool, z1,j;
1.126 brouard 2537: double ***freq; /* Frequencies */
2538: double *pp, **prop;
2539: double pos,posprop;
2540: double y2; /* in fractional years */
2541: int iagemin, iagemax;
1.145 brouard 2542: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2543:
2544: iagemin= (int) agemin;
2545: iagemax= (int) agemax;
2546: /*pp=vector(1,nlstate);*/
2547: prop=matrix(1,nlstate,iagemin,iagemax+3);
2548: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2549: j1=0;
2550:
1.145 brouard 2551: /*j=cptcoveff;*/
1.126 brouard 2552: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2553:
1.145 brouard 2554: first=1;
2555: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2556: /*for(i1=1; i1<=ncodemax[k1];i1++){
2557: j1++;*/
1.126 brouard 2558:
2559: for (i=1; i<=nlstate; i++)
2560: for(m=iagemin; m <= iagemax+3; m++)
2561: prop[i][m]=0.0;
2562:
2563: for (i=1; i<=imx; i++) { /* Each individual */
2564: bool=1;
2565: if (cptcovn>0) {
2566: for (z1=1; z1<=cptcoveff; z1++)
2567: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2568: bool=0;
2569: }
2570: if (bool==1) {
2571: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2572: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2573: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2574: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2575: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2576: 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);
2577: if (s[m][i]>0 && s[m][i]<=nlstate) {
2578: /*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]]);*/
2579: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2580: prop[s[m][i]][iagemax+3] += weight[i];
2581: }
2582: }
2583: } /* end selection of waves */
2584: }
2585: }
2586: for(i=iagemin; i <= iagemax+3; i++){
2587: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2588: posprop += prop[jk][i];
2589: }
1.145 brouard 2590:
1.126 brouard 2591: for(jk=1; jk <=nlstate ; jk++){
2592: if( i <= iagemax){
2593: if(posprop>=1.e-5){
2594: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2595: } else{
2596: if(first==1){
2597: first=0;
2598: 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]);
2599: }
2600: }
1.126 brouard 2601: }
2602: }/* end jk */
2603: }/* end i */
1.145 brouard 2604: /*} *//* end i1 */
2605: } /* end j1 */
1.126 brouard 2606:
2607: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2608: /*free_vector(pp,1,nlstate);*/
2609: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2610: } /* End of prevalence */
2611:
2612: /************* Waves Concatenation ***************/
2613:
2614: 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)
2615: {
2616: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2617: Death is a valid wave (if date is known).
2618: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2619: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2620: and mw[mi+1][i]. dh depends on stepm.
2621: */
2622:
2623: int i, mi, m;
2624: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2625: double sum=0., jmean=0.;*/
2626: int first;
2627: int j, k=0,jk, ju, jl;
2628: double sum=0.;
2629: first=0;
2630: jmin=1e+5;
2631: jmax=-1;
2632: jmean=0.;
2633: for(i=1; i<=imx; i++){
2634: mi=0;
2635: m=firstpass;
2636: while(s[m][i] <= nlstate){
2637: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2638: mw[++mi][i]=m;
2639: if(m >=lastpass)
2640: break;
2641: else
2642: m++;
2643: }/* end while */
2644: if (s[m][i] > nlstate){
2645: mi++; /* Death is another wave */
2646: /* if(mi==0) never been interviewed correctly before death */
2647: /* Only death is a correct wave */
2648: mw[mi][i]=m;
2649: }
2650:
2651: wav[i]=mi;
2652: if(mi==0){
2653: nbwarn++;
2654: if(first==0){
2655: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2656: first=1;
2657: }
2658: if(first==1){
2659: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2660: }
2661: } /* end mi==0 */
2662: } /* End individuals */
2663:
2664: for(i=1; i<=imx; i++){
2665: for(mi=1; mi<wav[i];mi++){
2666: if (stepm <=0)
2667: dh[mi][i]=1;
2668: else{
2669: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2670: if (agedc[i] < 2*AGESUP) {
2671: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2672: if(j==0) j=1; /* Survives at least one month after exam */
2673: else if(j<0){
2674: nberr++;
2675: 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]);
2676: j=1; /* Temporary Dangerous patch */
2677: 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);
2678: 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]);
2679: 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);
2680: }
2681: k=k+1;
2682: if (j >= jmax){
2683: jmax=j;
2684: ijmax=i;
2685: }
2686: if (j <= jmin){
2687: jmin=j;
2688: ijmin=i;
2689: }
2690: sum=sum+j;
2691: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2692: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2693: }
2694: }
2695: else{
2696: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2697: /* 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]); */
2698:
2699: k=k+1;
2700: if (j >= jmax) {
2701: jmax=j;
2702: ijmax=i;
2703: }
2704: else if (j <= jmin){
2705: jmin=j;
2706: ijmin=i;
2707: }
2708: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2709: /*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]);*/
2710: if(j<0){
2711: nberr++;
2712: 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]);
2713: 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]);
2714: }
2715: sum=sum+j;
2716: }
2717: jk= j/stepm;
2718: jl= j -jk*stepm;
2719: ju= j -(jk+1)*stepm;
2720: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2721: if(jl==0){
2722: dh[mi][i]=jk;
2723: bh[mi][i]=0;
2724: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2725: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2726: dh[mi][i]=jk+1;
2727: bh[mi][i]=ju;
2728: }
2729: }else{
2730: if(jl <= -ju){
2731: dh[mi][i]=jk;
2732: bh[mi][i]=jl; /* bias is positive if real duration
2733: * is higher than the multiple of stepm and negative otherwise.
2734: */
2735: }
2736: else{
2737: dh[mi][i]=jk+1;
2738: bh[mi][i]=ju;
2739: }
2740: if(dh[mi][i]==0){
2741: dh[mi][i]=1; /* At least one step */
2742: bh[mi][i]=ju; /* At least one step */
2743: /* 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);*/
2744: }
2745: } /* end if mle */
2746: }
2747: } /* end wave */
2748: }
2749: jmean=sum/k;
2750: 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 2751: 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 2752: }
2753:
2754: /*********** Tricode ****************************/
1.145 brouard 2755: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2756: {
1.144 brouard 2757: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2758: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2759: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2760: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2761: /* nbcode[Tvar[j]][1]=
1.144 brouard 2762: */
1.130 brouard 2763:
1.145 brouard 2764: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2765: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2766: int cptcode=0; /* Modality max of covariates j */
2767: int modmincovj=0; /* Modality min of covariates j */
2768:
2769:
1.126 brouard 2770: cptcoveff=0;
2771:
1.145 brouard 2772: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2773: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2774:
1.145 brouard 2775: /* Loop on covariates without age and products */
2776: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2777: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2778: modality of this covariate Vj*/
1.145 brouard 2779: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2780: * If product of Vn*Vm, still boolean *:
2781: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2782: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2783: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2784: modality of the nth covariate of individual i. */
1.145 brouard 2785: if (ij > modmaxcovj)
2786: modmaxcovj=ij;
2787: else if (ij < modmincovj)
2788: modmincovj=ij;
2789: if ((ij < -1) && (ij > NCOVMAX)){
2790: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2791: exit(1);
2792: }else
1.136 brouard 2793: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2794: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2795: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2796: /* getting the maximum value of the modality of the covariate
2797: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2798: female is 1, then modmaxcovj=1.*/
1.126 brouard 2799: }
1.145 brouard 2800: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2801: cptcode=modmaxcovj;
1.137 brouard 2802: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2803: /*for (i=0; i<=cptcode; i++) {*/
2804: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2805: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2806: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2807: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2808: }
2809: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2810: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2811: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2812:
1.136 brouard 2813: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2814: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2815: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2816: modmincovj=3; modmaxcovj = 7;
2817: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2818: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2819: variables V1_1 and V1_2.
2820: nbcode[Tvar[j]][ij]=k;
2821: nbcode[Tvar[j]][1]=0;
2822: nbcode[Tvar[j]][2]=1;
2823: nbcode[Tvar[j]][3]=2;
2824: */
2825: ij=1; /* ij is similar to i but can jumps over null modalities */
2826: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2827: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2828: /*recode from 0 */
1.131 brouard 2829: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2830: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2831: k is a modality. If we have model=V1+V1*sex
2832: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2833: ij++;
2834: }
2835: if (ij > ncodemax[j]) break;
1.137 brouard 2836: } /* end of loop on */
2837: } /* end of loop on modality */
2838: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2839:
1.145 brouard 2840: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2841:
1.145 brouard 2842: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2843: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2844: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2845: Ndum[ij]++;
2846: }
1.126 brouard 2847:
2848: ij=1;
1.145 brouard 2849: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2850: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2851: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2852: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2853: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2854: ij++;
1.145 brouard 2855: }else
2856: Tvaraff[ij]=0;
1.126 brouard 2857: }
1.131 brouard 2858: ij--;
1.144 brouard 2859: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2860:
1.126 brouard 2861: }
2862:
1.145 brouard 2863:
1.126 brouard 2864: /*********** Health Expectancies ****************/
2865:
1.127 brouard 2866: 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 2867:
2868: {
2869: /* Health expectancies, no variances */
2870: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2871: int nhstepma, nstepma; /* Decreasing with age */
2872: double age, agelim, hf;
2873: double ***p3mat;
2874: double eip;
2875:
2876: pstamp(ficreseij);
2877: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2878: fprintf(ficreseij,"# Age");
2879: for(i=1; i<=nlstate;i++){
2880: for(j=1; j<=nlstate;j++){
2881: fprintf(ficreseij," e%1d%1d ",i,j);
2882: }
2883: fprintf(ficreseij," e%1d. ",i);
2884: }
2885: fprintf(ficreseij,"\n");
2886:
2887:
2888: if(estepm < stepm){
2889: printf ("Problem %d lower than %d\n",estepm, stepm);
2890: }
2891: else hstepm=estepm;
2892: /* We compute the life expectancy from trapezoids spaced every estepm months
2893: * This is mainly to measure the difference between two models: for example
2894: * if stepm=24 months pijx are given only every 2 years and by summing them
2895: * we are calculating an estimate of the Life Expectancy assuming a linear
2896: * progression in between and thus overestimating or underestimating according
2897: * to the curvature of the survival function. If, for the same date, we
2898: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2899: * to compare the new estimate of Life expectancy with the same linear
2900: * hypothesis. A more precise result, taking into account a more precise
2901: * curvature will be obtained if estepm is as small as stepm. */
2902:
2903: /* For example we decided to compute the life expectancy with the smallest unit */
2904: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2905: nhstepm is the number of hstepm from age to agelim
2906: nstepm is the number of stepm from age to agelin.
2907: Look at hpijx to understand the reason of that which relies in memory size
2908: and note for a fixed period like estepm months */
2909: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2910: survival function given by stepm (the optimization length). Unfortunately it
2911: means that if the survival funtion is printed only each two years of age and if
2912: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2913: results. So we changed our mind and took the option of the best precision.
2914: */
2915: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2916:
2917: agelim=AGESUP;
2918: /* If stepm=6 months */
2919: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2920: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2921:
2922: /* nhstepm age range expressed in number of stepm */
2923: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2924: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2925: /* if (stepm >= YEARM) hstepm=1;*/
2926: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2927: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2928:
2929: for (age=bage; age<=fage; age ++){
2930: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2931: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2932: /* if (stepm >= YEARM) hstepm=1;*/
2933: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2934:
2935: /* If stepm=6 months */
2936: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2937: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2938:
2939: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2940:
2941: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2942:
2943: printf("%d|",(int)age);fflush(stdout);
2944: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2945:
2946: /* Computing expectancies */
2947: for(i=1; i<=nlstate;i++)
2948: for(j=1; j<=nlstate;j++)
2949: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2950: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2951:
2952: /* 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]);*/
2953:
2954: }
2955:
2956: fprintf(ficreseij,"%3.0f",age );
2957: for(i=1; i<=nlstate;i++){
2958: eip=0;
2959: for(j=1; j<=nlstate;j++){
2960: eip +=eij[i][j][(int)age];
2961: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2962: }
2963: fprintf(ficreseij,"%9.4f", eip );
2964: }
2965: fprintf(ficreseij,"\n");
2966:
2967: }
2968: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2969: printf("\n");
2970: fprintf(ficlog,"\n");
2971:
2972: }
2973:
1.127 brouard 2974: 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 2975:
2976: {
2977: /* Covariances of health expectancies eij and of total life expectancies according
2978: to initial status i, ei. .
2979: */
2980: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
2981: int nhstepma, nstepma; /* Decreasing with age */
2982: double age, agelim, hf;
2983: double ***p3matp, ***p3matm, ***varhe;
2984: double **dnewm,**doldm;
2985: double *xp, *xm;
2986: double **gp, **gm;
2987: double ***gradg, ***trgradg;
2988: int theta;
2989:
2990: double eip, vip;
2991:
2992: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
2993: xp=vector(1,npar);
2994: xm=vector(1,npar);
2995: dnewm=matrix(1,nlstate*nlstate,1,npar);
2996: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
2997:
2998: pstamp(ficresstdeij);
2999: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3000: fprintf(ficresstdeij,"# Age");
3001: for(i=1; i<=nlstate;i++){
3002: for(j=1; j<=nlstate;j++)
3003: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3004: fprintf(ficresstdeij," e%1d. ",i);
3005: }
3006: fprintf(ficresstdeij,"\n");
3007:
3008: pstamp(ficrescveij);
3009: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3010: fprintf(ficrescveij,"# Age");
3011: for(i=1; i<=nlstate;i++)
3012: for(j=1; j<=nlstate;j++){
3013: cptj= (j-1)*nlstate+i;
3014: for(i2=1; i2<=nlstate;i2++)
3015: for(j2=1; j2<=nlstate;j2++){
3016: cptj2= (j2-1)*nlstate+i2;
3017: if(cptj2 <= cptj)
3018: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3019: }
3020: }
3021: fprintf(ficrescveij,"\n");
3022:
3023: if(estepm < stepm){
3024: printf ("Problem %d lower than %d\n",estepm, stepm);
3025: }
3026: else hstepm=estepm;
3027: /* We compute the life expectancy from trapezoids spaced every estepm months
3028: * This is mainly to measure the difference between two models: for example
3029: * if stepm=24 months pijx are given only every 2 years and by summing them
3030: * we are calculating an estimate of the Life Expectancy assuming a linear
3031: * progression in between and thus overestimating or underestimating according
3032: * to the curvature of the survival function. If, for the same date, we
3033: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3034: * to compare the new estimate of Life expectancy with the same linear
3035: * hypothesis. A more precise result, taking into account a more precise
3036: * curvature will be obtained if estepm is as small as stepm. */
3037:
3038: /* For example we decided to compute the life expectancy with the smallest unit */
3039: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3040: nhstepm is the number of hstepm from age to agelim
3041: nstepm is the number of stepm from age to agelin.
3042: Look at hpijx to understand the reason of that which relies in memory size
3043: and note for a fixed period like estepm months */
3044: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3045: survival function given by stepm (the optimization length). Unfortunately it
3046: means that if the survival funtion is printed only each two years of age and if
3047: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3048: results. So we changed our mind and took the option of the best precision.
3049: */
3050: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3051:
3052: /* If stepm=6 months */
3053: /* nhstepm age range expressed in number of stepm */
3054: agelim=AGESUP;
3055: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3056: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3057: /* if (stepm >= YEARM) hstepm=1;*/
3058: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3059:
3060: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3061: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3062: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3063: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3064: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3065: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3066:
3067: for (age=bage; age<=fage; age ++){
3068: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3069: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3070: /* if (stepm >= YEARM) hstepm=1;*/
3071: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3072:
3073: /* If stepm=6 months */
3074: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3075: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3076:
3077: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3078:
3079: /* Computing Variances of health expectancies */
3080: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3081: decrease memory allocation */
3082: for(theta=1; theta <=npar; theta++){
3083: for(i=1; i<=npar; i++){
3084: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3085: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3086: }
3087: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3088: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3089:
3090: for(j=1; j<= nlstate; j++){
3091: for(i=1; i<=nlstate; i++){
3092: for(h=0; h<=nhstepm-1; h++){
3093: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3094: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3095: }
3096: }
3097: }
3098:
3099: for(ij=1; ij<= nlstate*nlstate; ij++)
3100: for(h=0; h<=nhstepm-1; h++){
3101: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3102: }
3103: }/* End theta */
3104:
3105:
3106: for(h=0; h<=nhstepm-1; h++)
3107: for(j=1; j<=nlstate*nlstate;j++)
3108: for(theta=1; theta <=npar; theta++)
3109: trgradg[h][j][theta]=gradg[h][theta][j];
3110:
3111:
3112: for(ij=1;ij<=nlstate*nlstate;ij++)
3113: for(ji=1;ji<=nlstate*nlstate;ji++)
3114: varhe[ij][ji][(int)age] =0.;
3115:
3116: printf("%d|",(int)age);fflush(stdout);
3117: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3118: for(h=0;h<=nhstepm-1;h++){
3119: for(k=0;k<=nhstepm-1;k++){
3120: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3121: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3122: for(ij=1;ij<=nlstate*nlstate;ij++)
3123: for(ji=1;ji<=nlstate*nlstate;ji++)
3124: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3125: }
3126: }
3127:
3128: /* Computing expectancies */
3129: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3130: for(i=1; i<=nlstate;i++)
3131: for(j=1; j<=nlstate;j++)
3132: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3133: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3134:
3135: /* 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]);*/
3136:
3137: }
3138:
3139: fprintf(ficresstdeij,"%3.0f",age );
3140: for(i=1; i<=nlstate;i++){
3141: eip=0.;
3142: vip=0.;
3143: for(j=1; j<=nlstate;j++){
3144: eip += eij[i][j][(int)age];
3145: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3146: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3147: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3148: }
3149: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3150: }
3151: fprintf(ficresstdeij,"\n");
3152:
3153: fprintf(ficrescveij,"%3.0f",age );
3154: for(i=1; i<=nlstate;i++)
3155: for(j=1; j<=nlstate;j++){
3156: cptj= (j-1)*nlstate+i;
3157: for(i2=1; i2<=nlstate;i2++)
3158: for(j2=1; j2<=nlstate;j2++){
3159: cptj2= (j2-1)*nlstate+i2;
3160: if(cptj2 <= cptj)
3161: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3162: }
3163: }
3164: fprintf(ficrescveij,"\n");
3165:
3166: }
3167: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3168: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3169: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3170: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3171: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3172: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3173: printf("\n");
3174: fprintf(ficlog,"\n");
3175:
3176: free_vector(xm,1,npar);
3177: free_vector(xp,1,npar);
3178: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3179: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3180: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3181: }
3182:
3183: /************ Variance ******************/
3184: 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[])
3185: {
3186: /* Variance of health expectancies */
3187: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3188: /* double **newm;*/
3189: double **dnewm,**doldm;
3190: double **dnewmp,**doldmp;
3191: int i, j, nhstepm, hstepm, h, nstepm ;
3192: int k, cptcode;
3193: double *xp;
3194: double **gp, **gm; /* for var eij */
3195: double ***gradg, ***trgradg; /*for var eij */
3196: double **gradgp, **trgradgp; /* for var p point j */
3197: double *gpp, *gmp; /* for var p point j */
3198: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3199: double ***p3mat;
3200: double age,agelim, hf;
3201: double ***mobaverage;
3202: int theta;
3203: char digit[4];
3204: char digitp[25];
3205:
3206: char fileresprobmorprev[FILENAMELENGTH];
3207:
3208: if(popbased==1){
3209: if(mobilav!=0)
3210: strcpy(digitp,"-populbased-mobilav-");
3211: else strcpy(digitp,"-populbased-nomobil-");
3212: }
3213: else
3214: strcpy(digitp,"-stablbased-");
3215:
3216: if (mobilav!=0) {
3217: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3218: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3219: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3220: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3221: }
3222: }
3223:
3224: strcpy(fileresprobmorprev,"prmorprev");
3225: sprintf(digit,"%-d",ij);
3226: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3227: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3228: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3229: strcat(fileresprobmorprev,fileres);
3230: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3231: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3232: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3233: }
3234: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3235:
3236: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3237: pstamp(ficresprobmorprev);
3238: 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);
3239: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3240: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3241: fprintf(ficresprobmorprev," p.%-d SE",j);
3242: for(i=1; i<=nlstate;i++)
3243: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3244: }
3245: fprintf(ficresprobmorprev,"\n");
3246: fprintf(ficgp,"\n# Routine varevsij");
3247: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3248: 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");
3249: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3250: /* } */
3251: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3252: pstamp(ficresvij);
3253: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3254: if(popbased==1)
1.128 brouard 3255: 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 3256: else
3257: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3258: fprintf(ficresvij,"# Age");
3259: for(i=1; i<=nlstate;i++)
3260: for(j=1; j<=nlstate;j++)
3261: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3262: fprintf(ficresvij,"\n");
3263:
3264: xp=vector(1,npar);
3265: dnewm=matrix(1,nlstate,1,npar);
3266: doldm=matrix(1,nlstate,1,nlstate);
3267: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3268: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3269:
3270: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3271: gpp=vector(nlstate+1,nlstate+ndeath);
3272: gmp=vector(nlstate+1,nlstate+ndeath);
3273: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3274:
3275: if(estepm < stepm){
3276: printf ("Problem %d lower than %d\n",estepm, stepm);
3277: }
3278: else hstepm=estepm;
3279: /* For example we decided to compute the life expectancy with the smallest unit */
3280: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3281: nhstepm is the number of hstepm from age to agelim
3282: nstepm is the number of stepm from age to agelin.
1.128 brouard 3283: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3284: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3285: survival function given by stepm (the optimization length). Unfortunately it
3286: means that if the survival funtion is printed every two years of age and if
3287: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3288: results. So we changed our mind and took the option of the best precision.
3289: */
3290: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3291: agelim = AGESUP;
3292: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3293: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3294: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3295: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3296: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3297: gp=matrix(0,nhstepm,1,nlstate);
3298: gm=matrix(0,nhstepm,1,nlstate);
3299:
3300:
3301: for(theta=1; theta <=npar; theta++){
3302: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3303: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3304: }
3305: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3306: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3307:
3308: if (popbased==1) {
3309: if(mobilav ==0){
3310: for(i=1; i<=nlstate;i++)
3311: prlim[i][i]=probs[(int)age][i][ij];
3312: }else{ /* mobilav */
3313: for(i=1; i<=nlstate;i++)
3314: prlim[i][i]=mobaverage[(int)age][i][ij];
3315: }
3316: }
3317:
3318: for(j=1; j<= nlstate; j++){
3319: for(h=0; h<=nhstepm; h++){
3320: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3321: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3322: }
3323: }
3324: /* This for computing probability of death (h=1 means
3325: computed over hstepm matrices product = hstepm*stepm months)
3326: as a weighted average of prlim.
3327: */
3328: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3329: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3330: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3331: }
3332: /* end probability of death */
3333:
3334: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3335: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3336: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3337: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3338:
3339: if (popbased==1) {
3340: if(mobilav ==0){
3341: for(i=1; i<=nlstate;i++)
3342: prlim[i][i]=probs[(int)age][i][ij];
3343: }else{ /* mobilav */
3344: for(i=1; i<=nlstate;i++)
3345: prlim[i][i]=mobaverage[(int)age][i][ij];
3346: }
3347: }
3348:
1.128 brouard 3349: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3350: for(h=0; h<=nhstepm; h++){
3351: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3352: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3353: }
3354: }
3355: /* This for computing probability of death (h=1 means
3356: computed over hstepm matrices product = hstepm*stepm months)
3357: as a weighted average of prlim.
3358: */
3359: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3360: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3361: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3362: }
3363: /* end probability of death */
3364:
3365: for(j=1; j<= nlstate; j++) /* vareij */
3366: for(h=0; h<=nhstepm; h++){
3367: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3368: }
3369:
3370: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3371: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3372: }
3373:
3374: } /* End theta */
3375:
3376: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3377:
3378: for(h=0; h<=nhstepm; h++) /* veij */
3379: for(j=1; j<=nlstate;j++)
3380: for(theta=1; theta <=npar; theta++)
3381: trgradg[h][j][theta]=gradg[h][theta][j];
3382:
3383: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3384: for(theta=1; theta <=npar; theta++)
3385: trgradgp[j][theta]=gradgp[theta][j];
3386:
3387:
3388: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3389: for(i=1;i<=nlstate;i++)
3390: for(j=1;j<=nlstate;j++)
3391: vareij[i][j][(int)age] =0.;
3392:
3393: for(h=0;h<=nhstepm;h++){
3394: for(k=0;k<=nhstepm;k++){
3395: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3396: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3397: for(i=1;i<=nlstate;i++)
3398: for(j=1;j<=nlstate;j++)
3399: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3400: }
3401: }
3402:
3403: /* pptj */
3404: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3405: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3406: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3407: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3408: varppt[j][i]=doldmp[j][i];
3409: /* end ppptj */
3410: /* x centered again */
3411: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3412: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3413:
3414: if (popbased==1) {
3415: if(mobilav ==0){
3416: for(i=1; i<=nlstate;i++)
3417: prlim[i][i]=probs[(int)age][i][ij];
3418: }else{ /* mobilav */
3419: for(i=1; i<=nlstate;i++)
3420: prlim[i][i]=mobaverage[(int)age][i][ij];
3421: }
3422: }
3423:
3424: /* This for computing probability of death (h=1 means
3425: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3426: as a weighted average of prlim.
3427: */
3428: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3429: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3430: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3431: }
3432: /* end probability of death */
3433:
3434: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3435: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3436: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3437: for(i=1; i<=nlstate;i++){
3438: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3439: }
3440: }
3441: fprintf(ficresprobmorprev,"\n");
3442:
3443: fprintf(ficresvij,"%.0f ",age );
3444: for(i=1; i<=nlstate;i++)
3445: for(j=1; j<=nlstate;j++){
3446: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3447: }
3448: fprintf(ficresvij,"\n");
3449: free_matrix(gp,0,nhstepm,1,nlstate);
3450: free_matrix(gm,0,nhstepm,1,nlstate);
3451: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3452: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3453: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3454: } /* End age */
3455: free_vector(gpp,nlstate+1,nlstate+ndeath);
3456: free_vector(gmp,nlstate+1,nlstate+ndeath);
3457: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3458: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3459: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3460: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3461: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3462: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3463: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3464: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3465: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3466: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3467: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3468: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3469: 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);
3470: /* 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);
3471: */
3472: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3473: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3474:
3475: free_vector(xp,1,npar);
3476: free_matrix(doldm,1,nlstate,1,nlstate);
3477: free_matrix(dnewm,1,nlstate,1,npar);
3478: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3479: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3480: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3481: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3482: fclose(ficresprobmorprev);
3483: fflush(ficgp);
3484: fflush(fichtm);
3485: } /* end varevsij */
3486:
3487: /************ Variance of prevlim ******************/
3488: 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[])
3489: {
3490: /* Variance of prevalence limit */
3491: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3492: double **newm;
3493: double **dnewm,**doldm;
3494: int i, j, nhstepm, hstepm;
3495: int k, cptcode;
3496: double *xp;
3497: double *gp, *gm;
3498: double **gradg, **trgradg;
3499: double age,agelim;
3500: int theta;
3501:
3502: pstamp(ficresvpl);
3503: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3504: fprintf(ficresvpl,"# Age");
3505: for(i=1; i<=nlstate;i++)
3506: fprintf(ficresvpl," %1d-%1d",i,i);
3507: fprintf(ficresvpl,"\n");
3508:
3509: xp=vector(1,npar);
3510: dnewm=matrix(1,nlstate,1,npar);
3511: doldm=matrix(1,nlstate,1,nlstate);
3512:
3513: hstepm=1*YEARM; /* Every year of age */
3514: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3515: agelim = AGESUP;
3516: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3517: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3518: if (stepm >= YEARM) hstepm=1;
3519: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3520: gradg=matrix(1,npar,1,nlstate);
3521: gp=vector(1,nlstate);
3522: gm=vector(1,nlstate);
3523:
3524: for(theta=1; theta <=npar; theta++){
3525: for(i=1; i<=npar; i++){ /* Computes gradient */
3526: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3527: }
3528: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3529: for(i=1;i<=nlstate;i++)
3530: gp[i] = prlim[i][i];
3531:
3532: for(i=1; i<=npar; i++) /* Computes gradient */
3533: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3534: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3535: for(i=1;i<=nlstate;i++)
3536: gm[i] = prlim[i][i];
3537:
3538: for(i=1;i<=nlstate;i++)
3539: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3540: } /* End theta */
3541:
3542: trgradg =matrix(1,nlstate,1,npar);
3543:
3544: for(j=1; j<=nlstate;j++)
3545: for(theta=1; theta <=npar; theta++)
3546: trgradg[j][theta]=gradg[theta][j];
3547:
3548: for(i=1;i<=nlstate;i++)
3549: varpl[i][(int)age] =0.;
3550: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3551: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3552: for(i=1;i<=nlstate;i++)
3553: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3554:
3555: fprintf(ficresvpl,"%.0f ",age );
3556: for(i=1; i<=nlstate;i++)
3557: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3558: fprintf(ficresvpl,"\n");
3559: free_vector(gp,1,nlstate);
3560: free_vector(gm,1,nlstate);
3561: free_matrix(gradg,1,npar,1,nlstate);
3562: free_matrix(trgradg,1,nlstate,1,npar);
3563: } /* End age */
3564:
3565: free_vector(xp,1,npar);
3566: free_matrix(doldm,1,nlstate,1,npar);
3567: free_matrix(dnewm,1,nlstate,1,nlstate);
3568:
3569: }
3570:
3571: /************ Variance of one-step probabilities ******************/
3572: 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[])
3573: {
3574: int i, j=0, i1, k1, l1, t, tj;
3575: int k2, l2, j1, z1;
3576: int k=0,l, cptcode;
1.145 brouard 3577: int first=1, first1, first2;
1.126 brouard 3578: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3579: double **dnewm,**doldm;
3580: double *xp;
3581: double *gp, *gm;
3582: double **gradg, **trgradg;
3583: double **mu;
1.145 brouard 3584: double age,agelim, cov[NCOVMAX+1];
1.126 brouard 3585: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3586: int theta;
3587: char fileresprob[FILENAMELENGTH];
3588: char fileresprobcov[FILENAMELENGTH];
3589: char fileresprobcor[FILENAMELENGTH];
3590: double ***varpij;
3591:
3592: strcpy(fileresprob,"prob");
3593: strcat(fileresprob,fileres);
3594: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3595: printf("Problem with resultfile: %s\n", fileresprob);
3596: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3597: }
3598: strcpy(fileresprobcov,"probcov");
3599: strcat(fileresprobcov,fileres);
3600: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3601: printf("Problem with resultfile: %s\n", fileresprobcov);
3602: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3603: }
3604: strcpy(fileresprobcor,"probcor");
3605: strcat(fileresprobcor,fileres);
3606: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3607: printf("Problem with resultfile: %s\n", fileresprobcor);
3608: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3609: }
3610: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3611: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3612: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3613: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3614: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3615: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3616: pstamp(ficresprob);
3617: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3618: fprintf(ficresprob,"# Age");
3619: pstamp(ficresprobcov);
3620: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3621: fprintf(ficresprobcov,"# Age");
3622: pstamp(ficresprobcor);
3623: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3624: fprintf(ficresprobcor,"# Age");
3625:
3626:
3627: for(i=1; i<=nlstate;i++)
3628: for(j=1; j<=(nlstate+ndeath);j++){
3629: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3630: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3631: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3632: }
3633: /* fprintf(ficresprob,"\n");
3634: fprintf(ficresprobcov,"\n");
3635: fprintf(ficresprobcor,"\n");
3636: */
1.131 brouard 3637: xp=vector(1,npar);
1.126 brouard 3638: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3639: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3640: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3641: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3642: first=1;
3643: fprintf(ficgp,"\n# Routine varprob");
3644: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3645: fprintf(fichtm,"\n");
3646:
3647: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3648: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3649: file %s<br>\n",optionfilehtmcov);
3650: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3651: and drawn. It helps understanding how is the covariance between two incidences.\
3652: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3653: 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. \
3654: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3655: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3656: standard deviations wide on each axis. <br>\
3657: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3658: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3659: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3660:
3661: cov[1]=1;
1.145 brouard 3662: /* tj=cptcoveff; */
3663: tj = (int) pow(2,cptcoveff);
1.126 brouard 3664: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3665: j1=0;
1.145 brouard 3666: for(j1=1; j1<=tj;j1++){
3667: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3668: /*j1++;*/
1.126 brouard 3669: if (cptcovn>0) {
3670: fprintf(ficresprob, "\n#********** Variable ");
3671: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3672: fprintf(ficresprob, "**********\n#\n");
3673: fprintf(ficresprobcov, "\n#********** Variable ");
3674: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3675: fprintf(ficresprobcov, "**********\n#\n");
3676:
3677: fprintf(ficgp, "\n#********** Variable ");
3678: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3679: fprintf(ficgp, "**********\n#\n");
3680:
3681:
3682: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3683: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3684: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3685:
3686: fprintf(ficresprobcor, "\n#********** Variable ");
3687: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3688: fprintf(ficresprobcor, "**********\n#");
3689: }
3690:
1.145 brouard 3691: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3692: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3693: gp=vector(1,(nlstate)*(nlstate+ndeath));
3694: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3695: for (age=bage; age<=fage; age ++){
3696: cov[2]=age;
3697: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3698: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3699: * 1 1 1 1 1
3700: * 2 2 1 1 1
3701: * 3 1 2 1 1
3702: */
3703: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3704: }
3705: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3706: for (k=1; k<=cptcovprod;k++)
3707: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3708:
3709:
3710: for(theta=1; theta <=npar; theta++){
3711: for(i=1; i<=npar; i++)
3712: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3713:
3714: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3715:
3716: k=0;
3717: for(i=1; i<= (nlstate); i++){
3718: for(j=1; j<=(nlstate+ndeath);j++){
3719: k=k+1;
3720: gp[k]=pmmij[i][j];
3721: }
3722: }
3723:
3724: for(i=1; i<=npar; i++)
3725: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3726:
3727: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3728: k=0;
3729: for(i=1; i<=(nlstate); i++){
3730: for(j=1; j<=(nlstate+ndeath);j++){
3731: k=k+1;
3732: gm[k]=pmmij[i][j];
3733: }
3734: }
3735:
3736: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3737: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3738: }
3739:
3740: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3741: for(theta=1; theta <=npar; theta++)
3742: trgradg[j][theta]=gradg[theta][j];
3743:
3744: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3745: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3746:
3747: pmij(pmmij,cov,ncovmodel,x,nlstate);
3748:
3749: k=0;
3750: for(i=1; i<=(nlstate); i++){
3751: for(j=1; j<=(nlstate+ndeath);j++){
3752: k=k+1;
3753: mu[k][(int) age]=pmmij[i][j];
3754: }
3755: }
3756: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3757: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3758: varpij[i][j][(int)age] = doldm[i][j];
3759:
3760: /*printf("\n%d ",(int)age);
3761: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3762: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3763: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3764: }*/
3765:
3766: fprintf(ficresprob,"\n%d ",(int)age);
3767: fprintf(ficresprobcov,"\n%d ",(int)age);
3768: fprintf(ficresprobcor,"\n%d ",(int)age);
3769:
3770: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3771: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3772: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3773: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3774: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3775: }
3776: i=0;
3777: for (k=1; k<=(nlstate);k++){
3778: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3779: i++;
1.126 brouard 3780: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3781: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3782: for (j=1; j<=i;j++){
1.145 brouard 3783: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3784: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3785: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3786: }
3787: }
3788: }/* end of loop for state */
3789: } /* end of loop for age */
1.145 brouard 3790: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3791: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3792: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3793: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3794:
1.126 brouard 3795: /* Confidence intervalle of pij */
3796: /*
1.131 brouard 3797: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3798: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3799: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3800: 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);
3801: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3802: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3803: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3804: */
3805:
3806: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3807: first1=1;first2=2;
1.126 brouard 3808: for (k2=1; k2<=(nlstate);k2++){
3809: for (l2=1; l2<=(nlstate+ndeath);l2++){
3810: if(l2==k2) continue;
3811: j=(k2-1)*(nlstate+ndeath)+l2;
3812: for (k1=1; k1<=(nlstate);k1++){
3813: for (l1=1; l1<=(nlstate+ndeath);l1++){
3814: if(l1==k1) continue;
3815: i=(k1-1)*(nlstate+ndeath)+l1;
3816: if(i<=j) continue;
3817: for (age=bage; age<=fage; age ++){
3818: if ((int)age %5==0){
3819: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3820: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3821: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3822: mu1=mu[i][(int) age]/stepm*YEARM ;
3823: mu2=mu[j][(int) age]/stepm*YEARM;
3824: c12=cv12/sqrt(v1*v2);
3825: /* Computing eigen value of matrix of covariance */
3826: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3827: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3828: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3829: if(first2==1){
3830: first1=0;
3831: 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);
3832: }
3833: 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);
3834: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3835: /* lc2=fabs(lc2); */
1.135 brouard 3836: }
3837:
1.126 brouard 3838: /* Eigen vectors */
3839: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3840: /*v21=sqrt(1.-v11*v11); *//* error */
3841: v21=(lc1-v1)/cv12*v11;
3842: v12=-v21;
3843: v22=v11;
3844: tnalp=v21/v11;
3845: if(first1==1){
3846: first1=0;
3847: 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);
3848: }
3849: 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);
3850: /*printf(fignu*/
3851: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3852: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3853: if(first==1){
3854: first=0;
3855: fprintf(ficgp,"\nset parametric;unset label");
3856: 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 3857: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3858: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3859: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3860: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3861: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3862: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3863: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3864: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3865: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3866: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3867: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3868: 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",\
3869: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3870: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3871: }else{
3872: first=0;
3873: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3874: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3875: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3876: 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",\
3877: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3878: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3879: }/* if first */
3880: } /* age mod 5 */
3881: } /* end loop age */
3882: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3883: first=1;
3884: } /*l12 */
3885: } /* k12 */
3886: } /*l1 */
3887: }/* k1 */
1.145 brouard 3888: /* } /* loop covariates */
1.126 brouard 3889: }
3890: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3891: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3892: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3893: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3894: free_vector(xp,1,npar);
3895: fclose(ficresprob);
3896: fclose(ficresprobcov);
3897: fclose(ficresprobcor);
3898: fflush(ficgp);
3899: fflush(fichtmcov);
3900: }
3901:
3902:
3903: /******************* Printing html file ***********/
3904: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3905: int lastpass, int stepm, int weightopt, char model[],\
3906: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3907: int popforecast, int estepm ,\
3908: double jprev1, double mprev1,double anprev1, \
3909: double jprev2, double mprev2,double anprev2){
3910: int jj1, k1, i1, cpt;
3911:
3912: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3913: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3914: </ul>");
3915: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3916: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3917: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3918: fprintf(fichtm,"\
3919: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3920: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3921: fprintf(fichtm,"\
3922: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3923: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3924: fprintf(fichtm,"\
1.128 brouard 3925: - (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 3926: <a href=\"%s\">%s</a> <br>\n",
3927: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3928: fprintf(fichtm,"\
3929: - Population projections by age and states: \
3930: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3931:
3932: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3933:
1.145 brouard 3934: m=pow(2,cptcoveff);
1.126 brouard 3935: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3936:
3937: jj1=0;
3938: for(k1=1; k1<=m;k1++){
3939: for(i1=1; i1<=ncodemax[k1];i1++){
3940: jj1++;
3941: if (cptcovn > 0) {
3942: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3943: for (cpt=1; cpt<=cptcoveff;cpt++)
3944: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3945: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3946: }
3947: /* Pij */
1.145 brouard 3948: 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> \
3949: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3950: /* Quasi-incidences */
3951: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 3952: 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> \
3953: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3954: /* Period (stable) prevalence in each health state */
1.154 brouard 3955: for(cpt=1; cpt<=nlstate;cpt++){
3956: 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> \
3957: <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 3958: }
3959: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 3960: 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> \
3961: <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 3962: }
3963: } /* end i1 */
3964: }/* End k1 */
3965: fprintf(fichtm,"</ul>");
3966:
3967:
3968: fprintf(fichtm,"\
3969: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3970: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3971:
3972: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3973: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3974: fprintf(fichtm,"\
3975: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3976: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
3977:
3978: fprintf(fichtm,"\
3979: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3980: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
3981: fprintf(fichtm,"\
3982: - 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): \
3983: <a href=\"%s\">%s</a> <br>\n</li>",
3984: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
3985: fprintf(fichtm,"\
3986: - (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): \
3987: <a href=\"%s\">%s</a> <br>\n</li>",
3988: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
3989: fprintf(fichtm,"\
1.128 brouard 3990: - 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 3991: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
3992: fprintf(fichtm,"\
1.128 brouard 3993: - 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",
3994: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 3995: fprintf(fichtm,"\
3996: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
3997: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
3998:
3999: /* if(popforecast==1) fprintf(fichtm,"\n */
4000: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4001: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4002: /* <br>",fileres,fileres,fileres,fileres); */
4003: /* else */
4004: /* 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); */
4005: fflush(fichtm);
4006: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4007:
1.145 brouard 4008: m=pow(2,cptcoveff);
1.126 brouard 4009: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4010:
4011: jj1=0;
4012: for(k1=1; k1<=m;k1++){
4013: for(i1=1; i1<=ncodemax[k1];i1++){
4014: jj1++;
4015: if (cptcovn > 0) {
4016: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4017: for (cpt=1; cpt<=cptcoveff;cpt++)
4018: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4019: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4020: }
4021: for(cpt=1; cpt<=nlstate;cpt++) {
4022: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4023: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4024: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4025: }
4026: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4027: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4028: true period expectancies (those weighted with period prevalences are also\
4029: drawn in addition to the population based expectancies computed using\
4030: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4031: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4032: } /* end i1 */
4033: }/* End k1 */
4034: fprintf(fichtm,"</ul>");
4035: fflush(fichtm);
4036: }
4037:
4038: /******************* Gnuplot file **************/
4039: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4040:
4041: char dirfileres[132],optfileres[132];
1.130 brouard 4042: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4043: int ng=0;
1.126 brouard 4044: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4045: /* printf("Problem with file %s",optionfilegnuplot); */
4046: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4047: /* } */
4048:
4049: /*#ifdef windows */
4050: fprintf(ficgp,"cd \"%s\" \n",pathc);
4051: /*#endif */
4052: m=pow(2,cptcoveff);
4053:
4054: strcpy(dirfileres,optionfilefiname);
4055: strcpy(optfileres,"vpl");
4056: /* 1eme*/
1.153 brouard 4057: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4058: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4059: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4060: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4061: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4062: fprintf(ficgp,"set xlabel \"Age\" \n\
4063: set ylabel \"Probability\" \n\
1.145 brouard 4064: set ter png small size 320, 240\n\
1.126 brouard 4065: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4066:
4067: for (i=1; i<= nlstate ; i ++) {
4068: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4069: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4070: }
1.145 brouard 4071: 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 4072: for (i=1; i<= nlstate ; i ++) {
4073: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4074: else fprintf(ficgp," \%%*lf (\%%*lf)");
4075: }
1.145 brouard 4076: 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 4077: for (i=1; i<= nlstate ; i ++) {
4078: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4079: else fprintf(ficgp," \%%*lf (\%%*lf)");
4080: }
1.145 brouard 4081: 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 4082: }
4083: }
4084: /*2 eme*/
1.153 brouard 4085: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4086: for (k1=1; k1<= m ; k1 ++) {
4087: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4088: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4089:
4090: for (i=1; i<= nlstate+1 ; i ++) {
4091: k=2*i;
4092: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4093: for (j=1; j<= nlstate+1 ; j ++) {
4094: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4095: else fprintf(ficgp," \%%*lf (\%%*lf)");
4096: }
4097: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4098: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4099: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4100: for (j=1; j<= nlstate+1 ; j ++) {
4101: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4102: else fprintf(ficgp," \%%*lf (\%%*lf)");
4103: }
1.145 brouard 4104: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4105: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4106: for (j=1; j<= nlstate+1 ; j ++) {
4107: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4108: else fprintf(ficgp," \%%*lf (\%%*lf)");
4109: }
1.145 brouard 4110: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4111: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4112: }
4113: }
4114:
4115: /*3eme*/
4116:
4117: for (k1=1; k1<= m ; k1 ++) {
4118: for (cpt=1; cpt<= nlstate ; cpt ++) {
4119: /* k=2+nlstate*(2*cpt-2); */
4120: k=2+(nlstate+1)*(cpt-1);
4121: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4122: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4123: 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);
4124: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4125: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4126: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4127: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4128: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4129: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4130:
4131: */
4132: for (i=1; i< nlstate ; i ++) {
4133: 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);
4134: /* 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);*/
4135:
4136: }
4137: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4138: }
4139: }
4140:
4141: /* CV preval stable (period) */
1.153 brouard 4142: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4143: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4144: k=3;
1.153 brouard 4145: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4146: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4147: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4148: set ter png small size 320, 240\n\
1.126 brouard 4149: unset log y\n\
1.153 brouard 4150: plot [%.f:%.f] ", ageminpar, agemaxpar);
4151: for (i=1; i<= nlstate ; i ++){
4152: if(i==1)
4153: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4154: else
4155: fprintf(ficgp,", '' ");
1.154 brouard 4156: l=(nlstate+ndeath)*(i-1)+1;
4157: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4158: for (j=1; j<= (nlstate-1) ; j ++)
4159: fprintf(ficgp,"+$%d",k+l+j);
4160: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4161: } /* nlstate */
4162: fprintf(ficgp,"\n");
4163: } /* end cpt state*/
4164: } /* end covariate */
1.126 brouard 4165:
4166: /* proba elementaires */
4167: for(i=1,jk=1; i <=nlstate; i++){
4168: for(k=1; k <=(nlstate+ndeath); k++){
4169: if (k != i) {
4170: for(j=1; j <=ncovmodel; j++){
4171: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4172: jk++;
4173: fprintf(ficgp,"\n");
4174: }
4175: }
4176: }
4177: }
1.145 brouard 4178: /*goto avoid;*/
1.126 brouard 4179: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4180: for(jk=1; jk <=m; jk++) {
1.145 brouard 4181: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4182: if (ng==2)
4183: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4184: else
4185: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4186: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4187: i=1;
4188: for(k2=1; k2<=nlstate; k2++) {
4189: k3=i;
4190: for(k=1; k<=(nlstate+ndeath); k++) {
4191: if (k != k2){
4192: if(ng==2)
4193: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4194: else
4195: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4196: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4197: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4198: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4199: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4200: /* ij++; */
4201: /* } */
4202: /* else */
1.126 brouard 4203: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4204: }
4205: fprintf(ficgp,")/(1");
4206:
4207: for(k1=1; k1 <=nlstate; k1++){
4208: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4209: ij=1;
4210: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4211: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4212: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4213: /* ij++; */
4214: /* } */
4215: /* else */
1.126 brouard 4216: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4217: }
4218: fprintf(ficgp,")");
4219: }
4220: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4221: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4222: i=i+ncovmodel;
4223: }
4224: } /* end k */
4225: } /* end k2 */
4226: } /* end jk */
4227: } /* end ng */
1.145 brouard 4228: avoid:
1.126 brouard 4229: fflush(ficgp);
4230: } /* end gnuplot */
4231:
4232:
4233: /*************** Moving average **************/
4234: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4235:
4236: int i, cpt, cptcod;
4237: int modcovmax =1;
4238: int mobilavrange, mob;
4239: double age;
4240:
4241: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4242: a covariate has 2 modalities */
4243: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4244:
4245: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4246: if(mobilav==1) mobilavrange=5; /* default */
4247: else mobilavrange=mobilav;
4248: for (age=bage; age<=fage; age++)
4249: for (i=1; i<=nlstate;i++)
4250: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4251: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4252: /* We keep the original values on the extreme ages bage, fage and for
4253: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4254: we use a 5 terms etc. until the borders are no more concerned.
4255: */
4256: for (mob=3;mob <=mobilavrange;mob=mob+2){
4257: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4258: for (i=1; i<=nlstate;i++){
4259: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4260: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4261: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4262: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4263: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4264: }
4265: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4266: }
4267: }
4268: }/* end age */
4269: }/* end mob */
4270: }else return -1;
4271: return 0;
4272: }/* End movingaverage */
4273:
4274:
4275: /************** Forecasting ******************/
4276: 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){
4277: /* proj1, year, month, day of starting projection
4278: agemin, agemax range of age
4279: dateprev1 dateprev2 range of dates during which prevalence is computed
4280: anproj2 year of en of projection (same day and month as proj1).
4281: */
4282: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4283: int *popage;
4284: double agec; /* generic age */
4285: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4286: double *popeffectif,*popcount;
4287: double ***p3mat;
4288: double ***mobaverage;
4289: char fileresf[FILENAMELENGTH];
4290:
4291: agelim=AGESUP;
4292: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4293:
4294: strcpy(fileresf,"f");
4295: strcat(fileresf,fileres);
4296: if((ficresf=fopen(fileresf,"w"))==NULL) {
4297: printf("Problem with forecast resultfile: %s\n", fileresf);
4298: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4299: }
4300: printf("Computing forecasting: result on file '%s' \n", fileresf);
4301: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4302:
4303: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4304:
4305: if (mobilav!=0) {
4306: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4307: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4308: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4309: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4310: }
4311: }
4312:
4313: stepsize=(int) (stepm+YEARM-1)/YEARM;
4314: if (stepm<=12) stepsize=1;
4315: if(estepm < stepm){
4316: printf ("Problem %d lower than %d\n",estepm, stepm);
4317: }
4318: else hstepm=estepm;
4319:
4320: hstepm=hstepm/stepm;
4321: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4322: fractional in yp1 */
4323: anprojmean=yp;
4324: yp2=modf((yp1*12),&yp);
4325: mprojmean=yp;
4326: yp1=modf((yp2*30.5),&yp);
4327: jprojmean=yp;
4328: if(jprojmean==0) jprojmean=1;
4329: if(mprojmean==0) jprojmean=1;
4330:
4331: i1=cptcoveff;
4332: if (cptcovn < 1){i1=1;}
4333:
4334: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4335:
4336: fprintf(ficresf,"#****** Routine prevforecast **\n");
4337:
4338: /* if (h==(int)(YEARM*yearp)){ */
4339: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4340: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4341: k=k+1;
4342: fprintf(ficresf,"\n#******");
4343: for(j=1;j<=cptcoveff;j++) {
4344: 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]]);
4345: }
4346: fprintf(ficresf,"******\n");
4347: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4348: for(j=1; j<=nlstate+ndeath;j++){
4349: for(i=1; i<=nlstate;i++)
4350: fprintf(ficresf," p%d%d",i,j);
4351: fprintf(ficresf," p.%d",j);
4352: }
4353: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4354: fprintf(ficresf,"\n");
4355: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4356:
4357: for (agec=fage; agec>=(ageminpar-1); agec--){
4358: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4359: nhstepm = nhstepm/hstepm;
4360: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4361: oldm=oldms;savm=savms;
4362: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4363:
4364: for (h=0; h<=nhstepm; h++){
4365: if (h*hstepm/YEARM*stepm ==yearp) {
4366: fprintf(ficresf,"\n");
4367: for(j=1;j<=cptcoveff;j++)
4368: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4369: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4370: }
4371: for(j=1; j<=nlstate+ndeath;j++) {
4372: ppij=0.;
4373: for(i=1; i<=nlstate;i++) {
4374: if (mobilav==1)
4375: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4376: else {
4377: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4378: }
4379: if (h*hstepm/YEARM*stepm== yearp) {
4380: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4381: }
4382: } /* end i */
4383: if (h*hstepm/YEARM*stepm==yearp) {
4384: fprintf(ficresf," %.3f", ppij);
4385: }
4386: }/* end j */
4387: } /* end h */
4388: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4389: } /* end agec */
4390: } /* end yearp */
4391: } /* end cptcod */
4392: } /* end cptcov */
4393:
4394: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4395:
4396: fclose(ficresf);
4397: }
4398:
4399: /************** Forecasting *****not tested NB*************/
4400: 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){
4401:
4402: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4403: int *popage;
4404: double calagedatem, agelim, kk1, kk2;
4405: double *popeffectif,*popcount;
4406: double ***p3mat,***tabpop,***tabpopprev;
4407: double ***mobaverage;
4408: char filerespop[FILENAMELENGTH];
4409:
4410: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4411: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4412: agelim=AGESUP;
4413: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4414:
4415: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4416:
4417:
4418: strcpy(filerespop,"pop");
4419: strcat(filerespop,fileres);
4420: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4421: printf("Problem with forecast resultfile: %s\n", filerespop);
4422: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4423: }
4424: printf("Computing forecasting: result on file '%s' \n", filerespop);
4425: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4426:
4427: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4428:
4429: if (mobilav!=0) {
4430: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4431: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4432: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4433: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4434: }
4435: }
4436:
4437: stepsize=(int) (stepm+YEARM-1)/YEARM;
4438: if (stepm<=12) stepsize=1;
4439:
4440: agelim=AGESUP;
4441:
4442: hstepm=1;
4443: hstepm=hstepm/stepm;
4444:
4445: if (popforecast==1) {
4446: if((ficpop=fopen(popfile,"r"))==NULL) {
4447: printf("Problem with population file : %s\n",popfile);exit(0);
4448: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4449: }
4450: popage=ivector(0,AGESUP);
4451: popeffectif=vector(0,AGESUP);
4452: popcount=vector(0,AGESUP);
4453:
4454: i=1;
4455: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4456:
4457: imx=i;
4458: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4459: }
4460:
4461: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4462: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4463: k=k+1;
4464: fprintf(ficrespop,"\n#******");
4465: for(j=1;j<=cptcoveff;j++) {
4466: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4467: }
4468: fprintf(ficrespop,"******\n");
4469: fprintf(ficrespop,"# Age");
4470: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4471: if (popforecast==1) fprintf(ficrespop," [Population]");
4472:
4473: for (cpt=0; cpt<=0;cpt++) {
4474: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4475:
4476: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4477: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4478: nhstepm = nhstepm/hstepm;
4479:
4480: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4481: oldm=oldms;savm=savms;
4482: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4483:
4484: for (h=0; h<=nhstepm; h++){
4485: if (h==(int) (calagedatem+YEARM*cpt)) {
4486: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4487: }
4488: for(j=1; j<=nlstate+ndeath;j++) {
4489: kk1=0.;kk2=0;
4490: for(i=1; i<=nlstate;i++) {
4491: if (mobilav==1)
4492: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4493: else {
4494: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4495: }
4496: }
4497: if (h==(int)(calagedatem+12*cpt)){
4498: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4499: /*fprintf(ficrespop," %.3f", kk1);
4500: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4501: }
4502: }
4503: for(i=1; i<=nlstate;i++){
4504: kk1=0.;
4505: for(j=1; j<=nlstate;j++){
4506: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4507: }
4508: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4509: }
4510:
4511: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4512: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4513: }
4514: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4515: }
4516: }
4517:
4518: /******/
4519:
4520: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4521: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4522: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4523: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4524: nhstepm = nhstepm/hstepm;
4525:
4526: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4527: oldm=oldms;savm=savms;
4528: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4529: for (h=0; h<=nhstepm; h++){
4530: if (h==(int) (calagedatem+YEARM*cpt)) {
4531: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4532: }
4533: for(j=1; j<=nlstate+ndeath;j++) {
4534: kk1=0.;kk2=0;
4535: for(i=1; i<=nlstate;i++) {
4536: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4537: }
4538: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4539: }
4540: }
4541: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4542: }
4543: }
4544: }
4545: }
4546:
4547: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4548:
4549: if (popforecast==1) {
4550: free_ivector(popage,0,AGESUP);
4551: free_vector(popeffectif,0,AGESUP);
4552: free_vector(popcount,0,AGESUP);
4553: }
4554: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4555: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4556: fclose(ficrespop);
4557: } /* End of popforecast */
4558:
4559: int fileappend(FILE *fichier, char *optionfich)
4560: {
4561: if((fichier=fopen(optionfich,"a"))==NULL) {
4562: printf("Problem with file: %s\n", optionfich);
4563: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4564: return (0);
4565: }
4566: fflush(fichier);
4567: return (1);
4568: }
4569:
4570:
4571: /**************** function prwizard **********************/
4572: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4573: {
4574:
4575: /* Wizard to print covariance matrix template */
4576:
4577: char ca[32], cb[32], cc[32];
4578: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4579: int numlinepar;
4580:
4581: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4582: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4583: for(i=1; i <=nlstate; i++){
4584: jj=0;
4585: for(j=1; j <=nlstate+ndeath; j++){
4586: if(j==i) continue;
4587: jj++;
4588: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4589: printf("%1d%1d",i,j);
4590: fprintf(ficparo,"%1d%1d",i,j);
4591: for(k=1; k<=ncovmodel;k++){
4592: /* printf(" %lf",param[i][j][k]); */
4593: /* fprintf(ficparo," %lf",param[i][j][k]); */
4594: printf(" 0.");
4595: fprintf(ficparo," 0.");
4596: }
4597: printf("\n");
4598: fprintf(ficparo,"\n");
4599: }
4600: }
4601: printf("# Scales (for hessian or gradient estimation)\n");
4602: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4603: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4604: for(i=1; i <=nlstate; i++){
4605: jj=0;
4606: for(j=1; j <=nlstate+ndeath; j++){
4607: if(j==i) continue;
4608: jj++;
4609: fprintf(ficparo,"%1d%1d",i,j);
4610: printf("%1d%1d",i,j);
4611: fflush(stdout);
4612: for(k=1; k<=ncovmodel;k++){
4613: /* printf(" %le",delti3[i][j][k]); */
4614: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4615: printf(" 0.");
4616: fprintf(ficparo," 0.");
4617: }
4618: numlinepar++;
4619: printf("\n");
4620: fprintf(ficparo,"\n");
4621: }
4622: }
4623: printf("# Covariance matrix\n");
4624: /* # 121 Var(a12)\n\ */
4625: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4626: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4627: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4628: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4629: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4630: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4631: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4632: fflush(stdout);
4633: fprintf(ficparo,"# Covariance matrix\n");
4634: /* # 121 Var(a12)\n\ */
4635: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4636: /* # ...\n\ */
4637: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4638:
4639: for(itimes=1;itimes<=2;itimes++){
4640: jj=0;
4641: for(i=1; i <=nlstate; i++){
4642: for(j=1; j <=nlstate+ndeath; j++){
4643: if(j==i) continue;
4644: for(k=1; k<=ncovmodel;k++){
4645: jj++;
4646: ca[0]= k+'a'-1;ca[1]='\0';
4647: if(itimes==1){
4648: printf("#%1d%1d%d",i,j,k);
4649: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4650: }else{
4651: printf("%1d%1d%d",i,j,k);
4652: fprintf(ficparo,"%1d%1d%d",i,j,k);
4653: /* printf(" %.5le",matcov[i][j]); */
4654: }
4655: ll=0;
4656: for(li=1;li <=nlstate; li++){
4657: for(lj=1;lj <=nlstate+ndeath; lj++){
4658: if(lj==li) continue;
4659: for(lk=1;lk<=ncovmodel;lk++){
4660: ll++;
4661: if(ll<=jj){
4662: cb[0]= lk +'a'-1;cb[1]='\0';
4663: if(ll<jj){
4664: if(itimes==1){
4665: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4666: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4667: }else{
4668: printf(" 0.");
4669: fprintf(ficparo," 0.");
4670: }
4671: }else{
4672: if(itimes==1){
4673: printf(" Var(%s%1d%1d)",ca,i,j);
4674: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4675: }else{
4676: printf(" 0.");
4677: fprintf(ficparo," 0.");
4678: }
4679: }
4680: }
4681: } /* end lk */
4682: } /* end lj */
4683: } /* end li */
4684: printf("\n");
4685: fprintf(ficparo,"\n");
4686: numlinepar++;
4687: } /* end k*/
4688: } /*end j */
4689: } /* end i */
4690: } /* end itimes */
4691:
4692: } /* end of prwizard */
4693: /******************* Gompertz Likelihood ******************************/
4694: double gompertz(double x[])
4695: {
4696: double A,B,L=0.0,sump=0.,num=0.;
4697: int i,n=0; /* n is the size of the sample */
4698:
4699: for (i=0;i<=imx-1 ; i++) {
4700: sump=sump+weight[i];
4701: /* sump=sump+1;*/
4702: num=num+1;
4703: }
4704:
4705:
4706: /* for (i=0; i<=imx; i++)
4707: 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]);*/
4708:
4709: for (i=1;i<=imx ; i++)
4710: {
4711: if (cens[i] == 1 && wav[i]>1)
4712: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4713:
4714: if (cens[i] == 0 && wav[i]>1)
4715: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4716: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4717:
4718: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4719: if (wav[i] > 1 ) { /* ??? */
4720: L=L+A*weight[i];
4721: /* 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]);*/
4722: }
4723: }
4724:
4725: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4726:
4727: return -2*L*num/sump;
4728: }
4729:
1.136 brouard 4730: #ifdef GSL
4731: /******************* Gompertz_f Likelihood ******************************/
4732: double gompertz_f(const gsl_vector *v, void *params)
4733: {
4734: double A,B,LL=0.0,sump=0.,num=0.;
4735: double *x= (double *) v->data;
4736: int i,n=0; /* n is the size of the sample */
4737:
4738: for (i=0;i<=imx-1 ; i++) {
4739: sump=sump+weight[i];
4740: /* sump=sump+1;*/
4741: num=num+1;
4742: }
4743:
4744:
4745: /* for (i=0; i<=imx; i++)
4746: 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]);*/
4747: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4748: for (i=1;i<=imx ; i++)
4749: {
4750: if (cens[i] == 1 && wav[i]>1)
4751: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4752:
4753: if (cens[i] == 0 && wav[i]>1)
4754: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4755: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4756:
4757: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4758: if (wav[i] > 1 ) { /* ??? */
4759: LL=LL+A*weight[i];
4760: /* 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]);*/
4761: }
4762: }
4763:
4764: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4765: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4766:
4767: return -2*LL*num/sump;
4768: }
4769: #endif
4770:
1.126 brouard 4771: /******************* Printing html file ***********/
4772: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4773: int lastpass, int stepm, int weightopt, char model[],\
4774: int imx, double p[],double **matcov,double agemortsup){
4775: int i,k;
4776:
4777: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4778: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4779: for (i=1;i<=2;i++)
4780: 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]));
4781: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4782: fprintf(fichtm,"</ul>");
4783:
4784: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4785:
4786: 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>");
4787:
4788: for (k=agegomp;k<(agemortsup-2);k++)
4789: 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]);
4790:
4791:
4792: fflush(fichtm);
4793: }
4794:
4795: /******************* Gnuplot file **************/
4796: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4797:
4798: char dirfileres[132],optfileres[132];
4799: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4800: int ng;
4801:
4802:
4803: /*#ifdef windows */
4804: fprintf(ficgp,"cd \"%s\" \n",pathc);
4805: /*#endif */
4806:
4807:
4808: strcpy(dirfileres,optionfilefiname);
4809: strcpy(optfileres,"vpl");
4810: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4811: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4812: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4813: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4814: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4815:
4816: }
4817:
1.136 brouard 4818: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4819: {
1.126 brouard 4820:
1.136 brouard 4821: /*-------- data file ----------*/
4822: FILE *fic;
4823: char dummy[]=" ";
4824: int i, j, n;
4825: int linei, month, year,iout;
4826: char line[MAXLINE], linetmp[MAXLINE];
4827: char stra[80], strb[80];
4828: char *stratrunc;
4829: int lstra;
1.126 brouard 4830:
4831:
1.136 brouard 4832: if((fic=fopen(datafile,"r"))==NULL) {
4833: printf("Problem while opening datafile: %s\n", datafile);return 1;
4834: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4835: }
1.126 brouard 4836:
1.136 brouard 4837: i=1;
4838: linei=0;
4839: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4840: linei=linei+1;
4841: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4842: if(line[j] == '\t')
4843: line[j] = ' ';
4844: }
4845: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4846: ;
4847: };
4848: line[j+1]=0; /* Trims blanks at end of line */
4849: if(line[0]=='#'){
4850: fprintf(ficlog,"Comment line\n%s\n",line);
4851: printf("Comment line\n%s\n",line);
4852: continue;
4853: }
4854: trimbb(linetmp,line); /* Trims multiple blanks in line */
4855: for (j=0; line[j]!='\0';j++){
4856: line[j]=linetmp[j];
4857: }
4858:
1.126 brouard 4859:
1.136 brouard 4860: for (j=maxwav;j>=1;j--){
1.137 brouard 4861: cutv(stra, strb, line, ' ');
1.136 brouard 4862: if(strb[0]=='.') { /* Missing status */
4863: lval=-1;
4864: }else{
4865: errno=0;
4866: lval=strtol(strb,&endptr,10);
4867: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4868: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4869: 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);
4870: 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 4871: return 1;
4872: }
4873: }
4874: s[j][i]=lval;
4875:
4876: strcpy(line,stra);
4877: cutv(stra, strb,line,' ');
4878: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4879: }
1.145 brouard 4880: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 4881: month=99;
4882: year=9999;
4883: }else{
1.141 brouard 4884: 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);
4885: 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 4886: return 1;
4887: }
4888: anint[j][i]= (double) year;
4889: mint[j][i]= (double)month;
4890: strcpy(line,stra);
4891: } /* ENd Waves */
4892:
4893: cutv(stra, strb,line,' ');
4894: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4895: }
4896: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4897: month=99;
4898: year=9999;
4899: }else{
1.141 brouard 4900: 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);
4901: 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 4902: return 1;
4903: }
4904: andc[i]=(double) year;
4905: moisdc[i]=(double) month;
4906: strcpy(line,stra);
4907:
4908: cutv(stra, strb,line,' ');
4909: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4910: }
1.145 brouard 4911: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 4912: month=99;
4913: year=9999;
4914: }else{
1.141 brouard 4915: 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);
4916: 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 4917: return 1;
4918: }
4919: if (year==9999) {
1.141 brouard 4920: 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);
4921: 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 4922: return 1;
1.126 brouard 4923:
1.136 brouard 4924: }
4925: annais[i]=(double)(year);
4926: moisnais[i]=(double)(month);
4927: strcpy(line,stra);
4928:
4929: cutv(stra, strb,line,' ');
4930: errno=0;
4931: dval=strtod(strb,&endptr);
4932: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4933: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4934: 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 4935: fflush(ficlog);
4936: return 1;
4937: }
4938: weight[i]=dval;
4939: strcpy(line,stra);
4940:
4941: for (j=ncovcol;j>=1;j--){
4942: cutv(stra, strb,line,' ');
4943: if(strb[0]=='.') { /* Missing status */
4944: lval=-1;
4945: }else{
4946: errno=0;
4947: lval=strtol(strb,&endptr,10);
4948: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4949: 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);
4950: 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 4951: return 1;
4952: }
4953: }
4954: if(lval <-1 || lval >1){
1.141 brouard 4955: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4956: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4957: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4958: For example, for multinomial values like 1, 2 and 3,\n \
4959: build V1=0 V2=0 for the reference value (1),\n \
4960: V1=1 V2=0 for (2) \n \
4961: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4962: output of IMaCh is often meaningless.\n \
4963: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 4964: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4965: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4966: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4967: For example, for multinomial values like 1, 2 and 3,\n \
4968: build V1=0 V2=0 for the reference value (1),\n \
4969: V1=1 V2=0 for (2) \n \
4970: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4971: output of IMaCh is often meaningless.\n \
4972: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
4973: return 1;
4974: }
4975: covar[j][i]=(double)(lval);
4976: strcpy(line,stra);
4977: }
4978: lstra=strlen(stra);
4979:
4980: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
4981: stratrunc = &(stra[lstra-9]);
4982: num[i]=atol(stratrunc);
4983: }
4984: else
4985: num[i]=atol(stra);
4986: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
4987: 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;}*/
4988:
4989: i=i+1;
4990: } /* End loop reading data */
1.126 brouard 4991:
1.136 brouard 4992: *imax=i-1; /* Number of individuals */
4993: fclose(fic);
4994:
4995: return (0);
4996: endread:
4997: printf("Exiting readdata: ");
4998: fclose(fic);
4999: return (1);
1.126 brouard 5000:
5001:
5002:
1.136 brouard 5003: }
1.145 brouard 5004: void removespace(char *str) {
5005: char *p1 = str, *p2 = str;
5006: do
5007: while (*p2 == ' ')
5008: p2++;
5009: while (*p1++ = *p2++);
5010: }
5011:
5012: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5013: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5014: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5015: * - cptcovn or number of covariates k of the models excluding age*products =6
5016: * - cptcovage number of covariates with age*products =2
5017: * - cptcovs number of simple covariates
5018: * - 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
5019: * which is a new column after the 9 (ncovcol) variables.
5020: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5021: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5022: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5023: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5024: */
1.136 brouard 5025: {
1.145 brouard 5026: int i, j, k, ks;
1.136 brouard 5027: int i1, j1, k1, k2;
5028: char modelsav[80];
1.145 brouard 5029: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5030:
1.145 brouard 5031: /*removespace(model);*/
1.136 brouard 5032: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5033: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5034: j=nbocc(model,'+'); /**< j=Number of '+' */
5035: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5036: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5037: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5038: /* including age products which are counted in cptcovage.
5039: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5040: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5041: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5042: strcpy(modelsav,model);
1.137 brouard 5043: if (strstr(model,"AGE") !=0){
5044: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5045: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5046: return 1;
5047: }
1.141 brouard 5048: if (strstr(model,"v") !=0){
5049: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5050: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5051: return 1;
5052: }
1.136 brouard 5053:
1.145 brouard 5054: /* Design
5055: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5056: * < ncovcol=8 >
5057: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5058: * k= 1 2 3 4 5 6 7 8
5059: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5060: * covar[k,i], value of kth covariate if not including age for individual i:
5061: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5062: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5063: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5064: * Tage[++cptcovage]=k
5065: * if products, new covar are created after ncovcol with k1
5066: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5067: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5068: * 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
5069: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5070: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5071: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5072: * < ncovcol=8 >
5073: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5074: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5075: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5076: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5077: * p Tprod[1]@2={ 6, 5}
5078: *p Tvard[1][1]@4= {7, 8, 5, 6}
5079: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5080: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5081: *How to reorganize?
5082: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5083: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5084: * {2, 1, 4, 8, 5, 6, 3, 7}
5085: * Struct []
5086: */
5087:
1.136 brouard 5088: /* This loop fills the array Tvar from the string 'model'.*/
5089: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5090: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5091: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5092: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5093: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5094: /* k=1 Tvar[1]=2 (from V2) */
5095: /* k=5 Tvar[5] */
5096: /* for (k=1; k<=cptcovn;k++) { */
5097: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5098: /* } */
5099: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5100: /*
5101: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5102: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5103: Tvar[k]=0;
5104: cptcovage=0;
5105: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5106: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5107: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5108: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5109: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5110: /*scanf("%d",i);*/
1.145 brouard 5111: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5112: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5113: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5114: /* covar is not filled and then is empty */
1.136 brouard 5115: cptcovprod--;
1.145 brouard 5116: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5117: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5118: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5119: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5120: /*printf("stre=%s ", stre);*/
1.137 brouard 5121: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5122: cptcovprod--;
1.145 brouard 5123: cutl(stre,strb,strc,'V');
1.136 brouard 5124: Tvar[k]=atoi(stre);
5125: cptcovage++;
5126: Tage[cptcovage]=k;
1.137 brouard 5127: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5128: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5129: cptcovn++;
5130: cptcovprodnoage++;k1++;
5131: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5132: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5133: because this model-covariate is a construction we invent a new column
5134: ncovcol + k1
5135: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5136: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5137: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5138: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5139: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5140: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5141: k2=k2+2;
5142: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5143: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5144: for (i=1; i<=lastobs;i++){
5145: /* Computes the new covariate which is a product of
1.145 brouard 5146: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5147: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5148: }
5149: } /* End age is not in the model */
5150: } /* End if model includes a product */
1.136 brouard 5151: else { /* no more sum */
5152: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5153: /* scanf("%d",i);*/
1.145 brouard 5154: cutl(strd,strc,strb,'V');
5155: ks++; /**< Number of simple covariates */
5156: cptcovn++;
5157: Tvar[k]=atoi(strd);
1.136 brouard 5158: }
1.137 brouard 5159: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5160: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5161: scanf("%d",i);*/
5162: } /* end of loop + */
5163: } /* end model */
5164:
5165: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5166: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5167:
5168: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5169: printf("cptcovprod=%d ", cptcovprod);
5170: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5171:
5172: scanf("%d ",i);*/
5173:
5174:
1.137 brouard 5175: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.136 brouard 5176: endread:
5177: printf("Exiting decodemodel: ");
5178: return (1);
5179: }
5180:
5181: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5182: {
5183: int i, m;
5184:
5185: for (i=1; i<=imx; i++) {
5186: for(m=2; (m<= maxwav); m++) {
5187: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5188: anint[m][i]=9999;
5189: s[m][i]=-1;
5190: }
5191: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5192: *nberr++;
5193: 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);
5194: 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);
5195: s[m][i]=-1;
5196: }
5197: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5198: *nberr++;
5199: 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]);
5200: 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]);
5201: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5202: }
5203: }
5204: }
5205:
5206: for (i=1; i<=imx; i++) {
5207: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5208: for(m=firstpass; (m<= lastpass); m++){
5209: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5210: if (s[m][i] >= nlstate+1) {
5211: if(agedc[i]>0)
5212: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5213: agev[m][i]=agedc[i];
5214: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5215: else {
5216: if ((int)andc[i]!=9999){
5217: nbwarn++;
5218: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5219: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5220: agev[m][i]=-1;
5221: }
5222: }
5223: }
5224: else if(s[m][i] !=9){ /* Standard case, age in fractional
5225: years but with the precision of a month */
5226: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5227: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5228: agev[m][i]=1;
5229: else if(agev[m][i] < *agemin){
5230: *agemin=agev[m][i];
5231: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5232: }
5233: else if(agev[m][i] >*agemax){
5234: *agemax=agev[m][i];
1.156 brouard 5235: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5236: }
5237: /*agev[m][i]=anint[m][i]-annais[i];*/
5238: /* agev[m][i] = age[i]+2*m;*/
5239: }
5240: else { /* =9 */
5241: agev[m][i]=1;
5242: s[m][i]=-1;
5243: }
5244: }
5245: else /*= 0 Unknown */
5246: agev[m][i]=1;
5247: }
5248:
5249: }
5250: for (i=1; i<=imx; i++) {
5251: for(m=firstpass; (m<=lastpass); m++){
5252: if (s[m][i] > (nlstate+ndeath)) {
5253: *nberr++;
5254: 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);
5255: 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);
5256: return 1;
5257: }
5258: }
5259: }
5260:
5261: /*for (i=1; i<=imx; i++){
5262: for (m=firstpass; (m<lastpass); m++){
5263: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5264: }
5265:
5266: }*/
5267:
5268:
1.139 brouard 5269: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5270: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5271:
5272: return (0);
5273: endread:
5274: printf("Exiting calandcheckages: ");
5275: return (1);
5276: }
5277:
5278:
5279: /***********************************************/
5280: /**************** Main Program *****************/
5281: /***********************************************/
5282:
5283: int main(int argc, char *argv[])
5284: {
5285: #ifdef GSL
5286: const gsl_multimin_fminimizer_type *T;
5287: size_t iteri = 0, it;
5288: int rval = GSL_CONTINUE;
5289: int status = GSL_SUCCESS;
5290: double ssval;
5291: #endif
5292: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5293: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5294: int linei, month, year,iout;
5295: int jj, ll, li, lj, lk, imk;
5296: int numlinepar=0; /* Current linenumber of parameter file */
5297: int itimes;
5298: int NDIM=2;
5299: int vpopbased=0;
5300:
5301: char ca[32], cb[32], cc[32];
5302: /* FILE *fichtm; *//* Html File */
5303: /* FILE *ficgp;*/ /*Gnuplot File */
5304: struct stat info;
5305: double agedeb, agefin,hf;
5306: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5307:
5308: double fret;
5309: double **xi,tmp,delta;
5310:
5311: double dum; /* Dummy variable */
5312: double ***p3mat;
5313: double ***mobaverage;
5314: int *indx;
5315: char line[MAXLINE], linepar[MAXLINE];
5316: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5317: char pathr[MAXLINE], pathimach[MAXLINE];
5318: char **bp, *tok, *val; /* pathtot */
5319: int firstobs=1, lastobs=10;
5320: int sdeb, sfin; /* Status at beginning and end */
5321: int c, h , cpt,l;
5322: int ju,jl, mi;
5323: int i1,j1, jk,aa,bb, stepsize, ij;
5324: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5325: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5326: int mobilav=0,popforecast=0;
5327: int hstepm, nhstepm;
5328: int agemortsup;
5329: float sumlpop=0.;
5330: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5331: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5332:
5333: double bage, fage, age, agelim, agebase;
5334: double ftolpl=FTOL;
5335: double **prlim;
5336: double ***param; /* Matrix of parameters */
5337: double *p;
5338: double **matcov; /* Matrix of covariance */
5339: double ***delti3; /* Scale */
5340: double *delti; /* Scale */
5341: double ***eij, ***vareij;
5342: double **varpl; /* Variances of prevalence limits by age */
5343: double *epj, vepp;
5344: double kk1, kk2;
5345: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5346: double **ximort;
1.145 brouard 5347: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5348: int *dcwave;
5349:
5350: char z[1]="c", occ;
5351:
5352: /*char *strt;*/
5353: char strtend[80];
1.126 brouard 5354:
5355: long total_usecs;
5356:
5357: /* setlocale (LC_ALL, ""); */
5358: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5359: /* textdomain (PACKAGE); */
5360: /* setlocale (LC_CTYPE, ""); */
5361: /* setlocale (LC_MESSAGES, ""); */
5362:
5363: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5364: rstart_time = time(NULL);
5365: /* (void) gettimeofday(&start_time,&tzp);*/
5366: start_time = *localtime(&rstart_time);
1.126 brouard 5367: curr_time=start_time;
1.157 brouard 5368: /*tml = *localtime(&start_time.tm_sec);*/
5369: /* strcpy(strstart,asctime(&tml)); */
5370: strcpy(strstart,asctime(&start_time));
1.126 brouard 5371:
5372: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5373: /* tp.tm_sec = tp.tm_sec +86400; */
5374: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5375: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5376: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5377: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5378: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5379: /* strt=asctime(&tmg); */
5380: /* printf("Time(after) =%s",strstart); */
5381: /* (void) time (&time_value);
5382: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5383: * tm = *localtime(&time_value);
5384: * strstart=asctime(&tm);
5385: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5386: */
5387:
5388: nberr=0; /* Number of errors and warnings */
5389: nbwarn=0;
5390: getcwd(pathcd, size);
5391:
5392: printf("\n%s\n%s",version,fullversion);
5393: if(argc <=1){
5394: printf("\nEnter the parameter file name: ");
5395: fgets(pathr,FILENAMELENGTH,stdin);
5396: i=strlen(pathr);
5397: if(pathr[i-1]=='\n')
5398: pathr[i-1]='\0';
1.156 brouard 5399: i=strlen(pathr);
5400: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5401: pathr[i-1]='\0';
1.126 brouard 5402: for (tok = pathr; tok != NULL; ){
5403: printf("Pathr |%s|\n",pathr);
5404: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5405: printf("val= |%s| pathr=%s\n",val,pathr);
5406: strcpy (pathtot, val);
5407: if(pathr[0] == '\0') break; /* Dirty */
5408: }
5409: }
5410: else{
5411: strcpy(pathtot,argv[1]);
5412: }
5413: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5414: /*cygwin_split_path(pathtot,path,optionfile);
5415: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5416: /* cutv(path,optionfile,pathtot,'\\');*/
5417:
5418: /* Split argv[0], imach program to get pathimach */
5419: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5420: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5421: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5422: /* strcpy(pathimach,argv[0]); */
5423: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5424: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5425: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5426: chdir(path); /* Can be a relative path */
5427: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5428: printf("Current directory %s!\n",pathcd);
5429: strcpy(command,"mkdir ");
5430: strcat(command,optionfilefiname);
5431: if((outcmd=system(command)) != 0){
5432: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5433: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5434: /* fclose(ficlog); */
5435: /* exit(1); */
5436: }
5437: /* if((imk=mkdir(optionfilefiname))<0){ */
5438: /* perror("mkdir"); */
5439: /* } */
5440:
5441: /*-------- arguments in the command line --------*/
5442:
5443: /* Log file */
5444: strcat(filelog, optionfilefiname);
5445: strcat(filelog,".log"); /* */
5446: if((ficlog=fopen(filelog,"w"))==NULL) {
5447: printf("Problem with logfile %s\n",filelog);
5448: goto end;
5449: }
5450: fprintf(ficlog,"Log filename:%s\n",filelog);
5451: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5452: fprintf(ficlog,"\nEnter the parameter file name: \n");
5453: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5454: path=%s \n\
5455: optionfile=%s\n\
5456: optionfilext=%s\n\
1.156 brouard 5457: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5458:
5459: printf("Local time (at start):%s",strstart);
5460: fprintf(ficlog,"Local time (at start): %s",strstart);
5461: fflush(ficlog);
5462: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5463: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5464:
5465: /* */
5466: strcpy(fileres,"r");
5467: strcat(fileres, optionfilefiname);
5468: strcat(fileres,".txt"); /* Other files have txt extension */
5469:
5470: /*---------arguments file --------*/
5471:
5472: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5473: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5474: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5475: fflush(ficlog);
1.149 brouard 5476: /* goto end; */
5477: exit(70);
1.126 brouard 5478: }
5479:
5480:
5481:
5482: strcpy(filereso,"o");
5483: strcat(filereso,fileres);
5484: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5485: printf("Problem with Output resultfile: %s\n", filereso);
5486: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5487: fflush(ficlog);
5488: goto end;
5489: }
5490:
5491: /* Reads comments: lines beginning with '#' */
5492: numlinepar=0;
5493: while((c=getc(ficpar))=='#' && c!= EOF){
5494: ungetc(c,ficpar);
5495: fgets(line, MAXLINE, ficpar);
5496: numlinepar++;
1.141 brouard 5497: fputs(line,stdout);
1.126 brouard 5498: fputs(line,ficparo);
5499: fputs(line,ficlog);
5500: }
5501: ungetc(c,ficpar);
5502:
5503: 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);
5504: numlinepar++;
5505: 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);
5506: 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);
5507: 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);
5508: fflush(ficlog);
5509: while((c=getc(ficpar))=='#' && c!= EOF){
5510: ungetc(c,ficpar);
5511: fgets(line, MAXLINE, ficpar);
5512: numlinepar++;
1.141 brouard 5513: fputs(line, stdout);
5514: //puts(line);
1.126 brouard 5515: fputs(line,ficparo);
5516: fputs(line,ficlog);
5517: }
5518: ungetc(c,ficpar);
5519:
5520:
1.145 brouard 5521: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5522: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5523: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5524: v1+v2*age+v2*v3 makes cptcovn = 3
5525: */
5526: if (strlen(model)>1)
1.145 brouard 5527: 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*/
5528: else
5529: ncovmodel=2;
1.126 brouard 5530: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5531: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5532: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5533: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5534: 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);
5535: 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);
5536: fflush(stdout);
5537: fclose (ficlog);
5538: goto end;
5539: }
1.126 brouard 5540: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5541: delti=delti3[1][1];
5542: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5543: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5544: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5545: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5546: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5547: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5548: fclose (ficparo);
5549: fclose (ficlog);
5550: goto end;
5551: exit(0);
5552: }
5553: else if(mle==-3) {
5554: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5555: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5556: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5557: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5558: matcov=matrix(1,npar,1,npar);
5559: }
5560: else{
1.145 brouard 5561: /* Read guessed parameters */
1.126 brouard 5562: /* Reads comments: lines beginning with '#' */
5563: while((c=getc(ficpar))=='#' && c!= EOF){
5564: ungetc(c,ficpar);
5565: fgets(line, MAXLINE, ficpar);
5566: numlinepar++;
1.141 brouard 5567: fputs(line,stdout);
1.126 brouard 5568: fputs(line,ficparo);
5569: fputs(line,ficlog);
5570: }
5571: ungetc(c,ficpar);
5572:
5573: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5574: for(i=1; i <=nlstate; i++){
5575: j=0;
5576: for(jj=1; jj <=nlstate+ndeath; jj++){
5577: if(jj==i) continue;
5578: j++;
5579: fscanf(ficpar,"%1d%1d",&i1,&j1);
5580: if ((i1 != i) && (j1 != j)){
5581: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5582: It might be a problem of design; if ncovcol and the model are correct\n \
5583: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5584: exit(1);
5585: }
5586: fprintf(ficparo,"%1d%1d",i1,j1);
5587: if(mle==1)
5588: printf("%1d%1d",i,j);
5589: fprintf(ficlog,"%1d%1d",i,j);
5590: for(k=1; k<=ncovmodel;k++){
5591: fscanf(ficpar," %lf",¶m[i][j][k]);
5592: if(mle==1){
5593: printf(" %lf",param[i][j][k]);
5594: fprintf(ficlog," %lf",param[i][j][k]);
5595: }
5596: else
5597: fprintf(ficlog," %lf",param[i][j][k]);
5598: fprintf(ficparo," %lf",param[i][j][k]);
5599: }
5600: fscanf(ficpar,"\n");
5601: numlinepar++;
5602: if(mle==1)
5603: printf("\n");
5604: fprintf(ficlog,"\n");
5605: fprintf(ficparo,"\n");
5606: }
5607: }
5608: fflush(ficlog);
5609:
1.145 brouard 5610: /* Reads scales values */
1.126 brouard 5611: p=param[1][1];
5612:
5613: /* Reads comments: lines beginning with '#' */
5614: while((c=getc(ficpar))=='#' && c!= EOF){
5615: ungetc(c,ficpar);
5616: fgets(line, MAXLINE, ficpar);
5617: numlinepar++;
1.141 brouard 5618: fputs(line,stdout);
1.126 brouard 5619: fputs(line,ficparo);
5620: fputs(line,ficlog);
5621: }
5622: ungetc(c,ficpar);
5623:
5624: for(i=1; i <=nlstate; i++){
5625: for(j=1; j <=nlstate+ndeath-1; j++){
5626: fscanf(ficpar,"%1d%1d",&i1,&j1);
5627: if ((i1-i)*(j1-j)!=0){
5628: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5629: exit(1);
5630: }
5631: printf("%1d%1d",i,j);
5632: fprintf(ficparo,"%1d%1d",i1,j1);
5633: fprintf(ficlog,"%1d%1d",i1,j1);
5634: for(k=1; k<=ncovmodel;k++){
5635: fscanf(ficpar,"%le",&delti3[i][j][k]);
5636: printf(" %le",delti3[i][j][k]);
5637: fprintf(ficparo," %le",delti3[i][j][k]);
5638: fprintf(ficlog," %le",delti3[i][j][k]);
5639: }
5640: fscanf(ficpar,"\n");
5641: numlinepar++;
5642: printf("\n");
5643: fprintf(ficparo,"\n");
5644: fprintf(ficlog,"\n");
5645: }
5646: }
5647: fflush(ficlog);
5648:
1.145 brouard 5649: /* Reads covariance matrix */
1.126 brouard 5650: delti=delti3[1][1];
5651:
5652:
5653: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5654:
5655: /* Reads comments: lines beginning with '#' */
5656: while((c=getc(ficpar))=='#' && c!= EOF){
5657: ungetc(c,ficpar);
5658: fgets(line, MAXLINE, ficpar);
5659: numlinepar++;
1.141 brouard 5660: fputs(line,stdout);
1.126 brouard 5661: fputs(line,ficparo);
5662: fputs(line,ficlog);
5663: }
5664: ungetc(c,ficpar);
5665:
5666: matcov=matrix(1,npar,1,npar);
1.131 brouard 5667: for(i=1; i <=npar; i++)
5668: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5669:
1.126 brouard 5670: for(i=1; i <=npar; i++){
1.145 brouard 5671: fscanf(ficpar,"%s",str);
1.126 brouard 5672: if(mle==1)
5673: printf("%s",str);
5674: fprintf(ficlog,"%s",str);
5675: fprintf(ficparo,"%s",str);
5676: for(j=1; j <=i; j++){
5677: fscanf(ficpar," %le",&matcov[i][j]);
5678: if(mle==1){
5679: printf(" %.5le",matcov[i][j]);
5680: }
5681: fprintf(ficlog," %.5le",matcov[i][j]);
5682: fprintf(ficparo," %.5le",matcov[i][j]);
5683: }
5684: fscanf(ficpar,"\n");
5685: numlinepar++;
5686: if(mle==1)
5687: printf("\n");
5688: fprintf(ficlog,"\n");
5689: fprintf(ficparo,"\n");
5690: }
5691: for(i=1; i <=npar; i++)
5692: for(j=i+1;j<=npar;j++)
5693: matcov[i][j]=matcov[j][i];
5694:
5695: if(mle==1)
5696: printf("\n");
5697: fprintf(ficlog,"\n");
5698:
5699: fflush(ficlog);
5700:
5701: /*-------- Rewriting parameter file ----------*/
5702: strcpy(rfileres,"r"); /* "Rparameterfile */
5703: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5704: strcat(rfileres,"."); /* */
5705: strcat(rfileres,optionfilext); /* Other files have txt extension */
5706: if((ficres =fopen(rfileres,"w"))==NULL) {
5707: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5708: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5709: }
5710: fprintf(ficres,"#%s\n",version);
5711: } /* End of mle != -3 */
5712:
5713:
5714: n= lastobs;
5715: num=lvector(1,n);
5716: moisnais=vector(1,n);
5717: annais=vector(1,n);
5718: moisdc=vector(1,n);
5719: andc=vector(1,n);
5720: agedc=vector(1,n);
5721: cod=ivector(1,n);
5722: weight=vector(1,n);
5723: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5724: mint=matrix(1,maxwav,1,n);
5725: anint=matrix(1,maxwav,1,n);
1.131 brouard 5726: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5727: tab=ivector(1,NCOVMAX);
1.144 brouard 5728: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5729:
1.136 brouard 5730: /* Reads data from file datafile */
5731: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5732: goto end;
5733:
5734: /* Calculation of the number of parameters from char model */
1.137 brouard 5735: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5736: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5737: k=3 V4 Tvar[k=3]= 4 (from V4)
5738: k=2 V1 Tvar[k=2]= 1 (from V1)
5739: k=1 Tvar[1]=2 (from V2)
5740: */
5741: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5742: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5743: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5744: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5745: */
5746: /* For model-covariate k tells which data-covariate to use but
5747: because this model-covariate is a construction we invent a new column
5748: ncovcol + k1
5749: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5750: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5751: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5752: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5753: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5754: */
1.145 brouard 5755: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5756: 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 5757: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5758: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5759: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5760: 4 covariates (3 plus signs)
5761: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5762: */
1.136 brouard 5763:
5764: if(decodemodel(model, lastobs) == 1)
5765: goto end;
5766:
1.137 brouard 5767: if((double)(lastobs-imx)/(double)imx > 1.10){
5768: nbwarn++;
5769: 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);
5770: 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);
5771: }
1.136 brouard 5772: /* if(mle==1){*/
1.137 brouard 5773: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5774: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5775: }
5776:
5777: /*-calculation of age at interview from date of interview and age at death -*/
5778: agev=matrix(1,maxwav,1,imx);
5779:
5780: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5781: goto end;
5782:
1.126 brouard 5783:
1.136 brouard 5784: agegomp=(int)agemin;
5785: free_vector(moisnais,1,n);
5786: free_vector(annais,1,n);
1.126 brouard 5787: /* free_matrix(mint,1,maxwav,1,n);
5788: free_matrix(anint,1,maxwav,1,n);*/
5789: free_vector(moisdc,1,n);
5790: free_vector(andc,1,n);
1.145 brouard 5791: /* */
5792:
1.126 brouard 5793: wav=ivector(1,imx);
5794: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5795: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5796: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5797:
5798: /* Concatenates waves */
5799: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5800: /* */
5801:
1.126 brouard 5802: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5803:
5804: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5805: ncodemax[1]=1;
1.145 brouard 5806: Ndum =ivector(-1,NCOVMAX);
5807: if (ncovmodel > 2)
5808: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5809:
5810: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5811: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5812: h=0;
5813:
5814:
5815: /*if (cptcovn > 0) */
1.126 brouard 5816:
1.145 brouard 5817:
1.126 brouard 5818: m=pow(2,cptcoveff);
5819:
1.131 brouard 5820: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5821: 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 */
5822: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5823: 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 5824: h++;
1.141 brouard 5825: if (h>m)
1.136 brouard 5826: h=1;
1.144 brouard 5827: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5828: * h 1 2 3 4
5829: *______________________________
5830: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5831: * 2 2 1 1 1
5832: * 3 i=2 1 2 1 1
5833: * 4 2 2 1 1
5834: * 5 i=3 1 i=2 1 2 1
5835: * 6 2 1 2 1
5836: * 7 i=4 1 2 2 1
5837: * 8 2 2 2 1
5838: * 9 i=5 1 i=3 1 i=2 1 1
5839: * 10 2 1 1 1
5840: * 11 i=6 1 2 1 1
5841: * 12 2 2 1 1
5842: * 13 i=7 1 i=4 1 2 1
5843: * 14 2 1 2 1
5844: * 15 i=8 1 2 2 1
5845: * 16 2 2 2 1
5846: */
1.141 brouard 5847: codtab[h][k]=j;
1.145 brouard 5848: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5849: 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 5850: }
5851: }
5852: }
5853: }
5854: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5855: codtab[1][2]=1;codtab[2][2]=2; */
5856: /* for(i=1; i <=m ;i++){
5857: for(k=1; k <=cptcovn; k++){
1.131 brouard 5858: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5859: }
5860: printf("\n");
5861: }
5862: scanf("%d",i);*/
1.145 brouard 5863:
5864: free_ivector(Ndum,-1,NCOVMAX);
5865:
5866:
1.126 brouard 5867:
5868: /*------------ gnuplot -------------*/
5869: strcpy(optionfilegnuplot,optionfilefiname);
5870: if(mle==-3)
5871: strcat(optionfilegnuplot,"-mort");
5872: strcat(optionfilegnuplot,".gp");
5873:
5874: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5875: printf("Problem with file %s",optionfilegnuplot);
5876: }
5877: else{
5878: fprintf(ficgp,"\n# %s\n", version);
5879: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 5880: //fprintf(ficgp,"set missing 'NaNq'\n");
5881: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 5882: }
5883: /* fclose(ficgp);*/
5884: /*--------- index.htm --------*/
5885:
5886: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5887: if(mle==-3)
5888: strcat(optionfilehtm,"-mort");
5889: strcat(optionfilehtm,".htm");
5890: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 5891: printf("Problem with %s \n",optionfilehtm);
5892: exit(0);
1.126 brouard 5893: }
5894:
5895: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5896: strcat(optionfilehtmcov,"-cov.htm");
5897: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5898: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5899: }
5900: else{
5901: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5902: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5903: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5904: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5905: }
5906:
5907: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5908: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5909: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5910: \n\
5911: <hr size=\"2\" color=\"#EC5E5E\">\
5912: <ul><li><h4>Parameter files</h4>\n\
5913: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5914: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5915: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5916: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5917: - Date and time at start: %s</ul>\n",\
5918: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5919: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5920: fileres,fileres,\
5921: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5922: fflush(fichtm);
5923:
5924: strcpy(pathr,path);
5925: strcat(pathr,optionfilefiname);
5926: chdir(optionfilefiname); /* Move to directory named optionfile */
5927:
5928: /* Calculates basic frequencies. Computes observed prevalence at single age
5929: and prints on file fileres'p'. */
5930: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5931:
5932: fprintf(fichtm,"\n");
5933: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5934: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5935: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5936: imx,agemin,agemax,jmin,jmax,jmean);
5937: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5938: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5939: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5940: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5941: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5942:
5943:
5944: /* For Powell, parameters are in a vector p[] starting at p[1]
5945: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5946: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5947:
5948: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5949:
5950: if (mle==-3){
1.136 brouard 5951: ximort=matrix(1,NDIM,1,NDIM);
5952: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 5953: cens=ivector(1,n);
5954: ageexmed=vector(1,n);
5955: agecens=vector(1,n);
5956: dcwave=ivector(1,n);
5957:
5958: for (i=1; i<=imx; i++){
5959: dcwave[i]=-1;
5960: for (m=firstpass; m<=lastpass; m++)
5961: if (s[m][i]>nlstate) {
5962: dcwave[i]=m;
5963: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5964: break;
5965: }
5966: }
5967:
5968: for (i=1; i<=imx; i++) {
5969: if (wav[i]>0){
5970: ageexmed[i]=agev[mw[1][i]][i];
5971: j=wav[i];
5972: agecens[i]=1.;
5973:
5974: if (ageexmed[i]> 1 && wav[i] > 0){
5975: agecens[i]=agev[mw[j][i]][i];
5976: cens[i]= 1;
5977: }else if (ageexmed[i]< 1)
5978: cens[i]= -1;
5979: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
5980: cens[i]=0 ;
5981: }
5982: else cens[i]=-1;
5983: }
5984:
5985: for (i=1;i<=NDIM;i++) {
5986: for (j=1;j<=NDIM;j++)
5987: ximort[i][j]=(i == j ? 1.0 : 0.0);
5988: }
5989:
1.145 brouard 5990: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 5991: /*printf("%lf %lf", p[1], p[2]);*/
5992:
5993:
1.136 brouard 5994: #ifdef GSL
5995: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
5996: #elsedef
1.126 brouard 5997: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 5998: #endif
1.126 brouard 5999: strcpy(filerespow,"pow-mort");
6000: strcat(filerespow,fileres);
6001: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6002: printf("Problem with resultfile: %s\n", filerespow);
6003: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6004: }
1.136 brouard 6005: #ifdef GSL
6006: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6007: #elsedef
1.126 brouard 6008: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6009: #endif
1.126 brouard 6010: /* for (i=1;i<=nlstate;i++)
6011: for(j=1;j<=nlstate+ndeath;j++)
6012: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6013: */
6014: fprintf(ficrespow,"\n");
1.136 brouard 6015: #ifdef GSL
6016: /* gsl starts here */
6017: T = gsl_multimin_fminimizer_nmsimplex;
6018: gsl_multimin_fminimizer *sfm = NULL;
6019: gsl_vector *ss, *x;
6020: gsl_multimin_function minex_func;
6021:
6022: /* Initial vertex size vector */
6023: ss = gsl_vector_alloc (NDIM);
6024:
6025: if (ss == NULL){
6026: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6027: }
6028: /* Set all step sizes to 1 */
6029: gsl_vector_set_all (ss, 0.001);
6030:
6031: /* Starting point */
1.126 brouard 6032:
1.136 brouard 6033: x = gsl_vector_alloc (NDIM);
6034:
6035: if (x == NULL){
6036: gsl_vector_free(ss);
6037: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6038: }
6039:
6040: /* Initialize method and iterate */
6041: /* p[1]=0.0268; p[NDIM]=0.083; */
6042: /* gsl_vector_set(x, 0, 0.0268); */
6043: /* gsl_vector_set(x, 1, 0.083); */
6044: gsl_vector_set(x, 0, p[1]);
6045: gsl_vector_set(x, 1, p[2]);
6046:
6047: minex_func.f = &gompertz_f;
6048: minex_func.n = NDIM;
6049: minex_func.params = (void *)&p; /* ??? */
6050:
6051: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6052: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6053:
6054: printf("Iterations beginning .....\n\n");
6055: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6056:
6057: iteri=0;
6058: while (rval == GSL_CONTINUE){
6059: iteri++;
6060: status = gsl_multimin_fminimizer_iterate(sfm);
6061:
6062: if (status) printf("error: %s\n", gsl_strerror (status));
6063: fflush(0);
6064:
6065: if (status)
6066: break;
6067:
6068: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6069: ssval = gsl_multimin_fminimizer_size (sfm);
6070:
6071: if (rval == GSL_SUCCESS)
6072: printf ("converged to a local maximum at\n");
6073:
6074: printf("%5d ", iteri);
6075: for (it = 0; it < NDIM; it++){
6076: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6077: }
6078: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6079: }
6080:
6081: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6082:
6083: gsl_vector_free(x); /* initial values */
6084: gsl_vector_free(ss); /* inital step size */
6085: for (it=0; it<NDIM; it++){
6086: p[it+1]=gsl_vector_get(sfm->x,it);
6087: fprintf(ficrespow," %.12lf", p[it]);
6088: }
6089: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6090: #endif
6091: #ifdef POWELL
6092: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6093: #endif
1.126 brouard 6094: fclose(ficrespow);
6095:
6096: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6097:
6098: for(i=1; i <=NDIM; i++)
6099: for(j=i+1;j<=NDIM;j++)
6100: matcov[i][j]=matcov[j][i];
6101:
6102: printf("\nCovariance matrix\n ");
6103: for(i=1; i <=NDIM; i++) {
6104: for(j=1;j<=NDIM;j++){
6105: printf("%f ",matcov[i][j]);
6106: }
6107: printf("\n ");
6108: }
6109:
6110: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6111: for (i=1;i<=NDIM;i++)
6112: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6113:
6114: lsurv=vector(1,AGESUP);
6115: lpop=vector(1,AGESUP);
6116: tpop=vector(1,AGESUP);
6117: lsurv[agegomp]=100000;
6118:
6119: for (k=agegomp;k<=AGESUP;k++) {
6120: agemortsup=k;
6121: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6122: }
6123:
6124: for (k=agegomp;k<agemortsup;k++)
6125: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6126:
6127: for (k=agegomp;k<agemortsup;k++){
6128: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6129: sumlpop=sumlpop+lpop[k];
6130: }
6131:
6132: tpop[agegomp]=sumlpop;
6133: for (k=agegomp;k<(agemortsup-3);k++){
6134: /* tpop[k+1]=2;*/
6135: tpop[k+1]=tpop[k]-lpop[k];
6136: }
6137:
6138:
6139: printf("\nAge lx qx dx Lx Tx e(x)\n");
6140: for (k=agegomp;k<(agemortsup-2);k++)
6141: 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]);
6142:
6143:
6144: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6145: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6146:
6147: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6148: stepm, weightopt,\
6149: model,imx,p,matcov,agemortsup);
6150:
6151: free_vector(lsurv,1,AGESUP);
6152: free_vector(lpop,1,AGESUP);
6153: free_vector(tpop,1,AGESUP);
1.136 brouard 6154: #ifdef GSL
6155: free_ivector(cens,1,n);
6156: free_vector(agecens,1,n);
6157: free_ivector(dcwave,1,n);
6158: free_matrix(ximort,1,NDIM,1,NDIM);
6159: #endif
1.126 brouard 6160: } /* Endof if mle==-3 */
6161:
6162: else{ /* For mle >=1 */
1.132 brouard 6163: globpr=0;/* debug */
6164: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6165: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6166: for (k=1; k<=npar;k++)
6167: printf(" %d %8.5f",k,p[k]);
6168: printf("\n");
6169: globpr=1; /* to print the contributions */
6170: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6171: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6172: for (k=1; k<=npar;k++)
6173: printf(" %d %8.5f",k,p[k]);
6174: printf("\n");
6175: if(mle>=1){ /* Could be 1 or 2 */
6176: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6177: }
6178:
6179: /*--------- results files --------------*/
6180: 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);
6181:
6182:
6183: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6184: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6185: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6186: for(i=1,jk=1; i <=nlstate; i++){
6187: for(k=1; k <=(nlstate+ndeath); k++){
6188: if (k != i) {
6189: printf("%d%d ",i,k);
6190: fprintf(ficlog,"%d%d ",i,k);
6191: fprintf(ficres,"%1d%1d ",i,k);
6192: for(j=1; j <=ncovmodel; j++){
6193: printf("%lf ",p[jk]);
6194: fprintf(ficlog,"%lf ",p[jk]);
6195: fprintf(ficres,"%lf ",p[jk]);
6196: jk++;
6197: }
6198: printf("\n");
6199: fprintf(ficlog,"\n");
6200: fprintf(ficres,"\n");
6201: }
6202: }
6203: }
6204: if(mle!=0){
6205: /* Computing hessian and covariance matrix */
6206: ftolhess=ftol; /* Usually correct */
6207: hesscov(matcov, p, npar, delti, ftolhess, func);
6208: }
6209: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6210: printf("# Scales (for hessian or gradient estimation)\n");
6211: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6212: for(i=1,jk=1; i <=nlstate; i++){
6213: for(j=1; j <=nlstate+ndeath; j++){
6214: if (j!=i) {
6215: fprintf(ficres,"%1d%1d",i,j);
6216: printf("%1d%1d",i,j);
6217: fprintf(ficlog,"%1d%1d",i,j);
6218: for(k=1; k<=ncovmodel;k++){
6219: printf(" %.5e",delti[jk]);
6220: fprintf(ficlog," %.5e",delti[jk]);
6221: fprintf(ficres," %.5e",delti[jk]);
6222: jk++;
6223: }
6224: printf("\n");
6225: fprintf(ficlog,"\n");
6226: fprintf(ficres,"\n");
6227: }
6228: }
6229: }
6230:
6231: 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");
6232: if(mle>=1)
6233: 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");
6234: 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");
6235: /* # 121 Var(a12)\n\ */
6236: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6237: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6238: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6239: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6240: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6241: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6242: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6243:
6244:
6245: /* Just to have a covariance matrix which will be more understandable
6246: even is we still don't want to manage dictionary of variables
6247: */
6248: for(itimes=1;itimes<=2;itimes++){
6249: jj=0;
6250: for(i=1; i <=nlstate; i++){
6251: for(j=1; j <=nlstate+ndeath; j++){
6252: if(j==i) continue;
6253: for(k=1; k<=ncovmodel;k++){
6254: jj++;
6255: ca[0]= k+'a'-1;ca[1]='\0';
6256: if(itimes==1){
6257: if(mle>=1)
6258: printf("#%1d%1d%d",i,j,k);
6259: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6260: fprintf(ficres,"#%1d%1d%d",i,j,k);
6261: }else{
6262: if(mle>=1)
6263: printf("%1d%1d%d",i,j,k);
6264: fprintf(ficlog,"%1d%1d%d",i,j,k);
6265: fprintf(ficres,"%1d%1d%d",i,j,k);
6266: }
6267: ll=0;
6268: for(li=1;li <=nlstate; li++){
6269: for(lj=1;lj <=nlstate+ndeath; lj++){
6270: if(lj==li) continue;
6271: for(lk=1;lk<=ncovmodel;lk++){
6272: ll++;
6273: if(ll<=jj){
6274: cb[0]= lk +'a'-1;cb[1]='\0';
6275: if(ll<jj){
6276: if(itimes==1){
6277: if(mle>=1)
6278: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6279: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6280: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6281: }else{
6282: if(mle>=1)
6283: printf(" %.5e",matcov[jj][ll]);
6284: fprintf(ficlog," %.5e",matcov[jj][ll]);
6285: fprintf(ficres," %.5e",matcov[jj][ll]);
6286: }
6287: }else{
6288: if(itimes==1){
6289: if(mle>=1)
6290: printf(" Var(%s%1d%1d)",ca,i,j);
6291: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6292: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6293: }else{
6294: if(mle>=1)
6295: printf(" %.5e",matcov[jj][ll]);
6296: fprintf(ficlog," %.5e",matcov[jj][ll]);
6297: fprintf(ficres," %.5e",matcov[jj][ll]);
6298: }
6299: }
6300: }
6301: } /* end lk */
6302: } /* end lj */
6303: } /* end li */
6304: if(mle>=1)
6305: printf("\n");
6306: fprintf(ficlog,"\n");
6307: fprintf(ficres,"\n");
6308: numlinepar++;
6309: } /* end k*/
6310: } /*end j */
6311: } /* end i */
6312: } /* end itimes */
6313:
6314: fflush(ficlog);
6315: fflush(ficres);
6316:
6317: while((c=getc(ficpar))=='#' && c!= EOF){
6318: ungetc(c,ficpar);
6319: fgets(line, MAXLINE, ficpar);
1.141 brouard 6320: fputs(line,stdout);
1.126 brouard 6321: fputs(line,ficparo);
6322: }
6323: ungetc(c,ficpar);
6324:
6325: estepm=0;
6326: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6327: if (estepm==0 || estepm < stepm) estepm=stepm;
6328: if (fage <= 2) {
6329: bage = ageminpar;
6330: fage = agemaxpar;
6331: }
6332:
6333: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6334: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6335: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6336:
6337: while((c=getc(ficpar))=='#' && c!= EOF){
6338: ungetc(c,ficpar);
6339: fgets(line, MAXLINE, ficpar);
1.141 brouard 6340: fputs(line,stdout);
1.126 brouard 6341: fputs(line,ficparo);
6342: }
6343: ungetc(c,ficpar);
6344:
6345: fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
6346: 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);
6347: 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);
6348: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6349: 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);
6350:
6351: while((c=getc(ficpar))=='#' && c!= EOF){
6352: ungetc(c,ficpar);
6353: fgets(line, MAXLINE, ficpar);
1.141 brouard 6354: fputs(line,stdout);
1.126 brouard 6355: fputs(line,ficparo);
6356: }
6357: ungetc(c,ficpar);
6358:
6359:
6360: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6361: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6362:
6363: fscanf(ficpar,"pop_based=%d\n",&popbased);
6364: fprintf(ficparo,"pop_based=%d\n",popbased);
6365: fprintf(ficres,"pop_based=%d\n",popbased);
6366:
6367: while((c=getc(ficpar))=='#' && c!= EOF){
6368: ungetc(c,ficpar);
6369: fgets(line, MAXLINE, ficpar);
1.141 brouard 6370: fputs(line,stdout);
1.126 brouard 6371: fputs(line,ficparo);
6372: }
6373: ungetc(c,ficpar);
6374:
6375: 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);
6376: 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);
6377: 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);
6378: 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);
6379: 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);
6380: /* day and month of proj2 are not used but only year anproj2.*/
6381:
6382:
6383:
1.145 brouard 6384: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6385: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6386:
6387: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6388: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6389:
6390: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6391: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6392: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6393:
6394: /*------------ free_vector -------------*/
6395: /* chdir(path); */
6396:
6397: free_ivector(wav,1,imx);
6398: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6399: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6400: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6401: free_lvector(num,1,n);
6402: free_vector(agedc,1,n);
6403: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6404: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6405: fclose(ficparo);
6406: fclose(ficres);
6407:
6408:
6409: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6410: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6411: fclose(ficrespl);
6412:
1.145 brouard 6413: #ifdef FREEEXIT2
6414: #include "freeexit2.h"
6415: #endif
6416:
1.126 brouard 6417: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6418: #include "hpijx.h"
6419: fclose(ficrespij);
1.126 brouard 6420:
1.145 brouard 6421: /*-------------- Variance of one-step probabilities---*/
6422: k=1;
1.126 brouard 6423: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6424:
6425:
6426: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6427: for(i=1;i<=AGESUP;i++)
6428: for(j=1;j<=NCOVMAX;j++)
6429: for(k=1;k<=NCOVMAX;k++)
6430: probs[i][j][k]=0.;
6431:
6432: /*---------- Forecasting ------------------*/
6433: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6434: if(prevfcast==1){
6435: /* if(stepm ==1){*/
6436: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6437: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6438: /* } */
6439: /* else{ */
6440: /* erreur=108; */
6441: /* 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); */
6442: /* 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); */
6443: /* } */
6444: }
6445:
6446:
1.127 brouard 6447: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6448:
6449: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6450: /* 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",\
6451: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6452: */
1.126 brouard 6453:
1.127 brouard 6454: if (mobilav!=0) {
6455: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6456: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6457: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6458: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6459: }
1.126 brouard 6460: }
6461:
6462:
1.127 brouard 6463: /*---------- Health expectancies, no variances ------------*/
6464:
1.126 brouard 6465: strcpy(filerese,"e");
6466: strcat(filerese,fileres);
6467: if((ficreseij=fopen(filerese,"w"))==NULL) {
6468: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6469: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6470: }
6471: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6472: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6473: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6474: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6475:
6476: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6477: fprintf(ficreseij,"\n#****** ");
6478: for(j=1;j<=cptcoveff;j++) {
6479: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6480: }
6481: fprintf(ficreseij,"******\n");
6482:
6483: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6484: oldm=oldms;savm=savms;
6485: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6486:
6487: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6488: /*}*/
1.127 brouard 6489: }
6490: fclose(ficreseij);
6491:
6492:
6493: /*---------- Health expectancies and variances ------------*/
6494:
6495:
6496: strcpy(filerest,"t");
6497: strcat(filerest,fileres);
6498: if((ficrest=fopen(filerest,"w"))==NULL) {
6499: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6500: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6501: }
6502: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6503: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6504:
1.126 brouard 6505:
6506: strcpy(fileresstde,"stde");
6507: strcat(fileresstde,fileres);
6508: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6509: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6510: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6511: }
6512: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6513: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6514:
6515: strcpy(filerescve,"cve");
6516: strcat(filerescve,fileres);
6517: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6518: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6519: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6520: }
6521: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6522: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6523:
6524: strcpy(fileresv,"v");
6525: strcat(fileresv,fileres);
6526: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6527: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6528: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6529: }
6530: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6531: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6532:
1.145 brouard 6533: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6534: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6535:
6536: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6537: fprintf(ficrest,"\n#****** ");
1.126 brouard 6538: for(j=1;j<=cptcoveff;j++)
6539: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6540: fprintf(ficrest,"******\n");
6541:
6542: fprintf(ficresstdeij,"\n#****** ");
6543: fprintf(ficrescveij,"\n#****** ");
6544: for(j=1;j<=cptcoveff;j++) {
6545: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6546: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6547: }
6548: fprintf(ficresstdeij,"******\n");
6549: fprintf(ficrescveij,"******\n");
6550:
6551: fprintf(ficresvij,"\n#****** ");
6552: for(j=1;j<=cptcoveff;j++)
6553: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6554: fprintf(ficresvij,"******\n");
6555:
6556: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6557: oldm=oldms;savm=savms;
1.127 brouard 6558: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6559: /*
6560: */
6561: /* goto endfree; */
1.126 brouard 6562:
6563: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6564: pstamp(ficrest);
1.145 brouard 6565:
6566:
1.128 brouard 6567: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6568: oldm=oldms;savm=savms; /* Segmentation fault */
6569: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);
6570: 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 6571: if(vpopbased==1)
6572: 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);
6573: else
6574: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6575: fprintf(ficrest,"# Age e.. (std) ");
6576: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6577: fprintf(ficrest,"\n");
1.126 brouard 6578:
1.128 brouard 6579: epj=vector(1,nlstate+1);
6580: for(age=bage; age <=fage ;age++){
6581: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6582: if (vpopbased==1) {
6583: if(mobilav ==0){
6584: for(i=1; i<=nlstate;i++)
6585: prlim[i][i]=probs[(int)age][i][k];
6586: }else{ /* mobilav */
6587: for(i=1; i<=nlstate;i++)
6588: prlim[i][i]=mobaverage[(int)age][i][k];
6589: }
1.126 brouard 6590: }
6591:
1.128 brouard 6592: fprintf(ficrest," %4.0f",age);
6593: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6594: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6595: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6596: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6597: }
6598: epj[nlstate+1] +=epj[j];
1.126 brouard 6599: }
6600:
1.128 brouard 6601: for(i=1, vepp=0.;i <=nlstate;i++)
6602: for(j=1;j <=nlstate;j++)
6603: vepp += vareij[i][j][(int)age];
6604: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6605: for(j=1;j <=nlstate;j++){
6606: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6607: }
6608: fprintf(ficrest,"\n");
1.126 brouard 6609: }
6610: }
6611: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6612: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6613: free_vector(epj,1,nlstate+1);
1.145 brouard 6614: /*}*/
1.126 brouard 6615: }
6616: free_vector(weight,1,n);
1.145 brouard 6617: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6618: free_imatrix(s,1,maxwav+1,1,n);
6619: free_matrix(anint,1,maxwav,1,n);
6620: free_matrix(mint,1,maxwav,1,n);
6621: free_ivector(cod,1,n);
6622: free_ivector(tab,1,NCOVMAX);
6623: fclose(ficresstdeij);
6624: fclose(ficrescveij);
6625: fclose(ficresvij);
6626: fclose(ficrest);
6627: fclose(ficpar);
6628:
6629: /*------- Variance of period (stable) prevalence------*/
6630:
6631: strcpy(fileresvpl,"vpl");
6632: strcat(fileresvpl,fileres);
6633: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6634: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6635: exit(0);
6636: }
6637: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6638:
1.145 brouard 6639: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6640: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6641:
6642: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6643: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6644: for(j=1;j<=cptcoveff;j++)
6645: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6646: fprintf(ficresvpl,"******\n");
6647:
6648: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6649: oldm=oldms;savm=savms;
6650: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6651: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6652: /*}*/
1.126 brouard 6653: }
6654:
6655: fclose(ficresvpl);
6656:
6657: /*---------- End : free ----------------*/
6658: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6659: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6660: } /* mle==-3 arrives here for freeing */
1.131 brouard 6661: endfree:
1.141 brouard 6662: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6663: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6664: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6665: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6666: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6667: free_matrix(covar,0,NCOVMAX,1,n);
6668: free_matrix(matcov,1,npar,1,npar);
6669: /*free_vector(delti,1,npar);*/
6670: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6671: free_matrix(agev,1,maxwav,1,imx);
6672: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6673:
1.145 brouard 6674: free_ivector(ncodemax,1,NCOVMAX);
6675: free_ivector(Tvar,1,NCOVMAX);
6676: free_ivector(Tprod,1,NCOVMAX);
6677: free_ivector(Tvaraff,1,NCOVMAX);
6678: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6679:
6680: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6681: free_imatrix(codtab,1,100,1,10);
6682: fflush(fichtm);
6683: fflush(ficgp);
6684:
6685:
6686: if((nberr >0) || (nbwarn>0)){
6687: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6688: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6689: }else{
6690: printf("End of Imach\n");
6691: fprintf(ficlog,"End of Imach\n");
6692: }
6693: printf("See log file on %s\n",filelog);
6694: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6695: /*(void) gettimeofday(&end_time,&tzp);*/
6696: rend_time = time(NULL);
6697: end_time = *localtime(&rend_time);
6698: /* tml = *localtime(&end_time.tm_sec); */
6699: strcpy(strtend,asctime(&end_time));
1.126 brouard 6700: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6701: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6702: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6703:
1.157 brouard 6704: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6705: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6706: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6707: /* printf("Total time was %d uSec.\n", total_usecs);*/
6708: /* if(fileappend(fichtm,optionfilehtm)){ */
6709: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6710: fclose(fichtm);
6711: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6712: fclose(fichtmcov);
6713: fclose(ficgp);
6714: fclose(ficlog);
6715: /*------ End -----------*/
6716:
6717:
6718: printf("Before Current directory %s!\n",pathcd);
6719: if(chdir(pathcd) != 0)
6720: printf("Can't move to directory %s!\n",path);
6721: if(getcwd(pathcd,MAXLINE) > 0)
6722: printf("Current directory %s!\n",pathcd);
6723: /*strcat(plotcmd,CHARSEPARATOR);*/
6724: sprintf(plotcmd,"gnuplot");
1.157 brouard 6725: #ifdef _WIN32
1.126 brouard 6726: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6727: #endif
6728: if(!stat(plotcmd,&info)){
1.158 brouard 6729: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6730: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6731: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6732: }else
6733: strcpy(pplotcmd,plotcmd);
1.157 brouard 6734: #ifdef __unix
1.126 brouard 6735: strcpy(plotcmd,GNUPLOTPROGRAM);
6736: if(!stat(plotcmd,&info)){
1.158 brouard 6737: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6738: }else
6739: strcpy(pplotcmd,plotcmd);
6740: #endif
6741: }else
6742: strcpy(pplotcmd,plotcmd);
6743:
6744: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6745: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6746:
6747: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6748: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6749: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6750: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6751: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6752: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6753: }
1.158 brouard 6754: printf(" Successful, please wait...");
1.126 brouard 6755: while (z[0] != 'q') {
6756: /* chdir(path); */
1.154 brouard 6757: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6758: scanf("%s",z);
6759: /* if (z[0] == 'c') system("./imach"); */
6760: if (z[0] == 'e') {
1.158 brouard 6761: #ifdef __APPLE__
1.152 brouard 6762: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6763: #elif __linux
6764: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6765: #else
1.152 brouard 6766: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6767: #endif
6768: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6769: system(pplotcmd);
1.126 brouard 6770: }
6771: else if (z[0] == 'g') system(plotcmd);
6772: else if (z[0] == 'q') exit(0);
6773: }
6774: end:
6775: while (z[0] != 'q') {
6776: printf("\nType q for exiting: ");
6777: scanf("%s",z);
6778: }
6779: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>