Annotation of imach/src/imach.c, revision 1.159
1.159 ! brouard 1: /* $Id: imach.c,v 1.158 2014/08/27 17:11:51 brouard Exp $
1.126 brouard 2: $State: Exp $
3: $Log: imach.c,v $
1.159 ! brouard 4: Revision 1.158 2014/08/27 17:11:51 brouard
! 5: *** empty log message ***
! 6:
1.158 brouard 7: Revision 1.157 2014/08/27 16:26:55 brouard
8: Summary: Preparing windows Visual studio version
9: Author: Brouard
10:
11: In order to compile on Visual studio, time.h is now correct and time_t
12: and tm struct should be used. difftime should be used but sometimes I
13: just make the differences in raw time format (time(&now).
14: Trying to suppress #ifdef LINUX
15: Add xdg-open for __linux in order to open default browser.
16:
1.157 brouard 17: Revision 1.156 2014/08/25 20:10:10 brouard
18: *** empty log message ***
19:
1.156 brouard 20: Revision 1.155 2014/08/25 18:32:34 brouard
21: Summary: New compile, minor changes
22: Author: Brouard
23:
1.155 brouard 24: Revision 1.154 2014/06/20 17:32:08 brouard
25: Summary: Outputs now all graphs of convergence to period prevalence
26:
1.154 brouard 27: Revision 1.153 2014/06/20 16:45:46 brouard
28: Summary: If 3 live state, convergence to period prevalence on same graph
29: Author: Brouard
30:
1.153 brouard 31: Revision 1.152 2014/06/18 17:54:09 brouard
32: Summary: open browser, use gnuplot on same dir than imach if not found in the path
33:
1.152 brouard 34: Revision 1.151 2014/06/18 16:43:30 brouard
35: *** empty log message ***
36:
1.151 brouard 37: Revision 1.150 2014/06/18 16:42:35 brouard
38: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
39: Author: brouard
40:
1.150 brouard 41: Revision 1.149 2014/06/18 15:51:14 brouard
42: Summary: Some fixes in parameter files errors
43: Author: Nicolas Brouard
44:
1.149 brouard 45: Revision 1.148 2014/06/17 17:38:48 brouard
46: Summary: Nothing new
47: Author: Brouard
48:
49: Just a new packaging for OS/X version 0.98nS
50:
1.148 brouard 51: Revision 1.147 2014/06/16 10:33:11 brouard
52: *** empty log message ***
53:
1.147 brouard 54: Revision 1.146 2014/06/16 10:20:28 brouard
55: Summary: Merge
56: Author: Brouard
57:
58: Merge, before building revised version.
59:
1.146 brouard 60: Revision 1.145 2014/06/10 21:23:15 brouard
61: Summary: Debugging with valgrind
62: Author: Nicolas Brouard
63:
64: Lot of changes in order to output the results with some covariates
65: After the Edimburgh REVES conference 2014, it seems mandatory to
66: improve the code.
67: No more memory valgrind error but a lot has to be done in order to
68: continue the work of splitting the code into subroutines.
69: Also, decodemodel has been improved. Tricode is still not
70: optimal. nbcode should be improved. Documentation has been added in
71: the source code.
72:
1.144 brouard 73: Revision 1.143 2014/01/26 09:45:38 brouard
74: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
75:
76: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
77: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
78:
1.143 brouard 79: Revision 1.142 2014/01/26 03:57:36 brouard
80: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
81:
82: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
83:
1.142 brouard 84: Revision 1.141 2014/01/26 02:42:01 brouard
85: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
86:
1.141 brouard 87: Revision 1.140 2011/09/02 10:37:54 brouard
88: Summary: times.h is ok with mingw32 now.
89:
1.140 brouard 90: Revision 1.139 2010/06/14 07:50:17 brouard
91: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
92: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
93:
1.139 brouard 94: Revision 1.138 2010/04/30 18:19:40 brouard
95: *** empty log message ***
96:
1.138 brouard 97: Revision 1.137 2010/04/29 18:11:38 brouard
98: (Module): Checking covariates for more complex models
99: than V1+V2. A lot of change to be done. Unstable.
100:
1.137 brouard 101: Revision 1.136 2010/04/26 20:30:53 brouard
102: (Module): merging some libgsl code. Fixing computation
103: of likelione (using inter/intrapolation if mle = 0) in order to
104: get same likelihood as if mle=1.
105: Some cleaning of code and comments added.
106:
1.136 brouard 107: Revision 1.135 2009/10/29 15:33:14 brouard
108: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
109:
1.135 brouard 110: Revision 1.134 2009/10/29 13:18:53 brouard
111: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
112:
1.134 brouard 113: Revision 1.133 2009/07/06 10:21:25 brouard
114: just nforces
115:
1.133 brouard 116: Revision 1.132 2009/07/06 08:22:05 brouard
117: Many tings
118:
1.132 brouard 119: Revision 1.131 2009/06/20 16:22:47 brouard
120: Some dimensions resccaled
121:
1.131 brouard 122: Revision 1.130 2009/05/26 06:44:34 brouard
123: (Module): Max Covariate is now set to 20 instead of 8. A
124: lot of cleaning with variables initialized to 0. Trying to make
125: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
126:
1.130 brouard 127: Revision 1.129 2007/08/31 13:49:27 lievre
128: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
129:
1.129 lievre 130: Revision 1.128 2006/06/30 13:02:05 brouard
131: (Module): Clarifications on computing e.j
132:
1.128 brouard 133: Revision 1.127 2006/04/28 18:11:50 brouard
134: (Module): Yes the sum of survivors was wrong since
135: imach-114 because nhstepm was no more computed in the age
136: loop. Now we define nhstepma in the age loop.
137: (Module): In order to speed up (in case of numerous covariates) we
138: compute health expectancies (without variances) in a first step
139: and then all the health expectancies with variances or standard
140: deviation (needs data from the Hessian matrices) which slows the
141: computation.
142: In the future we should be able to stop the program is only health
143: expectancies and graph are needed without standard deviations.
144:
1.127 brouard 145: Revision 1.126 2006/04/28 17:23:28 brouard
146: (Module): Yes the sum of survivors was wrong since
147: imach-114 because nhstepm was no more computed in the age
148: loop. Now we define nhstepma in the age loop.
149: Version 0.98h
150:
1.126 brouard 151: Revision 1.125 2006/04/04 15:20:31 lievre
152: Errors in calculation of health expectancies. Age was not initialized.
153: Forecasting file added.
154:
155: Revision 1.124 2006/03/22 17:13:53 lievre
156: Parameters are printed with %lf instead of %f (more numbers after the comma).
157: The log-likelihood is printed in the log file
158:
159: Revision 1.123 2006/03/20 10:52:43 brouard
160: * imach.c (Module): <title> changed, corresponds to .htm file
161: name. <head> headers where missing.
162:
163: * imach.c (Module): Weights can have a decimal point as for
164: English (a comma might work with a correct LC_NUMERIC environment,
165: otherwise the weight is truncated).
166: Modification of warning when the covariates values are not 0 or
167: 1.
168: Version 0.98g
169:
170: Revision 1.122 2006/03/20 09:45:41 brouard
171: (Module): Weights can have a decimal point as for
172: English (a comma might work with a correct LC_NUMERIC environment,
173: otherwise the weight is truncated).
174: Modification of warning when the covariates values are not 0 or
175: 1.
176: Version 0.98g
177:
178: Revision 1.121 2006/03/16 17:45:01 lievre
179: * imach.c (Module): Comments concerning covariates added
180:
181: * imach.c (Module): refinements in the computation of lli if
182: status=-2 in order to have more reliable computation if stepm is
183: not 1 month. Version 0.98f
184:
185: Revision 1.120 2006/03/16 15:10:38 lievre
186: (Module): refinements in the computation of lli if
187: status=-2 in order to have more reliable computation if stepm is
188: not 1 month. Version 0.98f
189:
190: Revision 1.119 2006/03/15 17:42:26 brouard
191: (Module): Bug if status = -2, the loglikelihood was
192: computed as likelihood omitting the logarithm. Version O.98e
193:
194: Revision 1.118 2006/03/14 18:20:07 brouard
195: (Module): varevsij Comments added explaining the second
196: table of variances if popbased=1 .
197: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
198: (Module): Function pstamp added
199: (Module): Version 0.98d
200:
201: Revision 1.117 2006/03/14 17:16:22 brouard
202: (Module): varevsij Comments added explaining the second
203: table of variances if popbased=1 .
204: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
205: (Module): Function pstamp added
206: (Module): Version 0.98d
207:
208: Revision 1.116 2006/03/06 10:29:27 brouard
209: (Module): Variance-covariance wrong links and
210: varian-covariance of ej. is needed (Saito).
211:
212: Revision 1.115 2006/02/27 12:17:45 brouard
213: (Module): One freematrix added in mlikeli! 0.98c
214:
215: Revision 1.114 2006/02/26 12:57:58 brouard
216: (Module): Some improvements in processing parameter
217: filename with strsep.
218:
219: Revision 1.113 2006/02/24 14:20:24 brouard
220: (Module): Memory leaks checks with valgrind and:
221: datafile was not closed, some imatrix were not freed and on matrix
222: allocation too.
223:
224: Revision 1.112 2006/01/30 09:55:26 brouard
225: (Module): Back to gnuplot.exe instead of wgnuplot.exe
226:
227: Revision 1.111 2006/01/25 20:38:18 brouard
228: (Module): Lots of cleaning and bugs added (Gompertz)
229: (Module): Comments can be added in data file. Missing date values
230: can be a simple dot '.'.
231:
232: Revision 1.110 2006/01/25 00:51:50 brouard
233: (Module): Lots of cleaning and bugs added (Gompertz)
234:
235: Revision 1.109 2006/01/24 19:37:15 brouard
236: (Module): Comments (lines starting with a #) are allowed in data.
237:
238: Revision 1.108 2006/01/19 18:05:42 lievre
239: Gnuplot problem appeared...
240: To be fixed
241:
242: Revision 1.107 2006/01/19 16:20:37 brouard
243: Test existence of gnuplot in imach path
244:
245: Revision 1.106 2006/01/19 13:24:36 brouard
246: Some cleaning and links added in html output
247:
248: Revision 1.105 2006/01/05 20:23:19 lievre
249: *** empty log message ***
250:
251: Revision 1.104 2005/09/30 16:11:43 lievre
252: (Module): sump fixed, loop imx fixed, and simplifications.
253: (Module): If the status is missing at the last wave but we know
254: that the person is alive, then we can code his/her status as -2
255: (instead of missing=-1 in earlier versions) and his/her
256: contributions to the likelihood is 1 - Prob of dying from last
257: health status (= 1-p13= p11+p12 in the easiest case of somebody in
258: the healthy state at last known wave). Version is 0.98
259:
260: Revision 1.103 2005/09/30 15:54:49 lievre
261: (Module): sump fixed, loop imx fixed, and simplifications.
262:
263: Revision 1.102 2004/09/15 17:31:30 brouard
264: Add the possibility to read data file including tab characters.
265:
266: Revision 1.101 2004/09/15 10:38:38 brouard
267: Fix on curr_time
268:
269: Revision 1.100 2004/07/12 18:29:06 brouard
270: Add version for Mac OS X. Just define UNIX in Makefile
271:
272: Revision 1.99 2004/06/05 08:57:40 brouard
273: *** empty log message ***
274:
275: Revision 1.98 2004/05/16 15:05:56 brouard
276: New version 0.97 . First attempt to estimate force of mortality
277: directly from the data i.e. without the need of knowing the health
278: state at each age, but using a Gompertz model: log u =a + b*age .
279: This is the basic analysis of mortality and should be done before any
280: other analysis, in order to test if the mortality estimated from the
281: cross-longitudinal survey is different from the mortality estimated
282: from other sources like vital statistic data.
283:
284: The same imach parameter file can be used but the option for mle should be -3.
285:
1.133 brouard 286: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 287: former routines in order to include the new code within the former code.
288:
289: The output is very simple: only an estimate of the intercept and of
290: the slope with 95% confident intervals.
291:
292: Current limitations:
293: A) Even if you enter covariates, i.e. with the
294: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
295: B) There is no computation of Life Expectancy nor Life Table.
296:
297: Revision 1.97 2004/02/20 13:25:42 lievre
298: Version 0.96d. Population forecasting command line is (temporarily)
299: suppressed.
300:
301: Revision 1.96 2003/07/15 15:38:55 brouard
302: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
303: rewritten within the same printf. Workaround: many printfs.
304:
305: Revision 1.95 2003/07/08 07:54:34 brouard
306: * imach.c (Repository):
307: (Repository): Using imachwizard code to output a more meaningful covariance
308: matrix (cov(a12,c31) instead of numbers.
309:
310: Revision 1.94 2003/06/27 13:00:02 brouard
311: Just cleaning
312:
313: Revision 1.93 2003/06/25 16:33:55 brouard
314: (Module): On windows (cygwin) function asctime_r doesn't
315: exist so I changed back to asctime which exists.
316: (Module): Version 0.96b
317:
318: Revision 1.92 2003/06/25 16:30:45 brouard
319: (Module): On windows (cygwin) function asctime_r doesn't
320: exist so I changed back to asctime which exists.
321:
322: Revision 1.91 2003/06/25 15:30:29 brouard
323: * imach.c (Repository): Duplicated warning errors corrected.
324: (Repository): Elapsed time after each iteration is now output. It
325: helps to forecast when convergence will be reached. Elapsed time
326: is stamped in powell. We created a new html file for the graphs
327: concerning matrix of covariance. It has extension -cov.htm.
328:
329: Revision 1.90 2003/06/24 12:34:15 brouard
330: (Module): Some bugs corrected for windows. Also, when
331: mle=-1 a template is output in file "or"mypar.txt with the design
332: of the covariance matrix to be input.
333:
334: Revision 1.89 2003/06/24 12:30:52 brouard
335: (Module): Some bugs corrected for windows. Also, when
336: mle=-1 a template is output in file "or"mypar.txt with the design
337: of the covariance matrix to be input.
338:
339: Revision 1.88 2003/06/23 17:54:56 brouard
340: * 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.
341:
342: Revision 1.87 2003/06/18 12:26:01 brouard
343: Version 0.96
344:
345: Revision 1.86 2003/06/17 20:04:08 brouard
346: (Module): Change position of html and gnuplot routines and added
347: routine fileappend.
348:
349: Revision 1.85 2003/06/17 13:12:43 brouard
350: * imach.c (Repository): Check when date of death was earlier that
351: current date of interview. It may happen when the death was just
352: prior to the death. In this case, dh was negative and likelihood
353: was wrong (infinity). We still send an "Error" but patch by
354: assuming that the date of death was just one stepm after the
355: interview.
356: (Repository): Because some people have very long ID (first column)
357: we changed int to long in num[] and we added a new lvector for
358: memory allocation. But we also truncated to 8 characters (left
359: truncation)
360: (Repository): No more line truncation errors.
361:
362: Revision 1.84 2003/06/13 21:44:43 brouard
363: * imach.c (Repository): Replace "freqsummary" at a correct
364: place. It differs from routine "prevalence" which may be called
365: many times. Probs is memory consuming and must be used with
366: parcimony.
367: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
368:
369: Revision 1.83 2003/06/10 13:39:11 lievre
370: *** empty log message ***
371:
372: Revision 1.82 2003/06/05 15:57:20 brouard
373: Add log in imach.c and fullversion number is now printed.
374:
375: */
376: /*
377: Interpolated Markov Chain
378:
379: Short summary of the programme:
380:
381: This program computes Healthy Life Expectancies from
382: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
383: first survey ("cross") where individuals from different ages are
384: interviewed on their health status or degree of disability (in the
385: case of a health survey which is our main interest) -2- at least a
386: second wave of interviews ("longitudinal") which measure each change
387: (if any) in individual health status. Health expectancies are
388: computed from the time spent in each health state according to a
389: model. More health states you consider, more time is necessary to reach the
390: Maximum Likelihood of the parameters involved in the model. The
391: simplest model is the multinomial logistic model where pij is the
392: probability to be observed in state j at the second wave
393: conditional to be observed in state i at the first wave. Therefore
394: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
395: 'age' is age and 'sex' is a covariate. If you want to have a more
396: complex model than "constant and age", you should modify the program
397: where the markup *Covariates have to be included here again* invites
398: you to do it. More covariates you add, slower the
399: convergence.
400:
401: The advantage of this computer programme, compared to a simple
402: multinomial logistic model, is clear when the delay between waves is not
403: identical for each individual. Also, if a individual missed an
404: intermediate interview, the information is lost, but taken into
405: account using an interpolation or extrapolation.
406:
407: hPijx is the probability to be observed in state i at age x+h
408: conditional to the observed state i at age x. The delay 'h' can be
409: split into an exact number (nh*stepm) of unobserved intermediate
410: states. This elementary transition (by month, quarter,
411: semester or year) is modelled as a multinomial logistic. The hPx
412: matrix is simply the matrix product of nh*stepm elementary matrices
413: and the contribution of each individual to the likelihood is simply
414: hPijx.
415:
416: Also this programme outputs the covariance matrix of the parameters but also
417: of the life expectancies. It also computes the period (stable) prevalence.
418:
1.133 brouard 419: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
420: Institut national d'études démographiques, Paris.
1.126 brouard 421: This software have been partly granted by Euro-REVES, a concerted action
422: from the European Union.
423: It is copyrighted identically to a GNU software product, ie programme and
424: software can be distributed freely for non commercial use. Latest version
425: can be accessed at http://euroreves.ined.fr/imach .
426:
427: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
428: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
429:
430: **********************************************************************/
431: /*
432: main
433: read parameterfile
434: read datafile
435: concatwav
436: freqsummary
437: if (mle >= 1)
438: mlikeli
439: print results files
440: if mle==1
441: computes hessian
442: read end of parameter file: agemin, agemax, bage, fage, estepm
443: begin-prev-date,...
444: open gnuplot file
445: open html file
1.145 brouard 446: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
447: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
448: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
449: freexexit2 possible for memory heap.
450:
451: h Pij x | pij_nom ficrestpij
452: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
453: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
454: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
455:
456: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
457: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
458: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
459: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
460: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
461:
1.126 brouard 462: forecasting if prevfcast==1 prevforecast call prevalence()
463: health expectancies
464: Variance-covariance of DFLE
465: prevalence()
466: movingaverage()
467: varevsij()
468: if popbased==1 varevsij(,popbased)
469: total life expectancies
470: Variance of period (stable) prevalence
471: end
472: */
473:
474:
475:
476:
477: #include <math.h>
478: #include <stdio.h>
479: #include <stdlib.h>
480: #include <string.h>
1.159 ! brouard 481:
! 482: #ifdef _WIN32
! 483: #include <io.h>
! 484: #else
1.126 brouard 485: #include <unistd.h>
1.159 ! brouard 486: #endif
1.126 brouard 487:
488: #include <limits.h>
489: #include <sys/types.h>
490: #include <sys/stat.h>
491: #include <errno.h>
1.159 ! brouard 492: /* extern int errno; */
1.126 brouard 493:
1.157 brouard 494: /* #ifdef LINUX */
495: /* #include <time.h> */
496: /* #include "timeval.h" */
497: /* #else */
498: /* #include <sys/time.h> */
499: /* #endif */
500:
1.126 brouard 501: #include <time.h>
502:
1.136 brouard 503: #ifdef GSL
504: #include <gsl/gsl_errno.h>
505: #include <gsl/gsl_multimin.h>
506: #endif
507:
1.126 brouard 508: /* #include <libintl.h> */
509: /* #define _(String) gettext (String) */
510:
1.141 brouard 511: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 512:
513: #define GNUPLOTPROGRAM "gnuplot"
514: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
515: #define FILENAMELENGTH 132
516:
517: #define GLOCK_ERROR_NOPATH -1 /* empty path */
518: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
519:
1.144 brouard 520: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
521: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 522:
523: #define NINTERVMAX 8
1.144 brouard 524: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
525: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
526: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 527: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 528: #define MAXN 20000
1.144 brouard 529: #define YEARM 12. /**< Number of months per year */
1.126 brouard 530: #define AGESUP 130
531: #define AGEBASE 40
1.144 brouard 532: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.157 brouard 533: #ifdef _WIN32
534: #define DIRSEPARATOR '\\'
535: #define CHARSEPARATOR "\\"
536: #define ODIRSEPARATOR '/'
537: #else
1.126 brouard 538: #define DIRSEPARATOR '/'
539: #define CHARSEPARATOR "/"
540: #define ODIRSEPARATOR '\\'
541: #endif
542:
1.159 ! brouard 543: /* $Id: imach.c,v 1.158 2014/08/27 17:11:51 brouard Exp $ */
1.126 brouard 544: /* $State: Exp $ */
545:
1.157 brouard 546: 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.159 ! brouard 547: char fullversion[]="$Revision: 1.158 $ $Date: 2014/08/27 17:11:51 $";
1.126 brouard 548: char strstart[80];
549: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 550: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 551: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 552: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
553: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
554: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
555: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
556: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
557: int cptcovprodnoage=0; /**< Number of covariate products without age */
558: int cptcoveff=0; /* Total number of covariates to vary for printing results */
559: int cptcov=0; /* Working variable */
1.126 brouard 560: int npar=NPARMAX;
561: int nlstate=2; /* Number of live states */
562: int ndeath=1; /* Number of dead states */
1.130 brouard 563: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 564: int popbased=0;
565:
566: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 567: int maxwav=0; /* Maxim number of waves */
568: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
569: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
570: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 571: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 572: int mle=1, weightopt=0;
1.126 brouard 573: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
574: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
575: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
576: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130 brouard 577: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 578: double **matprod2(); /* test */
1.126 brouard 579: double **oldm, **newm, **savm; /* Working pointers to matrices */
580: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 581: /*FILE *fic ; */ /* Used in readdata only */
582: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 583: FILE *ficlog, *ficrespow;
1.130 brouard 584: int globpr=0; /* Global variable for printing or not */
1.126 brouard 585: double fretone; /* Only one call to likelihood */
1.130 brouard 586: long ipmx=0; /* Number of contributions */
1.126 brouard 587: double sw; /* Sum of weights */
588: char filerespow[FILENAMELENGTH];
589: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
590: FILE *ficresilk;
591: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
592: FILE *ficresprobmorprev;
593: FILE *fichtm, *fichtmcov; /* Html File */
594: FILE *ficreseij;
595: char filerese[FILENAMELENGTH];
596: FILE *ficresstdeij;
597: char fileresstde[FILENAMELENGTH];
598: FILE *ficrescveij;
599: char filerescve[FILENAMELENGTH];
600: FILE *ficresvij;
601: char fileresv[FILENAMELENGTH];
602: FILE *ficresvpl;
603: char fileresvpl[FILENAMELENGTH];
604: char title[MAXLINE];
605: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
606: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
607: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
608: char command[FILENAMELENGTH];
609: int outcmd=0;
610:
611: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
612:
613: char filelog[FILENAMELENGTH]; /* Log file */
614: char filerest[FILENAMELENGTH];
615: char fileregp[FILENAMELENGTH];
616: char popfile[FILENAMELENGTH];
617:
618: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
619:
1.157 brouard 620: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
621: /* struct timezone tzp; */
622: /* extern int gettimeofday(); */
623: struct tm tml, *gmtime(), *localtime();
624:
625: extern time_t time();
626:
627: struct tm start_time, end_time, curr_time, last_time, forecast_time;
628: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
629: struct tm tm;
630:
1.126 brouard 631: char strcurr[80], strfor[80];
632:
633: char *endptr;
634: long lval;
635: double dval;
636:
637: #define NR_END 1
638: #define FREE_ARG char*
639: #define FTOL 1.0e-10
640:
641: #define NRANSI
642: #define ITMAX 200
643:
644: #define TOL 2.0e-4
645:
646: #define CGOLD 0.3819660
647: #define ZEPS 1.0e-10
648: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
649:
650: #define GOLD 1.618034
651: #define GLIMIT 100.0
652: #define TINY 1.0e-20
653:
654: static double maxarg1,maxarg2;
655: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
656: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
657:
658: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
659: #define rint(a) floor(a+0.5)
660:
661: static double sqrarg;
662: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
663: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
664: int agegomp= AGEGOMP;
665:
666: int imx;
667: int stepm=1;
668: /* Stepm, step in month: minimum step interpolation*/
669:
670: int estepm;
671: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
672:
673: int m,nb;
674: long *num;
675: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
676: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
677: double **pmmij, ***probs;
678: double *ageexmed,*agecens;
679: double dateintmean=0;
680:
681: double *weight;
682: int **s; /* Status */
1.141 brouard 683: double *agedc;
1.145 brouard 684: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 685: * covar=matrix(0,NCOVMAX,1,n);
686: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
687: double idx;
688: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 689: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 690: int **codtab; /**< codtab=imatrix(1,100,1,10); */
691: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 692: double *lsurv, *lpop, *tpop;
693:
1.143 brouard 694: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
695: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 696:
697: /**************** split *************************/
698: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
699: {
700: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
701: the name of the file (name), its extension only (ext) and its first part of the name (finame)
702: */
703: char *ss; /* pointer */
704: int l1, l2; /* length counters */
705:
706: l1 = strlen(path ); /* length of path */
707: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
708: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
709: if ( ss == NULL ) { /* no directory, so determine current directory */
710: strcpy( name, path ); /* we got the fullname name because no directory */
711: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
712: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
713: /* get current working directory */
714: /* extern char* getcwd ( char *buf , int len);*/
715: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
716: return( GLOCK_ERROR_GETCWD );
717: }
718: /* got dirc from getcwd*/
719: printf(" DIRC = %s \n",dirc);
720: } else { /* strip direcotry from path */
721: ss++; /* after this, the filename */
722: l2 = strlen( ss ); /* length of filename */
723: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
724: strcpy( name, ss ); /* save file name */
725: strncpy( dirc, path, l1 - l2 ); /* now the directory */
726: dirc[l1-l2] = 0; /* add zero */
727: printf(" DIRC2 = %s \n",dirc);
728: }
729: /* We add a separator at the end of dirc if not exists */
730: l1 = strlen( dirc ); /* length of directory */
731: if( dirc[l1-1] != DIRSEPARATOR ){
732: dirc[l1] = DIRSEPARATOR;
733: dirc[l1+1] = 0;
734: printf(" DIRC3 = %s \n",dirc);
735: }
736: ss = strrchr( name, '.' ); /* find last / */
737: if (ss >0){
738: ss++;
739: strcpy(ext,ss); /* save extension */
740: l1= strlen( name);
741: l2= strlen(ss)+1;
742: strncpy( finame, name, l1-l2);
743: finame[l1-l2]= 0;
744: }
745:
746: return( 0 ); /* we're done */
747: }
748:
749:
750: /******************************************/
751:
752: void replace_back_to_slash(char *s, char*t)
753: {
754: int i;
755: int lg=0;
756: i=0;
757: lg=strlen(t);
758: for(i=0; i<= lg; i++) {
759: (s[i] = t[i]);
760: if (t[i]== '\\') s[i]='/';
761: }
762: }
763:
1.132 brouard 764: char *trimbb(char *out, char *in)
1.137 brouard 765: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 766: char *s;
767: s=out;
768: while (*in != '\0'){
1.137 brouard 769: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 770: in++;
771: }
772: *out++ = *in++;
773: }
774: *out='\0';
775: return s;
776: }
777:
1.145 brouard 778: char *cutl(char *blocc, char *alocc, char *in, char occ)
779: {
780: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
781: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
782: gives blocc="abcdef2ghi" and alocc="j".
783: If occ is not found blocc is null and alocc is equal to in. Returns blocc
784: */
785: char *s, *t, *bl;
786: t=in;s=in;
787: while ((*in != occ) && (*in != '\0')){
788: *alocc++ = *in++;
789: }
790: if( *in == occ){
791: *(alocc)='\0';
792: s=++in;
793: }
794:
795: if (s == t) {/* occ not found */
796: *(alocc-(in-s))='\0';
797: in=s;
798: }
799: while ( *in != '\0'){
800: *blocc++ = *in++;
801: }
802:
803: *blocc='\0';
804: return t;
805: }
1.137 brouard 806: char *cutv(char *blocc, char *alocc, char *in, char occ)
807: {
808: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
809: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
810: gives blocc="abcdef2ghi" and alocc="j".
811: If occ is not found blocc is null and alocc is equal to in. Returns alocc
812: */
813: char *s, *t;
814: t=in;s=in;
815: while (*in != '\0'){
816: while( *in == occ){
817: *blocc++ = *in++;
818: s=in;
819: }
820: *blocc++ = *in++;
821: }
822: if (s == t) /* occ not found */
823: *(blocc-(in-s))='\0';
824: else
825: *(blocc-(in-s)-1)='\0';
826: in=s;
827: while ( *in != '\0'){
828: *alocc++ = *in++;
829: }
830:
831: *alocc='\0';
832: return s;
833: }
834:
1.126 brouard 835: int nbocc(char *s, char occ)
836: {
837: int i,j=0;
838: int lg=20;
839: i=0;
840: lg=strlen(s);
841: for(i=0; i<= lg; i++) {
842: if (s[i] == occ ) j++;
843: }
844: return j;
845: }
846:
1.137 brouard 847: /* void cutv(char *u,char *v, char*t, char occ) */
848: /* { */
849: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
850: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
851: /* gives u="abcdef2ghi" and v="j" *\/ */
852: /* int i,lg,j,p=0; */
853: /* i=0; */
854: /* lg=strlen(t); */
855: /* for(j=0; j<=lg-1; j++) { */
856: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
857: /* } */
1.126 brouard 858:
1.137 brouard 859: /* for(j=0; j<p; j++) { */
860: /* (u[j] = t[j]); */
861: /* } */
862: /* u[p]='\0'; */
1.126 brouard 863:
1.137 brouard 864: /* for(j=0; j<= lg; j++) { */
865: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
866: /* } */
867: /* } */
1.126 brouard 868:
869: /********************** nrerror ********************/
870:
871: void nrerror(char error_text[])
872: {
873: fprintf(stderr,"ERREUR ...\n");
874: fprintf(stderr,"%s\n",error_text);
875: exit(EXIT_FAILURE);
876: }
877: /*********************** vector *******************/
878: double *vector(int nl, int nh)
879: {
880: double *v;
881: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
882: if (!v) nrerror("allocation failure in vector");
883: return v-nl+NR_END;
884: }
885:
886: /************************ free vector ******************/
887: void free_vector(double*v, int nl, int nh)
888: {
889: free((FREE_ARG)(v+nl-NR_END));
890: }
891:
892: /************************ivector *******************************/
893: int *ivector(long nl,long nh)
894: {
895: int *v;
896: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
897: if (!v) nrerror("allocation failure in ivector");
898: return v-nl+NR_END;
899: }
900:
901: /******************free ivector **************************/
902: void free_ivector(int *v, long nl, long nh)
903: {
904: free((FREE_ARG)(v+nl-NR_END));
905: }
906:
907: /************************lvector *******************************/
908: long *lvector(long nl,long nh)
909: {
910: long *v;
911: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
912: if (!v) nrerror("allocation failure in ivector");
913: return v-nl+NR_END;
914: }
915:
916: /******************free lvector **************************/
917: void free_lvector(long *v, long nl, long nh)
918: {
919: free((FREE_ARG)(v+nl-NR_END));
920: }
921:
922: /******************* imatrix *******************************/
923: int **imatrix(long nrl, long nrh, long ncl, long nch)
924: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
925: {
926: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
927: int **m;
928:
929: /* allocate pointers to rows */
930: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
931: if (!m) nrerror("allocation failure 1 in matrix()");
932: m += NR_END;
933: m -= nrl;
934:
935:
936: /* allocate rows and set pointers to them */
937: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
938: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
939: m[nrl] += NR_END;
940: m[nrl] -= ncl;
941:
942: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
943:
944: /* return pointer to array of pointers to rows */
945: return m;
946: }
947:
948: /****************** free_imatrix *************************/
949: void free_imatrix(m,nrl,nrh,ncl,nch)
950: int **m;
951: long nch,ncl,nrh,nrl;
952: /* free an int matrix allocated by imatrix() */
953: {
954: free((FREE_ARG) (m[nrl]+ncl-NR_END));
955: free((FREE_ARG) (m+nrl-NR_END));
956: }
957:
958: /******************* matrix *******************************/
959: double **matrix(long nrl, long nrh, long ncl, long nch)
960: {
961: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
962: double **m;
963:
964: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
965: if (!m) nrerror("allocation failure 1 in matrix()");
966: m += NR_END;
967: m -= nrl;
968:
969: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
970: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
971: m[nrl] += NR_END;
972: m[nrl] -= ncl;
973:
974: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
975: return m;
1.145 brouard 976: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
977: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
978: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 979: */
980: }
981:
982: /*************************free matrix ************************/
983: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
984: {
985: free((FREE_ARG)(m[nrl]+ncl-NR_END));
986: free((FREE_ARG)(m+nrl-NR_END));
987: }
988:
989: /******************* ma3x *******************************/
990: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
991: {
992: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
993: double ***m;
994:
995: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
996: if (!m) nrerror("allocation failure 1 in matrix()");
997: m += NR_END;
998: m -= nrl;
999:
1000: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1001: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1002: m[nrl] += NR_END;
1003: m[nrl] -= ncl;
1004:
1005: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1006:
1007: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1008: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1009: m[nrl][ncl] += NR_END;
1010: m[nrl][ncl] -= nll;
1011: for (j=ncl+1; j<=nch; j++)
1012: m[nrl][j]=m[nrl][j-1]+nlay;
1013:
1014: for (i=nrl+1; i<=nrh; i++) {
1015: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1016: for (j=ncl+1; j<=nch; j++)
1017: m[i][j]=m[i][j-1]+nlay;
1018: }
1019: return m;
1020: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1021: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1022: */
1023: }
1024:
1025: /*************************free ma3x ************************/
1026: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1027: {
1028: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1029: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1030: free((FREE_ARG)(m+nrl-NR_END));
1031: }
1032:
1033: /*************** function subdirf ***********/
1034: char *subdirf(char fileres[])
1035: {
1036: /* Caution optionfilefiname is hidden */
1037: strcpy(tmpout,optionfilefiname);
1038: strcat(tmpout,"/"); /* Add to the right */
1039: strcat(tmpout,fileres);
1040: return tmpout;
1041: }
1042:
1043: /*************** function subdirf2 ***********/
1044: char *subdirf2(char fileres[], char *preop)
1045: {
1046:
1047: /* Caution optionfilefiname is hidden */
1048: strcpy(tmpout,optionfilefiname);
1049: strcat(tmpout,"/");
1050: strcat(tmpout,preop);
1051: strcat(tmpout,fileres);
1052: return tmpout;
1053: }
1054:
1055: /*************** function subdirf3 ***********/
1056: char *subdirf3(char fileres[], char *preop, char *preop2)
1057: {
1058:
1059: /* Caution optionfilefiname is hidden */
1060: strcpy(tmpout,optionfilefiname);
1061: strcat(tmpout,"/");
1062: strcat(tmpout,preop);
1063: strcat(tmpout,preop2);
1064: strcat(tmpout,fileres);
1065: return tmpout;
1066: }
1067:
1068: /***************** f1dim *************************/
1069: extern int ncom;
1070: extern double *pcom,*xicom;
1071: extern double (*nrfunc)(double []);
1072:
1073: double f1dim(double x)
1074: {
1075: int j;
1076: double f;
1077: double *xt;
1078:
1079: xt=vector(1,ncom);
1080: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1081: f=(*nrfunc)(xt);
1082: free_vector(xt,1,ncom);
1083: return f;
1084: }
1085:
1086: /*****************brent *************************/
1087: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1088: {
1089: int iter;
1090: double a,b,d,etemp;
1.159 ! brouard 1091: double fu=0,fv,fw,fx;
1.126 brouard 1092: double ftemp;
1093: double p,q,r,tol1,tol2,u,v,w,x,xm;
1094: double e=0.0;
1095:
1096: a=(ax < cx ? ax : cx);
1097: b=(ax > cx ? ax : cx);
1098: x=w=v=bx;
1099: fw=fv=fx=(*f)(x);
1100: for (iter=1;iter<=ITMAX;iter++) {
1101: xm=0.5*(a+b);
1102: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1103: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1104: printf(".");fflush(stdout);
1105: fprintf(ficlog,".");fflush(ficlog);
1106: #ifdef DEBUG
1107: 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);
1108: 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);
1109: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1110: #endif
1111: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1112: *xmin=x;
1113: return fx;
1114: }
1115: ftemp=fu;
1116: if (fabs(e) > tol1) {
1117: r=(x-w)*(fx-fv);
1118: q=(x-v)*(fx-fw);
1119: p=(x-v)*q-(x-w)*r;
1120: q=2.0*(q-r);
1121: if (q > 0.0) p = -p;
1122: q=fabs(q);
1123: etemp=e;
1124: e=d;
1125: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1126: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1127: else {
1128: d=p/q;
1129: u=x+d;
1130: if (u-a < tol2 || b-u < tol2)
1131: d=SIGN(tol1,xm-x);
1132: }
1133: } else {
1134: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1135: }
1136: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1137: fu=(*f)(u);
1138: if (fu <= fx) {
1139: if (u >= x) a=x; else b=x;
1140: SHFT(v,w,x,u)
1141: SHFT(fv,fw,fx,fu)
1142: } else {
1143: if (u < x) a=u; else b=u;
1144: if (fu <= fw || w == x) {
1145: v=w;
1146: w=u;
1147: fv=fw;
1148: fw=fu;
1149: } else if (fu <= fv || v == x || v == w) {
1150: v=u;
1151: fv=fu;
1152: }
1153: }
1154: }
1155: nrerror("Too many iterations in brent");
1156: *xmin=x;
1157: return fx;
1158: }
1159:
1160: /****************** mnbrak ***********************/
1161:
1162: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1163: double (*func)(double))
1164: {
1165: double ulim,u,r,q, dum;
1166: double fu;
1167:
1168: *fa=(*func)(*ax);
1169: *fb=(*func)(*bx);
1170: if (*fb > *fa) {
1171: SHFT(dum,*ax,*bx,dum)
1172: SHFT(dum,*fb,*fa,dum)
1173: }
1174: *cx=(*bx)+GOLD*(*bx-*ax);
1175: *fc=(*func)(*cx);
1176: while (*fb > *fc) {
1177: r=(*bx-*ax)*(*fb-*fc);
1178: q=(*bx-*cx)*(*fb-*fa);
1179: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1180: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
1181: ulim=(*bx)+GLIMIT*(*cx-*bx);
1182: if ((*bx-u)*(u-*cx) > 0.0) {
1183: fu=(*func)(u);
1184: } else if ((*cx-u)*(u-ulim) > 0.0) {
1185: fu=(*func)(u);
1186: if (fu < *fc) {
1187: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1188: SHFT(*fb,*fc,fu,(*func)(u))
1189: }
1190: } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
1191: u=ulim;
1192: fu=(*func)(u);
1193: } else {
1194: u=(*cx)+GOLD*(*cx-*bx);
1195: fu=(*func)(u);
1196: }
1197: SHFT(*ax,*bx,*cx,u)
1198: SHFT(*fa,*fb,*fc,fu)
1199: }
1200: }
1201:
1202: /*************** linmin ************************/
1203:
1204: int ncom;
1205: double *pcom,*xicom;
1206: double (*nrfunc)(double []);
1207:
1208: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1209: {
1210: double brent(double ax, double bx, double cx,
1211: double (*f)(double), double tol, double *xmin);
1212: double f1dim(double x);
1213: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1214: double *fc, double (*func)(double));
1215: int j;
1216: double xx,xmin,bx,ax;
1217: double fx,fb,fa;
1218:
1219: ncom=n;
1220: pcom=vector(1,n);
1221: xicom=vector(1,n);
1222: nrfunc=func;
1223: for (j=1;j<=n;j++) {
1224: pcom[j]=p[j];
1225: xicom[j]=xi[j];
1226: }
1227: ax=0.0;
1228: xx=1.0;
1229: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
1230: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
1231: #ifdef DEBUG
1232: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1233: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1234: #endif
1235: for (j=1;j<=n;j++) {
1236: xi[j] *= xmin;
1237: p[j] += xi[j];
1238: }
1239: free_vector(xicom,1,n);
1240: free_vector(pcom,1,n);
1241: }
1242:
1243: char *asc_diff_time(long time_sec, char ascdiff[])
1244: {
1245: long sec_left, days, hours, minutes;
1246: days = (time_sec) / (60*60*24);
1247: sec_left = (time_sec) % (60*60*24);
1248: hours = (sec_left) / (60*60) ;
1249: sec_left = (sec_left) %(60*60);
1250: minutes = (sec_left) /60;
1251: sec_left = (sec_left) % (60);
1.141 brouard 1252: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1.126 brouard 1253: return ascdiff;
1254: }
1255:
1256: /*************** powell ************************/
1257: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1258: double (*func)(double []))
1259: {
1260: void linmin(double p[], double xi[], int n, double *fret,
1261: double (*func)(double []));
1262: int i,ibig,j;
1263: double del,t,*pt,*ptt,*xit;
1264: double fp,fptt;
1265: double *xits;
1266: int niterf, itmp;
1267:
1268: pt=vector(1,n);
1269: ptt=vector(1,n);
1270: xit=vector(1,n);
1271: xits=vector(1,n);
1272: *fret=(*func)(p);
1273: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1274: rcurr_time = time(NULL);
1.126 brouard 1275: for (*iter=1;;++(*iter)) {
1276: fp=(*fret);
1277: ibig=0;
1278: del=0.0;
1.157 brouard 1279: rlast_time=rcurr_time;
1280: /* (void) gettimeofday(&curr_time,&tzp); */
1281: rcurr_time = time(NULL);
1282: curr_time = *localtime(&rcurr_time);
1283: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1284: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1285: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1286: for (i=1;i<=n;i++) {
1287: printf(" %d %.12f",i, p[i]);
1288: fprintf(ficlog," %d %.12lf",i, p[i]);
1289: fprintf(ficrespow," %.12lf", p[i]);
1290: }
1291: printf("\n");
1292: fprintf(ficlog,"\n");
1293: fprintf(ficrespow,"\n");fflush(ficrespow);
1294: if(*iter <=3){
1.157 brouard 1295: tml = *localtime(&rcurr_time);
1296: strcpy(strcurr,asctime(&tml));
1.126 brouard 1297: /* asctime_r(&tm,strcurr); */
1.157 brouard 1298: rforecast_time=rcurr_time;
1.126 brouard 1299: itmp = strlen(strcurr);
1300: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1301: strcurr[itmp-1]='\0';
1.157 brouard 1302: printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1303: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1304: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1305: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1306: forecast_time = *localtime(&rforecast_time);
1.126 brouard 1307: /* asctime_r(&tmf,strfor); */
1.157 brouard 1308: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1309: itmp = strlen(strfor);
1310: if(strfor[itmp-1]=='\n')
1311: strfor[itmp-1]='\0';
1.157 brouard 1312: 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);
1313: 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 1314: }
1315: }
1316: for (i=1;i<=n;i++) {
1317: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1318: fptt=(*fret);
1319: #ifdef DEBUG
1320: printf("fret=%lf \n",*fret);
1321: fprintf(ficlog,"fret=%lf \n",*fret);
1322: #endif
1323: printf("%d",i);fflush(stdout);
1324: fprintf(ficlog,"%d",i);fflush(ficlog);
1325: linmin(p,xit,n,fret,func);
1326: if (fabs(fptt-(*fret)) > del) {
1327: del=fabs(fptt-(*fret));
1328: ibig=i;
1329: }
1330: #ifdef DEBUG
1331: printf("%d %.12e",i,(*fret));
1332: fprintf(ficlog,"%d %.12e",i,(*fret));
1333: for (j=1;j<=n;j++) {
1334: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1335: printf(" x(%d)=%.12e",j,xit[j]);
1336: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1337: }
1338: for(j=1;j<=n;j++) {
1339: printf(" p=%.12e",p[j]);
1340: fprintf(ficlog," p=%.12e",p[j]);
1341: }
1342: printf("\n");
1343: fprintf(ficlog,"\n");
1344: #endif
1345: }
1346: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1347: #ifdef DEBUG
1348: int k[2],l;
1349: k[0]=1;
1350: k[1]=-1;
1351: printf("Max: %.12e",(*func)(p));
1352: fprintf(ficlog,"Max: %.12e",(*func)(p));
1353: for (j=1;j<=n;j++) {
1354: printf(" %.12e",p[j]);
1355: fprintf(ficlog," %.12e",p[j]);
1356: }
1357: printf("\n");
1358: fprintf(ficlog,"\n");
1359: for(l=0;l<=1;l++) {
1360: for (j=1;j<=n;j++) {
1361: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1362: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1363: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1364: }
1365: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1366: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1367: }
1368: #endif
1369:
1370:
1371: free_vector(xit,1,n);
1372: free_vector(xits,1,n);
1373: free_vector(ptt,1,n);
1374: free_vector(pt,1,n);
1375: return;
1376: }
1377: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1378: for (j=1;j<=n;j++) {
1379: ptt[j]=2.0*p[j]-pt[j];
1380: xit[j]=p[j]-pt[j];
1381: pt[j]=p[j];
1382: }
1383: fptt=(*func)(ptt);
1384: if (fptt < fp) {
1385: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
1386: if (t < 0.0) {
1387: linmin(p,xit,n,fret,func);
1388: for (j=1;j<=n;j++) {
1389: xi[j][ibig]=xi[j][n];
1390: xi[j][n]=xit[j];
1391: }
1392: #ifdef DEBUG
1393: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1394: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1395: for(j=1;j<=n;j++){
1396: printf(" %.12e",xit[j]);
1397: fprintf(ficlog," %.12e",xit[j]);
1398: }
1399: printf("\n");
1400: fprintf(ficlog,"\n");
1401: #endif
1402: }
1403: }
1404: }
1405: }
1406:
1407: /**** Prevalence limit (stable or period prevalence) ****************/
1408:
1409: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1410: {
1411: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1412: matrix by transitions matrix until convergence is reached */
1413:
1414: int i, ii,j,k;
1415: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1416: /* double **matprod2(); */ /* test */
1.131 brouard 1417: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1418: double **newm;
1419: double agefin, delaymax=50 ; /* Max number of years to converge */
1420:
1421: for (ii=1;ii<=nlstate+ndeath;ii++)
1422: for (j=1;j<=nlstate+ndeath;j++){
1423: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1424: }
1425:
1426: cov[1]=1.;
1427:
1428: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1429: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1430: newm=savm;
1431: /* Covariates have to be included here again */
1.138 brouard 1432: cov[2]=agefin;
1433:
1434: for (k=1; k<=cptcovn;k++) {
1435: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1436: /*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 1437: }
1.145 brouard 1438: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1439: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1440: /* 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 1441:
1442: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1443: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1444: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1445: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1446: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1447: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1448:
1.126 brouard 1449: savm=oldm;
1450: oldm=newm;
1451: maxmax=0.;
1452: for(j=1;j<=nlstate;j++){
1453: min=1.;
1454: max=0.;
1455: for(i=1; i<=nlstate; i++) {
1456: sumnew=0;
1457: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1458: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1459: /*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 1460: max=FMAX(max,prlim[i][j]);
1461: min=FMIN(min,prlim[i][j]);
1462: }
1463: maxmin=max-min;
1464: maxmax=FMAX(maxmax,maxmin);
1465: }
1466: if(maxmax < ftolpl){
1467: return prlim;
1468: }
1469: }
1470: }
1471:
1472: /*************** transition probabilities ***************/
1473:
1474: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1475: {
1.138 brouard 1476: /* According to parameters values stored in x and the covariate's values stored in cov,
1477: computes the probability to be observed in state j being in state i by appying the
1478: model to the ncovmodel covariates (including constant and age).
1479: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1480: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1481: ncth covariate in the global vector x is given by the formula:
1482: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1483: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1484: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1485: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1486: Outputs ps[i][j] the probability to be observed in j being in j according to
1487: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1488: */
1489: double s1, lnpijopii;
1.126 brouard 1490: /*double t34;*/
1491: int i,j,j1, nc, ii, jj;
1492:
1493: for(i=1; i<= nlstate; i++){
1494: for(j=1; j<i;j++){
1.138 brouard 1495: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1496: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1497: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1498: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1499: }
1.138 brouard 1500: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1501: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1502: }
1503: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1504: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1505: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1506: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1507: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1508: }
1.138 brouard 1509: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1510: }
1511: }
1512:
1513: for(i=1; i<= nlstate; i++){
1514: s1=0;
1.131 brouard 1515: for(j=1; j<i; j++){
1.138 brouard 1516: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1517: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1518: }
1519: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1520: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1521: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1522: }
1.138 brouard 1523: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1524: ps[i][i]=1./(s1+1.);
1.138 brouard 1525: /* Computing other pijs */
1.126 brouard 1526: for(j=1; j<i; j++)
1527: ps[i][j]= exp(ps[i][j])*ps[i][i];
1528: for(j=i+1; j<=nlstate+ndeath; j++)
1529: ps[i][j]= exp(ps[i][j])*ps[i][i];
1530: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1531: } /* end i */
1532:
1533: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1534: for(jj=1; jj<= nlstate+ndeath; jj++){
1535: ps[ii][jj]=0;
1536: ps[ii][ii]=1;
1537: }
1538: }
1539:
1.145 brouard 1540:
1541: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1542: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1543: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1544: /* } */
1545: /* printf("\n "); */
1546: /* } */
1547: /* printf("\n ");printf("%lf ",cov[2]);*/
1548: /*
1.126 brouard 1549: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1550: goto end;*/
1551: return ps;
1552: }
1553:
1554: /**************** Product of 2 matrices ******************/
1555:
1.145 brouard 1556: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1557: {
1558: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1559: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1560: /* in, b, out are matrice of pointers which should have been initialized
1561: before: only the contents of out is modified. The function returns
1562: a pointer to pointers identical to out */
1.145 brouard 1563: int i, j, k;
1.126 brouard 1564: for(i=nrl; i<= nrh; i++)
1.145 brouard 1565: for(k=ncolol; k<=ncoloh; k++){
1566: out[i][k]=0.;
1567: for(j=ncl; j<=nch; j++)
1568: out[i][k] +=in[i][j]*b[j][k];
1569: }
1.126 brouard 1570: return out;
1571: }
1572:
1573:
1574: /************* Higher Matrix Product ***************/
1575:
1576: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1577: {
1578: /* Computes the transition matrix starting at age 'age' over
1579: 'nhstepm*hstepm*stepm' months (i.e. until
1580: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1581: nhstepm*hstepm matrices.
1582: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1583: (typically every 2 years instead of every month which is too big
1584: for the memory).
1585: Model is determined by parameters x and covariates have to be
1586: included manually here.
1587:
1588: */
1589:
1590: int i, j, d, h, k;
1.131 brouard 1591: double **out, cov[NCOVMAX+1];
1.126 brouard 1592: double **newm;
1593:
1594: /* Hstepm could be zero and should return the unit matrix */
1595: for (i=1;i<=nlstate+ndeath;i++)
1596: for (j=1;j<=nlstate+ndeath;j++){
1597: oldm[i][j]=(i==j ? 1.0 : 0.0);
1598: po[i][j][0]=(i==j ? 1.0 : 0.0);
1599: }
1600: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1601: for(h=1; h <=nhstepm; h++){
1602: for(d=1; d <=hstepm; d++){
1603: newm=savm;
1604: /* Covariates have to be included here again */
1605: cov[1]=1.;
1606: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1607: for (k=1; k<=cptcovn;k++)
1608: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1609: for (k=1; k<=cptcovage;k++)
1610: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1611: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1612: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1613:
1614:
1615: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1616: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1617: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1618: pmij(pmmij,cov,ncovmodel,x,nlstate));
1619: savm=oldm;
1620: oldm=newm;
1621: }
1622: for(i=1; i<=nlstate+ndeath; i++)
1623: for(j=1;j<=nlstate+ndeath;j++) {
1624: po[i][j][h]=newm[i][j];
1.128 brouard 1625: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1626: }
1.128 brouard 1627: /*printf("h=%d ",h);*/
1.126 brouard 1628: } /* end h */
1.128 brouard 1629: /* printf("\n H=%d \n",h); */
1.126 brouard 1630: return po;
1631: }
1632:
1633:
1634: /*************** log-likelihood *************/
1635: double func( double *x)
1636: {
1637: int i, ii, j, k, mi, d, kk;
1.131 brouard 1638: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1639: double **out;
1640: double sw; /* Sum of weights */
1641: double lli; /* Individual log likelihood */
1642: int s1, s2;
1643: double bbh, survp;
1644: long ipmx;
1645: /*extern weight */
1646: /* We are differentiating ll according to initial status */
1647: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1648: /*for(i=1;i<imx;i++)
1649: printf(" %d\n",s[4][i]);
1650: */
1651: cov[1]=1.;
1652:
1653: for(k=1; k<=nlstate; k++) ll[k]=0.;
1654:
1655: if(mle==1){
1656: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1657: /* Computes the values of the ncovmodel covariates of the model
1658: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1659: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1660: to be observed in j being in i according to the model.
1661: */
1.145 brouard 1662: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1663: cov[2+k]=covar[Tvar[k]][i];
1664: }
1.137 brouard 1665: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1666: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1667: has been calculated etc */
1.126 brouard 1668: for(mi=1; mi<= wav[i]-1; mi++){
1669: for (ii=1;ii<=nlstate+ndeath;ii++)
1670: for (j=1;j<=nlstate+ndeath;j++){
1671: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1672: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1673: }
1674: for(d=0; d<dh[mi][i]; d++){
1675: newm=savm;
1676: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1677: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1678: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1679: }
1680: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1681: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1682: savm=oldm;
1683: oldm=newm;
1684: } /* end mult */
1685:
1686: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1687: /* But now since version 0.9 we anticipate for bias at large stepm.
1688: * If stepm is larger than one month (smallest stepm) and if the exact delay
1689: * (in months) between two waves is not a multiple of stepm, we rounded to
1690: * the nearest (and in case of equal distance, to the lowest) interval but now
1691: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1692: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1693: * probability in order to take into account the bias as a fraction of the way
1694: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1695: * -stepm/2 to stepm/2 .
1696: * For stepm=1 the results are the same as for previous versions of Imach.
1697: * For stepm > 1 the results are less biased than in previous versions.
1698: */
1699: s1=s[mw[mi][i]][i];
1700: s2=s[mw[mi+1][i]][i];
1701: bbh=(double)bh[mi][i]/(double)stepm;
1702: /* bias bh is positive if real duration
1703: * is higher than the multiple of stepm and negative otherwise.
1704: */
1705: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1706: if( s2 > nlstate){
1707: /* i.e. if s2 is a death state and if the date of death is known
1708: then the contribution to the likelihood is the probability to
1709: die between last step unit time and current step unit time,
1710: which is also equal to probability to die before dh
1711: minus probability to die before dh-stepm .
1712: In version up to 0.92 likelihood was computed
1713: as if date of death was unknown. Death was treated as any other
1714: health state: the date of the interview describes the actual state
1715: and not the date of a change in health state. The former idea was
1716: to consider that at each interview the state was recorded
1717: (healthy, disable or death) and IMaCh was corrected; but when we
1718: introduced the exact date of death then we should have modified
1719: the contribution of an exact death to the likelihood. This new
1720: contribution is smaller and very dependent of the step unit
1721: stepm. It is no more the probability to die between last interview
1722: and month of death but the probability to survive from last
1723: interview up to one month before death multiplied by the
1724: probability to die within a month. Thanks to Chris
1725: Jackson for correcting this bug. Former versions increased
1726: mortality artificially. The bad side is that we add another loop
1727: which slows down the processing. The difference can be up to 10%
1728: lower mortality.
1729: */
1730: lli=log(out[s1][s2] - savm[s1][s2]);
1731:
1732:
1733: } else if (s2==-2) {
1734: for (j=1,survp=0. ; j<=nlstate; j++)
1735: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1736: /*survp += out[s1][j]; */
1737: lli= log(survp);
1738: }
1739:
1740: else if (s2==-4) {
1741: for (j=3,survp=0. ; j<=nlstate; j++)
1742: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1743: lli= log(survp);
1744: }
1745:
1746: else if (s2==-5) {
1747: for (j=1,survp=0. ; j<=2; j++)
1748: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1749: lli= log(survp);
1750: }
1751:
1752: else{
1753: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1754: /* 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 */
1755: }
1756: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1757: /*if(lli ==000.0)*/
1758: /*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); */
1759: ipmx +=1;
1760: sw += weight[i];
1761: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1762: } /* end of wave */
1763: } /* end of individual */
1764: } else if(mle==2){
1765: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1766: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1767: for(mi=1; mi<= wav[i]-1; mi++){
1768: for (ii=1;ii<=nlstate+ndeath;ii++)
1769: for (j=1;j<=nlstate+ndeath;j++){
1770: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1771: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1772: }
1773: for(d=0; d<=dh[mi][i]; d++){
1774: newm=savm;
1775: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1776: for (kk=1; kk<=cptcovage;kk++) {
1777: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1778: }
1779: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1780: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1781: savm=oldm;
1782: oldm=newm;
1783: } /* end mult */
1784:
1785: s1=s[mw[mi][i]][i];
1786: s2=s[mw[mi+1][i]][i];
1787: bbh=(double)bh[mi][i]/(double)stepm;
1788: 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 */
1789: ipmx +=1;
1790: sw += weight[i];
1791: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1792: } /* end of wave */
1793: } /* end of individual */
1794: } else if(mle==3){ /* exponential inter-extrapolation */
1795: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1796: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1797: for(mi=1; mi<= wav[i]-1; mi++){
1798: for (ii=1;ii<=nlstate+ndeath;ii++)
1799: for (j=1;j<=nlstate+ndeath;j++){
1800: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1801: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1802: }
1803: for(d=0; d<dh[mi][i]; d++){
1804: newm=savm;
1805: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1806: for (kk=1; kk<=cptcovage;kk++) {
1807: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1808: }
1809: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1810: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1811: savm=oldm;
1812: oldm=newm;
1813: } /* end mult */
1814:
1815: s1=s[mw[mi][i]][i];
1816: s2=s[mw[mi+1][i]][i];
1817: bbh=(double)bh[mi][i]/(double)stepm;
1818: 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 */
1819: ipmx +=1;
1820: sw += weight[i];
1821: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1822: } /* end of wave */
1823: } /* end of individual */
1824: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1825: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1826: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1827: for(mi=1; mi<= wav[i]-1; mi++){
1828: for (ii=1;ii<=nlstate+ndeath;ii++)
1829: for (j=1;j<=nlstate+ndeath;j++){
1830: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1831: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1832: }
1833: for(d=0; d<dh[mi][i]; d++){
1834: newm=savm;
1835: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1836: for (kk=1; kk<=cptcovage;kk++) {
1837: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1838: }
1839:
1840: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1841: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1842: savm=oldm;
1843: oldm=newm;
1844: } /* end mult */
1845:
1846: s1=s[mw[mi][i]][i];
1847: s2=s[mw[mi+1][i]][i];
1848: if( s2 > nlstate){
1849: lli=log(out[s1][s2] - savm[s1][s2]);
1850: }else{
1851: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1852: }
1853: ipmx +=1;
1854: sw += weight[i];
1855: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1856: /* printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1857: } /* end of wave */
1858: } /* end of individual */
1859: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1860: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1861: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1862: for(mi=1; mi<= wav[i]-1; mi++){
1863: for (ii=1;ii<=nlstate+ndeath;ii++)
1864: for (j=1;j<=nlstate+ndeath;j++){
1865: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1866: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1867: }
1868: for(d=0; d<dh[mi][i]; d++){
1869: newm=savm;
1870: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1871: for (kk=1; kk<=cptcovage;kk++) {
1872: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1873: }
1874:
1875: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1876: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1877: savm=oldm;
1878: oldm=newm;
1879: } /* end mult */
1880:
1881: s1=s[mw[mi][i]][i];
1882: s2=s[mw[mi+1][i]][i];
1883: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1884: ipmx +=1;
1885: sw += weight[i];
1886: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1887: /*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]);*/
1888: } /* end of wave */
1889: } /* end of individual */
1890: } /* End of if */
1891: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1892: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1893: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1894: return -l;
1895: }
1896:
1897: /*************** log-likelihood *************/
1898: double funcone( double *x)
1899: {
1900: /* Same as likeli but slower because of a lot of printf and if */
1901: int i, ii, j, k, mi, d, kk;
1.131 brouard 1902: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1903: double **out;
1904: double lli; /* Individual log likelihood */
1905: double llt;
1906: int s1, s2;
1907: double bbh, survp;
1908: /*extern weight */
1909: /* We are differentiating ll according to initial status */
1910: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1911: /*for(i=1;i<imx;i++)
1912: printf(" %d\n",s[4][i]);
1913: */
1914: cov[1]=1.;
1915:
1916: for(k=1; k<=nlstate; k++) ll[k]=0.;
1917:
1918: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1919: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1920: for(mi=1; mi<= wav[i]-1; mi++){
1921: for (ii=1;ii<=nlstate+ndeath;ii++)
1922: for (j=1;j<=nlstate+ndeath;j++){
1923: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1924: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1925: }
1926: for(d=0; d<dh[mi][i]; d++){
1927: newm=savm;
1928: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1929: for (kk=1; kk<=cptcovage;kk++) {
1930: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1931: }
1.145 brouard 1932: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 1933: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1934: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 1935: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
1936: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 1937: savm=oldm;
1938: oldm=newm;
1939: } /* end mult */
1940:
1941: s1=s[mw[mi][i]][i];
1942: s2=s[mw[mi+1][i]][i];
1943: bbh=(double)bh[mi][i]/(double)stepm;
1944: /* bias is positive if real duration
1945: * is higher than the multiple of stepm and negative otherwise.
1946: */
1947: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1948: lli=log(out[s1][s2] - savm[s1][s2]);
1949: } else if (s2==-2) {
1950: for (j=1,survp=0. ; j<=nlstate; j++)
1951: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1952: lli= log(survp);
1953: }else if (mle==1){
1954: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1955: } else if(mle==2){
1956: 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 */
1957: } else if(mle==3){ /* exponential inter-extrapolation */
1958: 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 */
1959: } else if (mle==4){ /* mle=4 no inter-extrapolation */
1960: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 1961: } else{ /* mle=0 back to 1 */
1962: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1963: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 1964: } /* End of if */
1965: ipmx +=1;
1966: sw += weight[i];
1967: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 1968: /*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 1969: if(globpr){
1.141 brouard 1970: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 1971: %11.6f %11.6f %11.6f ", \
1972: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1973: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
1974: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
1975: llt +=ll[k]*gipmx/gsw;
1976: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1977: }
1978: fprintf(ficresilk," %10.6f\n", -llt);
1979: }
1980: } /* end of wave */
1981: } /* end of individual */
1982: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1983: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1984: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1985: if(globpr==0){ /* First time we count the contributions and weights */
1986: gipmx=ipmx;
1987: gsw=sw;
1988: }
1989: return -l;
1990: }
1991:
1992:
1993: /*************** function likelione ***********/
1994: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
1995: {
1996: /* This routine should help understanding what is done with
1997: the selection of individuals/waves and
1998: to check the exact contribution to the likelihood.
1999: Plotting could be done.
2000: */
2001: int k;
2002:
2003: if(*globpri !=0){ /* Just counts and sums, no printings */
2004: strcpy(fileresilk,"ilk");
2005: strcat(fileresilk,fileres);
2006: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2007: printf("Problem with resultfile: %s\n", fileresilk);
2008: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2009: }
2010: 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");
2011: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2012: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2013: for(k=1; k<=nlstate; k++)
2014: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2015: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2016: }
2017:
2018: *fretone=(*funcone)(p);
2019: if(*globpri !=0){
2020: fclose(ficresilk);
2021: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2022: fflush(fichtm);
2023: }
2024: return;
2025: }
2026:
2027:
2028: /*********** Maximum Likelihood Estimation ***************/
2029:
2030: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2031: {
2032: int i,j, iter;
2033: double **xi;
2034: double fret;
2035: double fretone; /* Only one call to likelihood */
2036: /* char filerespow[FILENAMELENGTH];*/
2037: xi=matrix(1,npar,1,npar);
2038: for (i=1;i<=npar;i++)
2039: for (j=1;j<=npar;j++)
2040: xi[i][j]=(i==j ? 1.0 : 0.0);
2041: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2042: strcpy(filerespow,"pow");
2043: strcat(filerespow,fileres);
2044: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2045: printf("Problem with resultfile: %s\n", filerespow);
2046: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2047: }
2048: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2049: for (i=1;i<=nlstate;i++)
2050: for(j=1;j<=nlstate+ndeath;j++)
2051: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2052: fprintf(ficrespow,"\n");
2053:
2054: powell(p,xi,npar,ftol,&iter,&fret,func);
2055:
2056: free_matrix(xi,1,npar,1,npar);
2057: fclose(ficrespow);
2058: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
2059: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2060: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2061:
2062: }
2063:
2064: /**** Computes Hessian and covariance matrix ***/
2065: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2066: {
2067: double **a,**y,*x,pd;
2068: double **hess;
2069: int i, j,jk;
2070: int *indx;
2071:
2072: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2073: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2074: void lubksb(double **a, int npar, int *indx, double b[]) ;
2075: void ludcmp(double **a, int npar, int *indx, double *d) ;
2076: double gompertz(double p[]);
2077: hess=matrix(1,npar,1,npar);
2078:
2079: printf("\nCalculation of the hessian matrix. Wait...\n");
2080: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2081: for (i=1;i<=npar;i++){
2082: printf("%d",i);fflush(stdout);
2083: fprintf(ficlog,"%d",i);fflush(ficlog);
2084:
2085: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2086:
2087: /* printf(" %f ",p[i]);
2088: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2089: }
2090:
2091: for (i=1;i<=npar;i++) {
2092: for (j=1;j<=npar;j++) {
2093: if (j>i) {
2094: printf(".%d%d",i,j);fflush(stdout);
2095: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2096: hess[i][j]=hessij(p,delti,i,j,func,npar);
2097:
2098: hess[j][i]=hess[i][j];
2099: /*printf(" %lf ",hess[i][j]);*/
2100: }
2101: }
2102: }
2103: printf("\n");
2104: fprintf(ficlog,"\n");
2105:
2106: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2107: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2108:
2109: a=matrix(1,npar,1,npar);
2110: y=matrix(1,npar,1,npar);
2111: x=vector(1,npar);
2112: indx=ivector(1,npar);
2113: for (i=1;i<=npar;i++)
2114: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2115: ludcmp(a,npar,indx,&pd);
2116:
2117: for (j=1;j<=npar;j++) {
2118: for (i=1;i<=npar;i++) x[i]=0;
2119: x[j]=1;
2120: lubksb(a,npar,indx,x);
2121: for (i=1;i<=npar;i++){
2122: matcov[i][j]=x[i];
2123: }
2124: }
2125:
2126: printf("\n#Hessian matrix#\n");
2127: fprintf(ficlog,"\n#Hessian matrix#\n");
2128: for (i=1;i<=npar;i++) {
2129: for (j=1;j<=npar;j++) {
2130: printf("%.3e ",hess[i][j]);
2131: fprintf(ficlog,"%.3e ",hess[i][j]);
2132: }
2133: printf("\n");
2134: fprintf(ficlog,"\n");
2135: }
2136:
2137: /* Recompute Inverse */
2138: for (i=1;i<=npar;i++)
2139: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2140: ludcmp(a,npar,indx,&pd);
2141:
2142: /* printf("\n#Hessian matrix recomputed#\n");
2143:
2144: for (j=1;j<=npar;j++) {
2145: for (i=1;i<=npar;i++) x[i]=0;
2146: x[j]=1;
2147: lubksb(a,npar,indx,x);
2148: for (i=1;i<=npar;i++){
2149: y[i][j]=x[i];
2150: printf("%.3e ",y[i][j]);
2151: fprintf(ficlog,"%.3e ",y[i][j]);
2152: }
2153: printf("\n");
2154: fprintf(ficlog,"\n");
2155: }
2156: */
2157:
2158: free_matrix(a,1,npar,1,npar);
2159: free_matrix(y,1,npar,1,npar);
2160: free_vector(x,1,npar);
2161: free_ivector(indx,1,npar);
2162: free_matrix(hess,1,npar,1,npar);
2163:
2164:
2165: }
2166:
2167: /*************** hessian matrix ****************/
2168: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2169: {
2170: int i;
2171: int l=1, lmax=20;
2172: double k1,k2;
1.132 brouard 2173: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2174: double res;
2175: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2176: double fx;
2177: int k=0,kmax=10;
2178: double l1;
2179:
2180: fx=func(x);
2181: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2182: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2183: l1=pow(10,l);
2184: delts=delt;
2185: for(k=1 ; k <kmax; k=k+1){
2186: delt = delta*(l1*k);
2187: p2[theta]=x[theta] +delt;
1.145 brouard 2188: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2189: p2[theta]=x[theta]-delt;
2190: k2=func(p2)-fx;
2191: /*res= (k1-2.0*fx+k2)/delt/delt; */
2192: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2193:
1.132 brouard 2194: #ifdef DEBUGHESS
1.126 brouard 2195: 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);
2196: 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);
2197: #endif
2198: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2199: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2200: k=kmax;
2201: }
2202: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2203: k=kmax; l=lmax*10.;
2204: }
2205: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2206: delts=delt;
2207: }
2208: }
2209: }
2210: delti[theta]=delts;
2211: return res;
2212:
2213: }
2214:
2215: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2216: {
2217: int i;
2218: int l=1, l1, lmax=20;
2219: double k1,k2,k3,k4,res,fx;
1.132 brouard 2220: double p2[MAXPARM+1];
1.126 brouard 2221: int k;
2222:
2223: fx=func(x);
2224: for (k=1; k<=2; k++) {
2225: for (i=1;i<=npar;i++) p2[i]=x[i];
2226: p2[thetai]=x[thetai]+delti[thetai]/k;
2227: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2228: k1=func(p2)-fx;
2229:
2230: p2[thetai]=x[thetai]+delti[thetai]/k;
2231: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2232: k2=func(p2)-fx;
2233:
2234: p2[thetai]=x[thetai]-delti[thetai]/k;
2235: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2236: k3=func(p2)-fx;
2237:
2238: p2[thetai]=x[thetai]-delti[thetai]/k;
2239: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2240: k4=func(p2)-fx;
2241: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2242: #ifdef DEBUG
2243: 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);
2244: 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);
2245: #endif
2246: }
2247: return res;
2248: }
2249:
2250: /************** Inverse of matrix **************/
2251: void ludcmp(double **a, int n, int *indx, double *d)
2252: {
2253: int i,imax,j,k;
2254: double big,dum,sum,temp;
2255: double *vv;
2256:
2257: vv=vector(1,n);
2258: *d=1.0;
2259: for (i=1;i<=n;i++) {
2260: big=0.0;
2261: for (j=1;j<=n;j++)
2262: if ((temp=fabs(a[i][j])) > big) big=temp;
2263: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2264: vv[i]=1.0/big;
2265: }
2266: for (j=1;j<=n;j++) {
2267: for (i=1;i<j;i++) {
2268: sum=a[i][j];
2269: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2270: a[i][j]=sum;
2271: }
2272: big=0.0;
2273: for (i=j;i<=n;i++) {
2274: sum=a[i][j];
2275: for (k=1;k<j;k++)
2276: sum -= a[i][k]*a[k][j];
2277: a[i][j]=sum;
2278: if ( (dum=vv[i]*fabs(sum)) >= big) {
2279: big=dum;
2280: imax=i;
2281: }
2282: }
2283: if (j != imax) {
2284: for (k=1;k<=n;k++) {
2285: dum=a[imax][k];
2286: a[imax][k]=a[j][k];
2287: a[j][k]=dum;
2288: }
2289: *d = -(*d);
2290: vv[imax]=vv[j];
2291: }
2292: indx[j]=imax;
2293: if (a[j][j] == 0.0) a[j][j]=TINY;
2294: if (j != n) {
2295: dum=1.0/(a[j][j]);
2296: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2297: }
2298: }
2299: free_vector(vv,1,n); /* Doesn't work */
2300: ;
2301: }
2302:
2303: void lubksb(double **a, int n, int *indx, double b[])
2304: {
2305: int i,ii=0,ip,j;
2306: double sum;
2307:
2308: for (i=1;i<=n;i++) {
2309: ip=indx[i];
2310: sum=b[ip];
2311: b[ip]=b[i];
2312: if (ii)
2313: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2314: else if (sum) ii=i;
2315: b[i]=sum;
2316: }
2317: for (i=n;i>=1;i--) {
2318: sum=b[i];
2319: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2320: b[i]=sum/a[i][i];
2321: }
2322: }
2323:
2324: void pstamp(FILE *fichier)
2325: {
2326: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2327: }
2328:
2329: /************ Frequencies ********************/
2330: 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[])
2331: { /* Some frequencies */
2332:
1.130 brouard 2333: int i, m, jk, k1,i1, j1, bool, z1,j;
1.126 brouard 2334: int first;
2335: double ***freq; /* Frequencies */
2336: double *pp, **prop;
2337: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2338: char fileresp[FILENAMELENGTH];
2339:
2340: pp=vector(1,nlstate);
2341: prop=matrix(1,nlstate,iagemin,iagemax+3);
2342: strcpy(fileresp,"p");
2343: strcat(fileresp,fileres);
2344: if((ficresp=fopen(fileresp,"w"))==NULL) {
2345: printf("Problem with prevalence resultfile: %s\n", fileresp);
2346: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2347: exit(0);
2348: }
2349: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2350: j1=0;
2351:
2352: j=cptcoveff;
2353: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2354:
2355: first=1;
2356:
1.145 brouard 2357: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2358: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2359: /* j1++;
2360: */
2361: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2362: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2363: scanf("%d", i);*/
2364: for (i=-5; i<=nlstate+ndeath; i++)
2365: for (jk=-5; jk<=nlstate+ndeath; jk++)
2366: for(m=iagemin; m <= iagemax+3; m++)
2367: freq[i][jk][m]=0;
1.143 brouard 2368:
2369: for (i=1; i<=nlstate; i++)
2370: for(m=iagemin; m <= iagemax+3; m++)
2371: prop[i][m]=0;
1.126 brouard 2372:
2373: dateintsum=0;
2374: k2cpt=0;
2375: for (i=1; i<=imx; i++) {
2376: bool=1;
1.144 brouard 2377: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2378: for (z1=1; z1<=cptcoveff; z1++)
2379: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2380: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2381: bool=0;
1.145 brouard 2382: /* 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",
2383: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2384: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2385: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2386: }
1.126 brouard 2387: }
1.144 brouard 2388:
1.126 brouard 2389: if (bool==1){
2390: for(m=firstpass; m<=lastpass; m++){
2391: k2=anint[m][i]+(mint[m][i]/12.);
2392: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2393: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2394: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2395: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2396: if (m<lastpass) {
2397: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2398: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2399: }
2400:
2401: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2402: dateintsum=dateintsum+k2;
2403: k2cpt++;
2404: }
2405: /*}*/
2406: }
2407: }
1.145 brouard 2408: } /* end i */
1.126 brouard 2409:
2410: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2411: pstamp(ficresp);
2412: if (cptcovn>0) {
2413: fprintf(ficresp, "\n#********** Variable ");
2414: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2415: fprintf(ficresp, "**********\n#");
1.143 brouard 2416: fprintf(ficlog, "\n#********** Variable ");
2417: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2418: fprintf(ficlog, "**********\n#");
1.126 brouard 2419: }
2420: for(i=1; i<=nlstate;i++)
2421: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2422: fprintf(ficresp, "\n");
2423:
2424: for(i=iagemin; i <= iagemax+3; i++){
2425: if(i==iagemax+3){
2426: fprintf(ficlog,"Total");
2427: }else{
2428: if(first==1){
2429: first=0;
2430: printf("See log file for details...\n");
2431: }
2432: fprintf(ficlog,"Age %d", i);
2433: }
2434: for(jk=1; jk <=nlstate ; jk++){
2435: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2436: pp[jk] += freq[jk][m][i];
2437: }
2438: for(jk=1; jk <=nlstate ; jk++){
2439: for(m=-1, pos=0; m <=0 ; m++)
2440: pos += freq[jk][m][i];
2441: if(pp[jk]>=1.e-10){
2442: if(first==1){
1.132 brouard 2443: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2444: }
2445: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2446: }else{
2447: if(first==1)
2448: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2449: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2450: }
2451: }
2452:
2453: for(jk=1; jk <=nlstate ; jk++){
2454: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2455: pp[jk] += freq[jk][m][i];
2456: }
2457: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2458: pos += pp[jk];
2459: posprop += prop[jk][i];
2460: }
2461: for(jk=1; jk <=nlstate ; jk++){
2462: if(pos>=1.e-5){
2463: if(first==1)
2464: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2465: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2466: }else{
2467: if(first==1)
2468: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2469: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2470: }
2471: if( i <= iagemax){
2472: if(pos>=1.e-5){
2473: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2474: /*probs[i][jk][j1]= pp[jk]/pos;*/
2475: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2476: }
2477: else
2478: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2479: }
2480: }
2481:
2482: for(jk=-1; jk <=nlstate+ndeath; jk++)
2483: for(m=-1; m <=nlstate+ndeath; m++)
2484: if(freq[jk][m][i] !=0 ) {
2485: if(first==1)
2486: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2487: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2488: }
2489: if(i <= iagemax)
2490: fprintf(ficresp,"\n");
2491: if(first==1)
2492: printf("Others in log...\n");
2493: fprintf(ficlog,"\n");
2494: }
1.145 brouard 2495: /*}*/
1.126 brouard 2496: }
2497: dateintmean=dateintsum/k2cpt;
2498:
2499: fclose(ficresp);
2500: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2501: free_vector(pp,1,nlstate);
2502: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2503: /* End of Freq */
2504: }
2505:
2506: /************ Prevalence ********************/
2507: 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)
2508: {
2509: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2510: in each health status at the date of interview (if between dateprev1 and dateprev2).
2511: We still use firstpass and lastpass as another selection.
2512: */
2513:
1.130 brouard 2514: int i, m, jk, k1, i1, j1, bool, z1,j;
1.126 brouard 2515: double ***freq; /* Frequencies */
2516: double *pp, **prop;
2517: double pos,posprop;
2518: double y2; /* in fractional years */
2519: int iagemin, iagemax;
1.145 brouard 2520: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2521:
2522: iagemin= (int) agemin;
2523: iagemax= (int) agemax;
2524: /*pp=vector(1,nlstate);*/
2525: prop=matrix(1,nlstate,iagemin,iagemax+3);
2526: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2527: j1=0;
2528:
1.145 brouard 2529: /*j=cptcoveff;*/
1.126 brouard 2530: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2531:
1.145 brouard 2532: first=1;
2533: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2534: /*for(i1=1; i1<=ncodemax[k1];i1++){
2535: j1++;*/
1.126 brouard 2536:
2537: for (i=1; i<=nlstate; i++)
2538: for(m=iagemin; m <= iagemax+3; m++)
2539: prop[i][m]=0.0;
2540:
2541: for (i=1; i<=imx; i++) { /* Each individual */
2542: bool=1;
2543: if (cptcovn>0) {
2544: for (z1=1; z1<=cptcoveff; z1++)
2545: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2546: bool=0;
2547: }
2548: if (bool==1) {
2549: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2550: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2551: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2552: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2553: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2554: 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);
2555: if (s[m][i]>0 && s[m][i]<=nlstate) {
2556: /*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]]);*/
2557: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2558: prop[s[m][i]][iagemax+3] += weight[i];
2559: }
2560: }
2561: } /* end selection of waves */
2562: }
2563: }
2564: for(i=iagemin; i <= iagemax+3; i++){
2565: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2566: posprop += prop[jk][i];
2567: }
1.145 brouard 2568:
1.126 brouard 2569: for(jk=1; jk <=nlstate ; jk++){
2570: if( i <= iagemax){
2571: if(posprop>=1.e-5){
2572: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2573: } else{
2574: if(first==1){
2575: first=0;
2576: 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]);
2577: }
2578: }
1.126 brouard 2579: }
2580: }/* end jk */
2581: }/* end i */
1.145 brouard 2582: /*} *//* end i1 */
2583: } /* end j1 */
1.126 brouard 2584:
2585: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2586: /*free_vector(pp,1,nlstate);*/
2587: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2588: } /* End of prevalence */
2589:
2590: /************* Waves Concatenation ***************/
2591:
2592: 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)
2593: {
2594: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2595: Death is a valid wave (if date is known).
2596: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2597: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2598: and mw[mi+1][i]. dh depends on stepm.
2599: */
2600:
2601: int i, mi, m;
2602: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2603: double sum=0., jmean=0.;*/
2604: int first;
2605: int j, k=0,jk, ju, jl;
2606: double sum=0.;
2607: first=0;
2608: jmin=1e+5;
2609: jmax=-1;
2610: jmean=0.;
2611: for(i=1; i<=imx; i++){
2612: mi=0;
2613: m=firstpass;
2614: while(s[m][i] <= nlstate){
2615: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2616: mw[++mi][i]=m;
2617: if(m >=lastpass)
2618: break;
2619: else
2620: m++;
2621: }/* end while */
2622: if (s[m][i] > nlstate){
2623: mi++; /* Death is another wave */
2624: /* if(mi==0) never been interviewed correctly before death */
2625: /* Only death is a correct wave */
2626: mw[mi][i]=m;
2627: }
2628:
2629: wav[i]=mi;
2630: if(mi==0){
2631: nbwarn++;
2632: if(first==0){
2633: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2634: first=1;
2635: }
2636: if(first==1){
2637: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2638: }
2639: } /* end mi==0 */
2640: } /* End individuals */
2641:
2642: for(i=1; i<=imx; i++){
2643: for(mi=1; mi<wav[i];mi++){
2644: if (stepm <=0)
2645: dh[mi][i]=1;
2646: else{
2647: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2648: if (agedc[i] < 2*AGESUP) {
2649: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2650: if(j==0) j=1; /* Survives at least one month after exam */
2651: else if(j<0){
2652: nberr++;
2653: 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]);
2654: j=1; /* Temporary Dangerous patch */
2655: 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);
2656: 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]);
2657: 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);
2658: }
2659: k=k+1;
2660: if (j >= jmax){
2661: jmax=j;
2662: ijmax=i;
2663: }
2664: if (j <= jmin){
2665: jmin=j;
2666: ijmin=i;
2667: }
2668: sum=sum+j;
2669: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2670: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2671: }
2672: }
2673: else{
2674: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2675: /* 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]); */
2676:
2677: k=k+1;
2678: if (j >= jmax) {
2679: jmax=j;
2680: ijmax=i;
2681: }
2682: else if (j <= jmin){
2683: jmin=j;
2684: ijmin=i;
2685: }
2686: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2687: /*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]);*/
2688: if(j<0){
2689: nberr++;
2690: 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]);
2691: 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]);
2692: }
2693: sum=sum+j;
2694: }
2695: jk= j/stepm;
2696: jl= j -jk*stepm;
2697: ju= j -(jk+1)*stepm;
2698: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2699: if(jl==0){
2700: dh[mi][i]=jk;
2701: bh[mi][i]=0;
2702: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2703: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2704: dh[mi][i]=jk+1;
2705: bh[mi][i]=ju;
2706: }
2707: }else{
2708: if(jl <= -ju){
2709: dh[mi][i]=jk;
2710: bh[mi][i]=jl; /* bias is positive if real duration
2711: * is higher than the multiple of stepm and negative otherwise.
2712: */
2713: }
2714: else{
2715: dh[mi][i]=jk+1;
2716: bh[mi][i]=ju;
2717: }
2718: if(dh[mi][i]==0){
2719: dh[mi][i]=1; /* At least one step */
2720: bh[mi][i]=ju; /* At least one step */
2721: /* 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);*/
2722: }
2723: } /* end if mle */
2724: }
2725: } /* end wave */
2726: }
2727: jmean=sum/k;
2728: 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 2729: 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 2730: }
2731:
2732: /*********** Tricode ****************************/
1.145 brouard 2733: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2734: {
1.144 brouard 2735: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2736: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2737: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2738: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2739: /* nbcode[Tvar[j]][1]=
1.144 brouard 2740: */
1.130 brouard 2741:
1.145 brouard 2742: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2743: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2744: int cptcode=0; /* Modality max of covariates j */
2745: int modmincovj=0; /* Modality min of covariates j */
2746:
2747:
1.126 brouard 2748: cptcoveff=0;
2749:
1.145 brouard 2750: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2751: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2752:
1.145 brouard 2753: /* Loop on covariates without age and products */
2754: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2755: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2756: modality of this covariate Vj*/
1.145 brouard 2757: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2758: * If product of Vn*Vm, still boolean *:
2759: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2760: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2761: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2762: modality of the nth covariate of individual i. */
1.145 brouard 2763: if (ij > modmaxcovj)
2764: modmaxcovj=ij;
2765: else if (ij < modmincovj)
2766: modmincovj=ij;
2767: if ((ij < -1) && (ij > NCOVMAX)){
2768: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2769: exit(1);
2770: }else
1.136 brouard 2771: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2772: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2773: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2774: /* getting the maximum value of the modality of the covariate
2775: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2776: female is 1, then modmaxcovj=1.*/
1.126 brouard 2777: }
1.145 brouard 2778: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2779: cptcode=modmaxcovj;
1.137 brouard 2780: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2781: /*for (i=0; i<=cptcode; i++) {*/
2782: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2783: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2784: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2785: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2786: }
2787: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2788: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2789: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2790:
1.136 brouard 2791: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2792: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2793: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2794: modmincovj=3; modmaxcovj = 7;
2795: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2796: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2797: variables V1_1 and V1_2.
2798: nbcode[Tvar[j]][ij]=k;
2799: nbcode[Tvar[j]][1]=0;
2800: nbcode[Tvar[j]][2]=1;
2801: nbcode[Tvar[j]][3]=2;
2802: */
2803: ij=1; /* ij is similar to i but can jumps over null modalities */
2804: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2805: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2806: /*recode from 0 */
1.131 brouard 2807: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2808: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2809: k is a modality. If we have model=V1+V1*sex
2810: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2811: ij++;
2812: }
2813: if (ij > ncodemax[j]) break;
1.137 brouard 2814: } /* end of loop on */
2815: } /* end of loop on modality */
2816: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2817:
1.145 brouard 2818: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2819:
1.145 brouard 2820: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2821: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2822: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2823: Ndum[ij]++;
2824: }
1.126 brouard 2825:
2826: ij=1;
1.145 brouard 2827: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2828: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2829: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2830: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2831: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2832: ij++;
1.145 brouard 2833: }else
2834: Tvaraff[ij]=0;
1.126 brouard 2835: }
1.131 brouard 2836: ij--;
1.144 brouard 2837: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2838:
1.126 brouard 2839: }
2840:
1.145 brouard 2841:
1.126 brouard 2842: /*********** Health Expectancies ****************/
2843:
1.127 brouard 2844: 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 2845:
2846: {
2847: /* Health expectancies, no variances */
2848: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2849: int nhstepma, nstepma; /* Decreasing with age */
2850: double age, agelim, hf;
2851: double ***p3mat;
2852: double eip;
2853:
2854: pstamp(ficreseij);
2855: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2856: fprintf(ficreseij,"# Age");
2857: for(i=1; i<=nlstate;i++){
2858: for(j=1; j<=nlstate;j++){
2859: fprintf(ficreseij," e%1d%1d ",i,j);
2860: }
2861: fprintf(ficreseij," e%1d. ",i);
2862: }
2863: fprintf(ficreseij,"\n");
2864:
2865:
2866: if(estepm < stepm){
2867: printf ("Problem %d lower than %d\n",estepm, stepm);
2868: }
2869: else hstepm=estepm;
2870: /* We compute the life expectancy from trapezoids spaced every estepm months
2871: * This is mainly to measure the difference between two models: for example
2872: * if stepm=24 months pijx are given only every 2 years and by summing them
2873: * we are calculating an estimate of the Life Expectancy assuming a linear
2874: * progression in between and thus overestimating or underestimating according
2875: * to the curvature of the survival function. If, for the same date, we
2876: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2877: * to compare the new estimate of Life expectancy with the same linear
2878: * hypothesis. A more precise result, taking into account a more precise
2879: * curvature will be obtained if estepm is as small as stepm. */
2880:
2881: /* For example we decided to compute the life expectancy with the smallest unit */
2882: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2883: nhstepm is the number of hstepm from age to agelim
2884: nstepm is the number of stepm from age to agelin.
2885: Look at hpijx to understand the reason of that which relies in memory size
2886: and note for a fixed period like estepm months */
2887: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2888: survival function given by stepm (the optimization length). Unfortunately it
2889: means that if the survival funtion is printed only each two years of age and if
2890: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2891: results. So we changed our mind and took the option of the best precision.
2892: */
2893: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2894:
2895: agelim=AGESUP;
2896: /* If stepm=6 months */
2897: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2898: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2899:
2900: /* nhstepm age range expressed in number of stepm */
2901: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2902: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2903: /* if (stepm >= YEARM) hstepm=1;*/
2904: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2905: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2906:
2907: for (age=bage; age<=fage; age ++){
2908: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2909: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2910: /* if (stepm >= YEARM) hstepm=1;*/
2911: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2912:
2913: /* If stepm=6 months */
2914: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2915: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2916:
2917: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2918:
2919: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2920:
2921: printf("%d|",(int)age);fflush(stdout);
2922: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2923:
2924: /* Computing expectancies */
2925: for(i=1; i<=nlstate;i++)
2926: for(j=1; j<=nlstate;j++)
2927: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2928: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2929:
2930: /* 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]);*/
2931:
2932: }
2933:
2934: fprintf(ficreseij,"%3.0f",age );
2935: for(i=1; i<=nlstate;i++){
2936: eip=0;
2937: for(j=1; j<=nlstate;j++){
2938: eip +=eij[i][j][(int)age];
2939: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2940: }
2941: fprintf(ficreseij,"%9.4f", eip );
2942: }
2943: fprintf(ficreseij,"\n");
2944:
2945: }
2946: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2947: printf("\n");
2948: fprintf(ficlog,"\n");
2949:
2950: }
2951:
1.127 brouard 2952: 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 2953:
2954: {
2955: /* Covariances of health expectancies eij and of total life expectancies according
2956: to initial status i, ei. .
2957: */
2958: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
2959: int nhstepma, nstepma; /* Decreasing with age */
2960: double age, agelim, hf;
2961: double ***p3matp, ***p3matm, ***varhe;
2962: double **dnewm,**doldm;
2963: double *xp, *xm;
2964: double **gp, **gm;
2965: double ***gradg, ***trgradg;
2966: int theta;
2967:
2968: double eip, vip;
2969:
2970: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
2971: xp=vector(1,npar);
2972: xm=vector(1,npar);
2973: dnewm=matrix(1,nlstate*nlstate,1,npar);
2974: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
2975:
2976: pstamp(ficresstdeij);
2977: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
2978: fprintf(ficresstdeij,"# Age");
2979: for(i=1; i<=nlstate;i++){
2980: for(j=1; j<=nlstate;j++)
2981: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
2982: fprintf(ficresstdeij," e%1d. ",i);
2983: }
2984: fprintf(ficresstdeij,"\n");
2985:
2986: pstamp(ficrescveij);
2987: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
2988: fprintf(ficrescveij,"# Age");
2989: for(i=1; i<=nlstate;i++)
2990: for(j=1; j<=nlstate;j++){
2991: cptj= (j-1)*nlstate+i;
2992: for(i2=1; i2<=nlstate;i2++)
2993: for(j2=1; j2<=nlstate;j2++){
2994: cptj2= (j2-1)*nlstate+i2;
2995: if(cptj2 <= cptj)
2996: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
2997: }
2998: }
2999: fprintf(ficrescveij,"\n");
3000:
3001: if(estepm < stepm){
3002: printf ("Problem %d lower than %d\n",estepm, stepm);
3003: }
3004: else hstepm=estepm;
3005: /* We compute the life expectancy from trapezoids spaced every estepm months
3006: * This is mainly to measure the difference between two models: for example
3007: * if stepm=24 months pijx are given only every 2 years and by summing them
3008: * we are calculating an estimate of the Life Expectancy assuming a linear
3009: * progression in between and thus overestimating or underestimating according
3010: * to the curvature of the survival function. If, for the same date, we
3011: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3012: * to compare the new estimate of Life expectancy with the same linear
3013: * hypothesis. A more precise result, taking into account a more precise
3014: * curvature will be obtained if estepm is as small as stepm. */
3015:
3016: /* For example we decided to compute the life expectancy with the smallest unit */
3017: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3018: nhstepm is the number of hstepm from age to agelim
3019: nstepm is the number of stepm from age to agelin.
3020: Look at hpijx to understand the reason of that which relies in memory size
3021: and note for a fixed period like estepm months */
3022: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3023: survival function given by stepm (the optimization length). Unfortunately it
3024: means that if the survival funtion is printed only each two years of age and if
3025: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3026: results. So we changed our mind and took the option of the best precision.
3027: */
3028: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3029:
3030: /* If stepm=6 months */
3031: /* nhstepm age range expressed in number of stepm */
3032: agelim=AGESUP;
3033: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3034: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3035: /* if (stepm >= YEARM) hstepm=1;*/
3036: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3037:
3038: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3039: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3040: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3041: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3042: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3043: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3044:
3045: for (age=bage; age<=fage; age ++){
3046: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3047: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3048: /* if (stepm >= YEARM) hstepm=1;*/
3049: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3050:
3051: /* If stepm=6 months */
3052: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3053: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3054:
3055: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3056:
3057: /* Computing Variances of health expectancies */
3058: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3059: decrease memory allocation */
3060: for(theta=1; theta <=npar; theta++){
3061: for(i=1; i<=npar; i++){
3062: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3063: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3064: }
3065: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3066: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3067:
3068: for(j=1; j<= nlstate; j++){
3069: for(i=1; i<=nlstate; i++){
3070: for(h=0; h<=nhstepm-1; h++){
3071: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3072: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3073: }
3074: }
3075: }
3076:
3077: for(ij=1; ij<= nlstate*nlstate; ij++)
3078: for(h=0; h<=nhstepm-1; h++){
3079: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3080: }
3081: }/* End theta */
3082:
3083:
3084: for(h=0; h<=nhstepm-1; h++)
3085: for(j=1; j<=nlstate*nlstate;j++)
3086: for(theta=1; theta <=npar; theta++)
3087: trgradg[h][j][theta]=gradg[h][theta][j];
3088:
3089:
3090: for(ij=1;ij<=nlstate*nlstate;ij++)
3091: for(ji=1;ji<=nlstate*nlstate;ji++)
3092: varhe[ij][ji][(int)age] =0.;
3093:
3094: printf("%d|",(int)age);fflush(stdout);
3095: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3096: for(h=0;h<=nhstepm-1;h++){
3097: for(k=0;k<=nhstepm-1;k++){
3098: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3099: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3100: for(ij=1;ij<=nlstate*nlstate;ij++)
3101: for(ji=1;ji<=nlstate*nlstate;ji++)
3102: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3103: }
3104: }
3105:
3106: /* Computing expectancies */
3107: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3108: for(i=1; i<=nlstate;i++)
3109: for(j=1; j<=nlstate;j++)
3110: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3111: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3112:
3113: /* 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]);*/
3114:
3115: }
3116:
3117: fprintf(ficresstdeij,"%3.0f",age );
3118: for(i=1; i<=nlstate;i++){
3119: eip=0.;
3120: vip=0.;
3121: for(j=1; j<=nlstate;j++){
3122: eip += eij[i][j][(int)age];
3123: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3124: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3125: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3126: }
3127: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3128: }
3129: fprintf(ficresstdeij,"\n");
3130:
3131: fprintf(ficrescveij,"%3.0f",age );
3132: for(i=1; i<=nlstate;i++)
3133: for(j=1; j<=nlstate;j++){
3134: cptj= (j-1)*nlstate+i;
3135: for(i2=1; i2<=nlstate;i2++)
3136: for(j2=1; j2<=nlstate;j2++){
3137: cptj2= (j2-1)*nlstate+i2;
3138: if(cptj2 <= cptj)
3139: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3140: }
3141: }
3142: fprintf(ficrescveij,"\n");
3143:
3144: }
3145: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3146: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3147: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3148: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3149: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3150: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3151: printf("\n");
3152: fprintf(ficlog,"\n");
3153:
3154: free_vector(xm,1,npar);
3155: free_vector(xp,1,npar);
3156: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3157: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3158: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3159: }
3160:
3161: /************ Variance ******************/
3162: 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[])
3163: {
3164: /* Variance of health expectancies */
3165: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3166: /* double **newm;*/
3167: double **dnewm,**doldm;
3168: double **dnewmp,**doldmp;
3169: int i, j, nhstepm, hstepm, h, nstepm ;
3170: int k, cptcode;
3171: double *xp;
3172: double **gp, **gm; /* for var eij */
3173: double ***gradg, ***trgradg; /*for var eij */
3174: double **gradgp, **trgradgp; /* for var p point j */
3175: double *gpp, *gmp; /* for var p point j */
3176: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3177: double ***p3mat;
3178: double age,agelim, hf;
3179: double ***mobaverage;
3180: int theta;
3181: char digit[4];
3182: char digitp[25];
3183:
3184: char fileresprobmorprev[FILENAMELENGTH];
3185:
3186: if(popbased==1){
3187: if(mobilav!=0)
3188: strcpy(digitp,"-populbased-mobilav-");
3189: else strcpy(digitp,"-populbased-nomobil-");
3190: }
3191: else
3192: strcpy(digitp,"-stablbased-");
3193:
3194: if (mobilav!=0) {
3195: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3196: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3197: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3198: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3199: }
3200: }
3201:
3202: strcpy(fileresprobmorprev,"prmorprev");
3203: sprintf(digit,"%-d",ij);
3204: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3205: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3206: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3207: strcat(fileresprobmorprev,fileres);
3208: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3209: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3210: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3211: }
3212: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3213:
3214: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3215: pstamp(ficresprobmorprev);
3216: 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);
3217: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3218: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3219: fprintf(ficresprobmorprev," p.%-d SE",j);
3220: for(i=1; i<=nlstate;i++)
3221: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3222: }
3223: fprintf(ficresprobmorprev,"\n");
3224: fprintf(ficgp,"\n# Routine varevsij");
3225: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3226: 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");
3227: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3228: /* } */
3229: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3230: pstamp(ficresvij);
3231: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3232: if(popbased==1)
1.128 brouard 3233: 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 3234: else
3235: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3236: fprintf(ficresvij,"# Age");
3237: for(i=1; i<=nlstate;i++)
3238: for(j=1; j<=nlstate;j++)
3239: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3240: fprintf(ficresvij,"\n");
3241:
3242: xp=vector(1,npar);
3243: dnewm=matrix(1,nlstate,1,npar);
3244: doldm=matrix(1,nlstate,1,nlstate);
3245: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3246: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3247:
3248: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3249: gpp=vector(nlstate+1,nlstate+ndeath);
3250: gmp=vector(nlstate+1,nlstate+ndeath);
3251: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3252:
3253: if(estepm < stepm){
3254: printf ("Problem %d lower than %d\n",estepm, stepm);
3255: }
3256: else hstepm=estepm;
3257: /* For example we decided to compute the life expectancy with the smallest unit */
3258: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3259: nhstepm is the number of hstepm from age to agelim
3260: nstepm is the number of stepm from age to agelin.
1.128 brouard 3261: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3262: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3263: survival function given by stepm (the optimization length). Unfortunately it
3264: means that if the survival funtion is printed every two years of age and if
3265: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3266: results. So we changed our mind and took the option of the best precision.
3267: */
3268: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3269: agelim = AGESUP;
3270: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3271: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3272: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3273: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3274: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3275: gp=matrix(0,nhstepm,1,nlstate);
3276: gm=matrix(0,nhstepm,1,nlstate);
3277:
3278:
3279: for(theta=1; theta <=npar; theta++){
3280: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3281: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3282: }
3283: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3284: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3285:
3286: if (popbased==1) {
3287: if(mobilav ==0){
3288: for(i=1; i<=nlstate;i++)
3289: prlim[i][i]=probs[(int)age][i][ij];
3290: }else{ /* mobilav */
3291: for(i=1; i<=nlstate;i++)
3292: prlim[i][i]=mobaverage[(int)age][i][ij];
3293: }
3294: }
3295:
3296: for(j=1; j<= nlstate; j++){
3297: for(h=0; h<=nhstepm; h++){
3298: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3299: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3300: }
3301: }
3302: /* This for computing probability of death (h=1 means
3303: computed over hstepm matrices product = hstepm*stepm months)
3304: as a weighted average of prlim.
3305: */
3306: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3307: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3308: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3309: }
3310: /* end probability of death */
3311:
3312: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3313: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3314: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3315: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3316:
3317: if (popbased==1) {
3318: if(mobilav ==0){
3319: for(i=1; i<=nlstate;i++)
3320: prlim[i][i]=probs[(int)age][i][ij];
3321: }else{ /* mobilav */
3322: for(i=1; i<=nlstate;i++)
3323: prlim[i][i]=mobaverage[(int)age][i][ij];
3324: }
3325: }
3326:
1.128 brouard 3327: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3328: for(h=0; h<=nhstepm; h++){
3329: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3330: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3331: }
3332: }
3333: /* This for computing probability of death (h=1 means
3334: computed over hstepm matrices product = hstepm*stepm months)
3335: as a weighted average of prlim.
3336: */
3337: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3338: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3339: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3340: }
3341: /* end probability of death */
3342:
3343: for(j=1; j<= nlstate; j++) /* vareij */
3344: for(h=0; h<=nhstepm; h++){
3345: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3346: }
3347:
3348: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3349: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3350: }
3351:
3352: } /* End theta */
3353:
3354: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3355:
3356: for(h=0; h<=nhstepm; h++) /* veij */
3357: for(j=1; j<=nlstate;j++)
3358: for(theta=1; theta <=npar; theta++)
3359: trgradg[h][j][theta]=gradg[h][theta][j];
3360:
3361: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3362: for(theta=1; theta <=npar; theta++)
3363: trgradgp[j][theta]=gradgp[theta][j];
3364:
3365:
3366: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3367: for(i=1;i<=nlstate;i++)
3368: for(j=1;j<=nlstate;j++)
3369: vareij[i][j][(int)age] =0.;
3370:
3371: for(h=0;h<=nhstepm;h++){
3372: for(k=0;k<=nhstepm;k++){
3373: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3374: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3375: for(i=1;i<=nlstate;i++)
3376: for(j=1;j<=nlstate;j++)
3377: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3378: }
3379: }
3380:
3381: /* pptj */
3382: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3383: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3384: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3385: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3386: varppt[j][i]=doldmp[j][i];
3387: /* end ppptj */
3388: /* x centered again */
3389: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3390: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3391:
3392: if (popbased==1) {
3393: if(mobilav ==0){
3394: for(i=1; i<=nlstate;i++)
3395: prlim[i][i]=probs[(int)age][i][ij];
3396: }else{ /* mobilav */
3397: for(i=1; i<=nlstate;i++)
3398: prlim[i][i]=mobaverage[(int)age][i][ij];
3399: }
3400: }
3401:
3402: /* This for computing probability of death (h=1 means
3403: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3404: as a weighted average of prlim.
3405: */
3406: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3407: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3408: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3409: }
3410: /* end probability of death */
3411:
3412: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3413: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3414: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3415: for(i=1; i<=nlstate;i++){
3416: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3417: }
3418: }
3419: fprintf(ficresprobmorprev,"\n");
3420:
3421: fprintf(ficresvij,"%.0f ",age );
3422: for(i=1; i<=nlstate;i++)
3423: for(j=1; j<=nlstate;j++){
3424: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3425: }
3426: fprintf(ficresvij,"\n");
3427: free_matrix(gp,0,nhstepm,1,nlstate);
3428: free_matrix(gm,0,nhstepm,1,nlstate);
3429: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3430: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3431: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3432: } /* End age */
3433: free_vector(gpp,nlstate+1,nlstate+ndeath);
3434: free_vector(gmp,nlstate+1,nlstate+ndeath);
3435: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3436: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3437: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3438: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3439: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3440: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3441: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3442: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3443: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3444: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3445: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3446: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3447: 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);
3448: /* 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);
3449: */
3450: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3451: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3452:
3453: free_vector(xp,1,npar);
3454: free_matrix(doldm,1,nlstate,1,nlstate);
3455: free_matrix(dnewm,1,nlstate,1,npar);
3456: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3457: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3458: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3459: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3460: fclose(ficresprobmorprev);
3461: fflush(ficgp);
3462: fflush(fichtm);
3463: } /* end varevsij */
3464:
3465: /************ Variance of prevlim ******************/
3466: 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[])
3467: {
3468: /* Variance of prevalence limit */
3469: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3470: double **newm;
3471: double **dnewm,**doldm;
3472: int i, j, nhstepm, hstepm;
3473: int k, cptcode;
3474: double *xp;
3475: double *gp, *gm;
3476: double **gradg, **trgradg;
3477: double age,agelim;
3478: int theta;
3479:
3480: pstamp(ficresvpl);
3481: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3482: fprintf(ficresvpl,"# Age");
3483: for(i=1; i<=nlstate;i++)
3484: fprintf(ficresvpl," %1d-%1d",i,i);
3485: fprintf(ficresvpl,"\n");
3486:
3487: xp=vector(1,npar);
3488: dnewm=matrix(1,nlstate,1,npar);
3489: doldm=matrix(1,nlstate,1,nlstate);
3490:
3491: hstepm=1*YEARM; /* Every year of age */
3492: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3493: agelim = AGESUP;
3494: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3495: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3496: if (stepm >= YEARM) hstepm=1;
3497: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3498: gradg=matrix(1,npar,1,nlstate);
3499: gp=vector(1,nlstate);
3500: gm=vector(1,nlstate);
3501:
3502: for(theta=1; theta <=npar; theta++){
3503: for(i=1; i<=npar; i++){ /* Computes gradient */
3504: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3505: }
3506: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3507: for(i=1;i<=nlstate;i++)
3508: gp[i] = prlim[i][i];
3509:
3510: for(i=1; i<=npar; i++) /* Computes gradient */
3511: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3512: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3513: for(i=1;i<=nlstate;i++)
3514: gm[i] = prlim[i][i];
3515:
3516: for(i=1;i<=nlstate;i++)
3517: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3518: } /* End theta */
3519:
3520: trgradg =matrix(1,nlstate,1,npar);
3521:
3522: for(j=1; j<=nlstate;j++)
3523: for(theta=1; theta <=npar; theta++)
3524: trgradg[j][theta]=gradg[theta][j];
3525:
3526: for(i=1;i<=nlstate;i++)
3527: varpl[i][(int)age] =0.;
3528: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3529: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3530: for(i=1;i<=nlstate;i++)
3531: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3532:
3533: fprintf(ficresvpl,"%.0f ",age );
3534: for(i=1; i<=nlstate;i++)
3535: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3536: fprintf(ficresvpl,"\n");
3537: free_vector(gp,1,nlstate);
3538: free_vector(gm,1,nlstate);
3539: free_matrix(gradg,1,npar,1,nlstate);
3540: free_matrix(trgradg,1,nlstate,1,npar);
3541: } /* End age */
3542:
3543: free_vector(xp,1,npar);
3544: free_matrix(doldm,1,nlstate,1,npar);
3545: free_matrix(dnewm,1,nlstate,1,nlstate);
3546:
3547: }
3548:
3549: /************ Variance of one-step probabilities ******************/
3550: 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[])
3551: {
3552: int i, j=0, i1, k1, l1, t, tj;
3553: int k2, l2, j1, z1;
3554: int k=0,l, cptcode;
1.145 brouard 3555: int first=1, first1, first2;
1.126 brouard 3556: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3557: double **dnewm,**doldm;
3558: double *xp;
3559: double *gp, *gm;
3560: double **gradg, **trgradg;
3561: double **mu;
1.145 brouard 3562: double age,agelim, cov[NCOVMAX+1];
1.126 brouard 3563: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3564: int theta;
3565: char fileresprob[FILENAMELENGTH];
3566: char fileresprobcov[FILENAMELENGTH];
3567: char fileresprobcor[FILENAMELENGTH];
3568: double ***varpij;
3569:
3570: strcpy(fileresprob,"prob");
3571: strcat(fileresprob,fileres);
3572: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3573: printf("Problem with resultfile: %s\n", fileresprob);
3574: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3575: }
3576: strcpy(fileresprobcov,"probcov");
3577: strcat(fileresprobcov,fileres);
3578: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3579: printf("Problem with resultfile: %s\n", fileresprobcov);
3580: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3581: }
3582: strcpy(fileresprobcor,"probcor");
3583: strcat(fileresprobcor,fileres);
3584: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3585: printf("Problem with resultfile: %s\n", fileresprobcor);
3586: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3587: }
3588: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3589: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3590: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3591: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3592: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3593: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3594: pstamp(ficresprob);
3595: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3596: fprintf(ficresprob,"# Age");
3597: pstamp(ficresprobcov);
3598: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3599: fprintf(ficresprobcov,"# Age");
3600: pstamp(ficresprobcor);
3601: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3602: fprintf(ficresprobcor,"# Age");
3603:
3604:
3605: for(i=1; i<=nlstate;i++)
3606: for(j=1; j<=(nlstate+ndeath);j++){
3607: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3608: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3609: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3610: }
3611: /* fprintf(ficresprob,"\n");
3612: fprintf(ficresprobcov,"\n");
3613: fprintf(ficresprobcor,"\n");
3614: */
1.131 brouard 3615: xp=vector(1,npar);
1.126 brouard 3616: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3617: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3618: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3619: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3620: first=1;
3621: fprintf(ficgp,"\n# Routine varprob");
3622: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3623: fprintf(fichtm,"\n");
3624:
3625: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3626: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3627: file %s<br>\n",optionfilehtmcov);
3628: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3629: and drawn. It helps understanding how is the covariance between two incidences.\
3630: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3631: 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. \
3632: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3633: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3634: standard deviations wide on each axis. <br>\
3635: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3636: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3637: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3638:
3639: cov[1]=1;
1.145 brouard 3640: /* tj=cptcoveff; */
3641: tj = (int) pow(2,cptcoveff);
1.126 brouard 3642: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3643: j1=0;
1.145 brouard 3644: for(j1=1; j1<=tj;j1++){
3645: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3646: /*j1++;*/
1.126 brouard 3647: if (cptcovn>0) {
3648: fprintf(ficresprob, "\n#********** Variable ");
3649: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3650: fprintf(ficresprob, "**********\n#\n");
3651: fprintf(ficresprobcov, "\n#********** Variable ");
3652: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3653: fprintf(ficresprobcov, "**********\n#\n");
3654:
3655: fprintf(ficgp, "\n#********** Variable ");
3656: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3657: fprintf(ficgp, "**********\n#\n");
3658:
3659:
3660: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3661: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3662: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3663:
3664: fprintf(ficresprobcor, "\n#********** Variable ");
3665: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3666: fprintf(ficresprobcor, "**********\n#");
3667: }
3668:
1.145 brouard 3669: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3670: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3671: gp=vector(1,(nlstate)*(nlstate+ndeath));
3672: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3673: for (age=bage; age<=fage; age ++){
3674: cov[2]=age;
3675: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3676: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3677: * 1 1 1 1 1
3678: * 2 2 1 1 1
3679: * 3 1 2 1 1
3680: */
3681: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3682: }
3683: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3684: for (k=1; k<=cptcovprod;k++)
3685: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3686:
3687:
3688: for(theta=1; theta <=npar; theta++){
3689: for(i=1; i<=npar; i++)
3690: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3691:
3692: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3693:
3694: k=0;
3695: for(i=1; i<= (nlstate); i++){
3696: for(j=1; j<=(nlstate+ndeath);j++){
3697: k=k+1;
3698: gp[k]=pmmij[i][j];
3699: }
3700: }
3701:
3702: for(i=1; i<=npar; i++)
3703: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3704:
3705: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3706: k=0;
3707: for(i=1; i<=(nlstate); i++){
3708: for(j=1; j<=(nlstate+ndeath);j++){
3709: k=k+1;
3710: gm[k]=pmmij[i][j];
3711: }
3712: }
3713:
3714: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3715: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3716: }
3717:
3718: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3719: for(theta=1; theta <=npar; theta++)
3720: trgradg[j][theta]=gradg[theta][j];
3721:
3722: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3723: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3724:
3725: pmij(pmmij,cov,ncovmodel,x,nlstate);
3726:
3727: k=0;
3728: for(i=1; i<=(nlstate); i++){
3729: for(j=1; j<=(nlstate+ndeath);j++){
3730: k=k+1;
3731: mu[k][(int) age]=pmmij[i][j];
3732: }
3733: }
3734: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3735: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3736: varpij[i][j][(int)age] = doldm[i][j];
3737:
3738: /*printf("\n%d ",(int)age);
3739: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3740: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3741: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3742: }*/
3743:
3744: fprintf(ficresprob,"\n%d ",(int)age);
3745: fprintf(ficresprobcov,"\n%d ",(int)age);
3746: fprintf(ficresprobcor,"\n%d ",(int)age);
3747:
3748: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3749: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3750: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3751: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3752: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3753: }
3754: i=0;
3755: for (k=1; k<=(nlstate);k++){
3756: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3757: i++;
1.126 brouard 3758: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3759: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3760: for (j=1; j<=i;j++){
1.145 brouard 3761: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3762: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3763: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3764: }
3765: }
3766: }/* end of loop for state */
3767: } /* end of loop for age */
1.145 brouard 3768: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3769: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3770: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3771: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3772:
1.126 brouard 3773: /* Confidence intervalle of pij */
3774: /*
1.131 brouard 3775: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3776: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3777: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3778: 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);
3779: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3780: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3781: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3782: */
3783:
3784: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3785: first1=1;first2=2;
1.126 brouard 3786: for (k2=1; k2<=(nlstate);k2++){
3787: for (l2=1; l2<=(nlstate+ndeath);l2++){
3788: if(l2==k2) continue;
3789: j=(k2-1)*(nlstate+ndeath)+l2;
3790: for (k1=1; k1<=(nlstate);k1++){
3791: for (l1=1; l1<=(nlstate+ndeath);l1++){
3792: if(l1==k1) continue;
3793: i=(k1-1)*(nlstate+ndeath)+l1;
3794: if(i<=j) continue;
3795: for (age=bage; age<=fage; age ++){
3796: if ((int)age %5==0){
3797: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3798: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3799: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3800: mu1=mu[i][(int) age]/stepm*YEARM ;
3801: mu2=mu[j][(int) age]/stepm*YEARM;
3802: c12=cv12/sqrt(v1*v2);
3803: /* Computing eigen value of matrix of covariance */
3804: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3805: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3806: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3807: if(first2==1){
3808: first1=0;
3809: 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);
3810: }
3811: 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);
3812: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3813: /* lc2=fabs(lc2); */
1.135 brouard 3814: }
3815:
1.126 brouard 3816: /* Eigen vectors */
3817: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3818: /*v21=sqrt(1.-v11*v11); *//* error */
3819: v21=(lc1-v1)/cv12*v11;
3820: v12=-v21;
3821: v22=v11;
3822: tnalp=v21/v11;
3823: if(first1==1){
3824: first1=0;
3825: 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);
3826: }
3827: 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);
3828: /*printf(fignu*/
3829: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3830: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3831: if(first==1){
3832: first=0;
3833: fprintf(ficgp,"\nset parametric;unset label");
3834: 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 3835: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3836: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3837: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3838: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3839: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3840: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3841: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3842: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3843: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3844: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3845: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3846: 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",\
3847: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3848: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3849: }else{
3850: first=0;
3851: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3852: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3853: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3854: 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",\
3855: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3856: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3857: }/* if first */
3858: } /* age mod 5 */
3859: } /* end loop age */
3860: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3861: first=1;
3862: } /*l12 */
3863: } /* k12 */
3864: } /*l1 */
3865: }/* k1 */
1.145 brouard 3866: /* } /* loop covariates */
1.126 brouard 3867: }
3868: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3869: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3870: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3871: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3872: free_vector(xp,1,npar);
3873: fclose(ficresprob);
3874: fclose(ficresprobcov);
3875: fclose(ficresprobcor);
3876: fflush(ficgp);
3877: fflush(fichtmcov);
3878: }
3879:
3880:
3881: /******************* Printing html file ***********/
3882: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3883: int lastpass, int stepm, int weightopt, char model[],\
3884: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3885: int popforecast, int estepm ,\
3886: double jprev1, double mprev1,double anprev1, \
3887: double jprev2, double mprev2,double anprev2){
3888: int jj1, k1, i1, cpt;
3889:
3890: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3891: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3892: </ul>");
3893: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3894: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3895: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3896: fprintf(fichtm,"\
3897: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3898: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3899: fprintf(fichtm,"\
3900: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3901: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3902: fprintf(fichtm,"\
1.128 brouard 3903: - (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 3904: <a href=\"%s\">%s</a> <br>\n",
3905: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3906: fprintf(fichtm,"\
3907: - Population projections by age and states: \
3908: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3909:
3910: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3911:
1.145 brouard 3912: m=pow(2,cptcoveff);
1.126 brouard 3913: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3914:
3915: jj1=0;
3916: for(k1=1; k1<=m;k1++){
3917: for(i1=1; i1<=ncodemax[k1];i1++){
3918: jj1++;
3919: if (cptcovn > 0) {
3920: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3921: for (cpt=1; cpt<=cptcoveff;cpt++)
3922: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3923: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3924: }
3925: /* Pij */
1.145 brouard 3926: 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> \
3927: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3928: /* Quasi-incidences */
3929: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 3930: 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> \
3931: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 3932: /* Period (stable) prevalence in each health state */
1.154 brouard 3933: for(cpt=1; cpt<=nlstate;cpt++){
3934: 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> \
3935: <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 3936: }
3937: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 3938: 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> \
3939: <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 3940: }
3941: } /* end i1 */
3942: }/* End k1 */
3943: fprintf(fichtm,"</ul>");
3944:
3945:
3946: fprintf(fichtm,"\
3947: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3948: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3949:
3950: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3951: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3952: fprintf(fichtm,"\
3953: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3954: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
3955:
3956: fprintf(fichtm,"\
3957: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3958: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
3959: fprintf(fichtm,"\
3960: - 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): \
3961: <a href=\"%s\">%s</a> <br>\n</li>",
3962: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
3963: fprintf(fichtm,"\
3964: - (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): \
3965: <a href=\"%s\">%s</a> <br>\n</li>",
3966: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
3967: fprintf(fichtm,"\
1.128 brouard 3968: - 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 3969: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
3970: fprintf(fichtm,"\
1.128 brouard 3971: - 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",
3972: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 3973: fprintf(fichtm,"\
3974: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
3975: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
3976:
3977: /* if(popforecast==1) fprintf(fichtm,"\n */
3978: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
3979: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
3980: /* <br>",fileres,fileres,fileres,fileres); */
3981: /* else */
3982: /* 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); */
3983: fflush(fichtm);
3984: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
3985:
1.145 brouard 3986: m=pow(2,cptcoveff);
1.126 brouard 3987: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3988:
3989: jj1=0;
3990: for(k1=1; k1<=m;k1++){
3991: for(i1=1; i1<=ncodemax[k1];i1++){
3992: jj1++;
3993: if (cptcovn > 0) {
3994: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3995: for (cpt=1; cpt<=cptcoveff;cpt++)
3996: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3997: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3998: }
3999: for(cpt=1; cpt<=nlstate;cpt++) {
4000: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4001: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4002: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4003: }
4004: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4005: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4006: true period expectancies (those weighted with period prevalences are also\
4007: drawn in addition to the population based expectancies computed using\
4008: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4009: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4010: } /* end i1 */
4011: }/* End k1 */
4012: fprintf(fichtm,"</ul>");
4013: fflush(fichtm);
4014: }
4015:
4016: /******************* Gnuplot file **************/
4017: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4018:
4019: char dirfileres[132],optfileres[132];
1.130 brouard 4020: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4021: int ng=0;
1.126 brouard 4022: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4023: /* printf("Problem with file %s",optionfilegnuplot); */
4024: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4025: /* } */
4026:
4027: /*#ifdef windows */
4028: fprintf(ficgp,"cd \"%s\" \n",pathc);
4029: /*#endif */
4030: m=pow(2,cptcoveff);
4031:
4032: strcpy(dirfileres,optionfilefiname);
4033: strcpy(optfileres,"vpl");
4034: /* 1eme*/
1.153 brouard 4035: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4036: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4037: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4038: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4039: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4040: fprintf(ficgp,"set xlabel \"Age\" \n\
4041: set ylabel \"Probability\" \n\
1.145 brouard 4042: set ter png small size 320, 240\n\
1.126 brouard 4043: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4044:
4045: for (i=1; i<= nlstate ; i ++) {
4046: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4047: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4048: }
1.145 brouard 4049: 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 4050: for (i=1; i<= nlstate ; i ++) {
4051: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4052: else fprintf(ficgp," \%%*lf (\%%*lf)");
4053: }
1.145 brouard 4054: 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 4055: for (i=1; i<= nlstate ; i ++) {
4056: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4057: else fprintf(ficgp," \%%*lf (\%%*lf)");
4058: }
1.145 brouard 4059: 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 4060: }
4061: }
4062: /*2 eme*/
1.153 brouard 4063: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4064: for (k1=1; k1<= m ; k1 ++) {
4065: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4066: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4067:
4068: for (i=1; i<= nlstate+1 ; i ++) {
4069: k=2*i;
4070: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4071: for (j=1; j<= nlstate+1 ; j ++) {
4072: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4073: else fprintf(ficgp," \%%*lf (\%%*lf)");
4074: }
4075: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4076: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4077: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4078: for (j=1; j<= nlstate+1 ; j ++) {
4079: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4080: else fprintf(ficgp," \%%*lf (\%%*lf)");
4081: }
1.145 brouard 4082: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4083: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4084: for (j=1; j<= nlstate+1 ; j ++) {
4085: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4086: else fprintf(ficgp," \%%*lf (\%%*lf)");
4087: }
1.145 brouard 4088: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4089: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4090: }
4091: }
4092:
4093: /*3eme*/
4094:
4095: for (k1=1; k1<= m ; k1 ++) {
4096: for (cpt=1; cpt<= nlstate ; cpt ++) {
4097: /* k=2+nlstate*(2*cpt-2); */
4098: k=2+(nlstate+1)*(cpt-1);
4099: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4100: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4101: 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);
4102: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4103: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4104: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4105: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4106: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4107: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4108:
4109: */
4110: for (i=1; i< nlstate ; i ++) {
4111: 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);
4112: /* 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);*/
4113:
4114: }
4115: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4116: }
4117: }
4118:
4119: /* CV preval stable (period) */
1.153 brouard 4120: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4121: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4122: k=3;
1.153 brouard 4123: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4124: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4125: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4126: set ter png small size 320, 240\n\
1.126 brouard 4127: unset log y\n\
1.153 brouard 4128: plot [%.f:%.f] ", ageminpar, agemaxpar);
4129: for (i=1; i<= nlstate ; i ++){
4130: if(i==1)
4131: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4132: else
4133: fprintf(ficgp,", '' ");
1.154 brouard 4134: l=(nlstate+ndeath)*(i-1)+1;
4135: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4136: for (j=1; j<= (nlstate-1) ; j ++)
4137: fprintf(ficgp,"+$%d",k+l+j);
4138: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4139: } /* nlstate */
4140: fprintf(ficgp,"\n");
4141: } /* end cpt state*/
4142: } /* end covariate */
1.126 brouard 4143:
4144: /* proba elementaires */
4145: for(i=1,jk=1; i <=nlstate; i++){
4146: for(k=1; k <=(nlstate+ndeath); k++){
4147: if (k != i) {
4148: for(j=1; j <=ncovmodel; j++){
4149: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4150: jk++;
4151: fprintf(ficgp,"\n");
4152: }
4153: }
4154: }
4155: }
1.145 brouard 4156: /*goto avoid;*/
1.126 brouard 4157: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4158: for(jk=1; jk <=m; jk++) {
1.145 brouard 4159: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4160: if (ng==2)
4161: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4162: else
4163: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4164: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4165: i=1;
4166: for(k2=1; k2<=nlstate; k2++) {
4167: k3=i;
4168: for(k=1; k<=(nlstate+ndeath); k++) {
4169: if (k != k2){
4170: if(ng==2)
4171: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4172: else
4173: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4174: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4175: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4176: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4177: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4178: /* ij++; */
4179: /* } */
4180: /* else */
1.126 brouard 4181: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4182: }
4183: fprintf(ficgp,")/(1");
4184:
4185: for(k1=1; k1 <=nlstate; k1++){
4186: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4187: ij=1;
4188: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4189: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4190: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4191: /* ij++; */
4192: /* } */
4193: /* else */
1.126 brouard 4194: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4195: }
4196: fprintf(ficgp,")");
4197: }
4198: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4199: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4200: i=i+ncovmodel;
4201: }
4202: } /* end k */
4203: } /* end k2 */
4204: } /* end jk */
4205: } /* end ng */
1.145 brouard 4206: avoid:
1.126 brouard 4207: fflush(ficgp);
4208: } /* end gnuplot */
4209:
4210:
4211: /*************** Moving average **************/
4212: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4213:
4214: int i, cpt, cptcod;
4215: int modcovmax =1;
4216: int mobilavrange, mob;
4217: double age;
4218:
4219: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4220: a covariate has 2 modalities */
4221: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4222:
4223: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4224: if(mobilav==1) mobilavrange=5; /* default */
4225: else mobilavrange=mobilav;
4226: for (age=bage; age<=fage; age++)
4227: for (i=1; i<=nlstate;i++)
4228: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4229: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4230: /* We keep the original values on the extreme ages bage, fage and for
4231: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4232: we use a 5 terms etc. until the borders are no more concerned.
4233: */
4234: for (mob=3;mob <=mobilavrange;mob=mob+2){
4235: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4236: for (i=1; i<=nlstate;i++){
4237: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4238: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4239: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4240: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4241: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4242: }
4243: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4244: }
4245: }
4246: }/* end age */
4247: }/* end mob */
4248: }else return -1;
4249: return 0;
4250: }/* End movingaverage */
4251:
4252:
4253: /************** Forecasting ******************/
4254: 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){
4255: /* proj1, year, month, day of starting projection
4256: agemin, agemax range of age
4257: dateprev1 dateprev2 range of dates during which prevalence is computed
4258: anproj2 year of en of projection (same day and month as proj1).
4259: */
4260: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4261: int *popage;
4262: double agec; /* generic age */
4263: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4264: double *popeffectif,*popcount;
4265: double ***p3mat;
4266: double ***mobaverage;
4267: char fileresf[FILENAMELENGTH];
4268:
4269: agelim=AGESUP;
4270: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4271:
4272: strcpy(fileresf,"f");
4273: strcat(fileresf,fileres);
4274: if((ficresf=fopen(fileresf,"w"))==NULL) {
4275: printf("Problem with forecast resultfile: %s\n", fileresf);
4276: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4277: }
4278: printf("Computing forecasting: result on file '%s' \n", fileresf);
4279: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4280:
4281: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4282:
4283: if (mobilav!=0) {
4284: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4285: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4286: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4287: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4288: }
4289: }
4290:
4291: stepsize=(int) (stepm+YEARM-1)/YEARM;
4292: if (stepm<=12) stepsize=1;
4293: if(estepm < stepm){
4294: printf ("Problem %d lower than %d\n",estepm, stepm);
4295: }
4296: else hstepm=estepm;
4297:
4298: hstepm=hstepm/stepm;
4299: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4300: fractional in yp1 */
4301: anprojmean=yp;
4302: yp2=modf((yp1*12),&yp);
4303: mprojmean=yp;
4304: yp1=modf((yp2*30.5),&yp);
4305: jprojmean=yp;
4306: if(jprojmean==0) jprojmean=1;
4307: if(mprojmean==0) jprojmean=1;
4308:
4309: i1=cptcoveff;
4310: if (cptcovn < 1){i1=1;}
4311:
4312: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4313:
4314: fprintf(ficresf,"#****** Routine prevforecast **\n");
4315:
4316: /* if (h==(int)(YEARM*yearp)){ */
4317: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4318: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4319: k=k+1;
4320: fprintf(ficresf,"\n#******");
4321: for(j=1;j<=cptcoveff;j++) {
4322: 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]]);
4323: }
4324: fprintf(ficresf,"******\n");
4325: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4326: for(j=1; j<=nlstate+ndeath;j++){
4327: for(i=1; i<=nlstate;i++)
4328: fprintf(ficresf," p%d%d",i,j);
4329: fprintf(ficresf," p.%d",j);
4330: }
4331: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4332: fprintf(ficresf,"\n");
4333: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4334:
4335: for (agec=fage; agec>=(ageminpar-1); agec--){
4336: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4337: nhstepm = nhstepm/hstepm;
4338: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4339: oldm=oldms;savm=savms;
4340: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4341:
4342: for (h=0; h<=nhstepm; h++){
4343: if (h*hstepm/YEARM*stepm ==yearp) {
4344: fprintf(ficresf,"\n");
4345: for(j=1;j<=cptcoveff;j++)
4346: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4347: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4348: }
4349: for(j=1; j<=nlstate+ndeath;j++) {
4350: ppij=0.;
4351: for(i=1; i<=nlstate;i++) {
4352: if (mobilav==1)
4353: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4354: else {
4355: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4356: }
4357: if (h*hstepm/YEARM*stepm== yearp) {
4358: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4359: }
4360: } /* end i */
4361: if (h*hstepm/YEARM*stepm==yearp) {
4362: fprintf(ficresf," %.3f", ppij);
4363: }
4364: }/* end j */
4365: } /* end h */
4366: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4367: } /* end agec */
4368: } /* end yearp */
4369: } /* end cptcod */
4370: } /* end cptcov */
4371:
4372: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4373:
4374: fclose(ficresf);
4375: }
4376:
4377: /************** Forecasting *****not tested NB*************/
4378: 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){
4379:
4380: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4381: int *popage;
4382: double calagedatem, agelim, kk1, kk2;
4383: double *popeffectif,*popcount;
4384: double ***p3mat,***tabpop,***tabpopprev;
4385: double ***mobaverage;
4386: char filerespop[FILENAMELENGTH];
4387:
4388: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4389: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4390: agelim=AGESUP;
4391: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4392:
4393: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4394:
4395:
4396: strcpy(filerespop,"pop");
4397: strcat(filerespop,fileres);
4398: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4399: printf("Problem with forecast resultfile: %s\n", filerespop);
4400: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4401: }
4402: printf("Computing forecasting: result on file '%s' \n", filerespop);
4403: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4404:
4405: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4406:
4407: if (mobilav!=0) {
4408: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4409: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4410: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4411: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4412: }
4413: }
4414:
4415: stepsize=(int) (stepm+YEARM-1)/YEARM;
4416: if (stepm<=12) stepsize=1;
4417:
4418: agelim=AGESUP;
4419:
4420: hstepm=1;
4421: hstepm=hstepm/stepm;
4422:
4423: if (popforecast==1) {
4424: if((ficpop=fopen(popfile,"r"))==NULL) {
4425: printf("Problem with population file : %s\n",popfile);exit(0);
4426: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4427: }
4428: popage=ivector(0,AGESUP);
4429: popeffectif=vector(0,AGESUP);
4430: popcount=vector(0,AGESUP);
4431:
4432: i=1;
4433: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4434:
4435: imx=i;
4436: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4437: }
4438:
4439: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4440: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4441: k=k+1;
4442: fprintf(ficrespop,"\n#******");
4443: for(j=1;j<=cptcoveff;j++) {
4444: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4445: }
4446: fprintf(ficrespop,"******\n");
4447: fprintf(ficrespop,"# Age");
4448: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4449: if (popforecast==1) fprintf(ficrespop," [Population]");
4450:
4451: for (cpt=0; cpt<=0;cpt++) {
4452: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4453:
4454: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4455: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4456: nhstepm = nhstepm/hstepm;
4457:
4458: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4459: oldm=oldms;savm=savms;
4460: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4461:
4462: for (h=0; h<=nhstepm; h++){
4463: if (h==(int) (calagedatem+YEARM*cpt)) {
4464: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4465: }
4466: for(j=1; j<=nlstate+ndeath;j++) {
4467: kk1=0.;kk2=0;
4468: for(i=1; i<=nlstate;i++) {
4469: if (mobilav==1)
4470: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4471: else {
4472: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4473: }
4474: }
4475: if (h==(int)(calagedatem+12*cpt)){
4476: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4477: /*fprintf(ficrespop," %.3f", kk1);
4478: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4479: }
4480: }
4481: for(i=1; i<=nlstate;i++){
4482: kk1=0.;
4483: for(j=1; j<=nlstate;j++){
4484: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4485: }
4486: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4487: }
4488:
4489: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4490: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4491: }
4492: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4493: }
4494: }
4495:
4496: /******/
4497:
4498: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4499: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4500: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4501: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4502: nhstepm = nhstepm/hstepm;
4503:
4504: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4505: oldm=oldms;savm=savms;
4506: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4507: for (h=0; h<=nhstepm; h++){
4508: if (h==(int) (calagedatem+YEARM*cpt)) {
4509: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4510: }
4511: for(j=1; j<=nlstate+ndeath;j++) {
4512: kk1=0.;kk2=0;
4513: for(i=1; i<=nlstate;i++) {
4514: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4515: }
4516: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4517: }
4518: }
4519: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4520: }
4521: }
4522: }
4523: }
4524:
4525: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4526:
4527: if (popforecast==1) {
4528: free_ivector(popage,0,AGESUP);
4529: free_vector(popeffectif,0,AGESUP);
4530: free_vector(popcount,0,AGESUP);
4531: }
4532: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4533: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4534: fclose(ficrespop);
4535: } /* End of popforecast */
4536:
4537: int fileappend(FILE *fichier, char *optionfich)
4538: {
4539: if((fichier=fopen(optionfich,"a"))==NULL) {
4540: printf("Problem with file: %s\n", optionfich);
4541: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4542: return (0);
4543: }
4544: fflush(fichier);
4545: return (1);
4546: }
4547:
4548:
4549: /**************** function prwizard **********************/
4550: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4551: {
4552:
4553: /* Wizard to print covariance matrix template */
4554:
4555: char ca[32], cb[32], cc[32];
4556: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4557: int numlinepar;
4558:
4559: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4560: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4561: for(i=1; i <=nlstate; i++){
4562: jj=0;
4563: for(j=1; j <=nlstate+ndeath; j++){
4564: if(j==i) continue;
4565: jj++;
4566: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4567: printf("%1d%1d",i,j);
4568: fprintf(ficparo,"%1d%1d",i,j);
4569: for(k=1; k<=ncovmodel;k++){
4570: /* printf(" %lf",param[i][j][k]); */
4571: /* fprintf(ficparo," %lf",param[i][j][k]); */
4572: printf(" 0.");
4573: fprintf(ficparo," 0.");
4574: }
4575: printf("\n");
4576: fprintf(ficparo,"\n");
4577: }
4578: }
4579: printf("# Scales (for hessian or gradient estimation)\n");
4580: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4581: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4582: for(i=1; i <=nlstate; i++){
4583: jj=0;
4584: for(j=1; j <=nlstate+ndeath; j++){
4585: if(j==i) continue;
4586: jj++;
4587: fprintf(ficparo,"%1d%1d",i,j);
4588: printf("%1d%1d",i,j);
4589: fflush(stdout);
4590: for(k=1; k<=ncovmodel;k++){
4591: /* printf(" %le",delti3[i][j][k]); */
4592: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4593: printf(" 0.");
4594: fprintf(ficparo," 0.");
4595: }
4596: numlinepar++;
4597: printf("\n");
4598: fprintf(ficparo,"\n");
4599: }
4600: }
4601: printf("# Covariance matrix\n");
4602: /* # 121 Var(a12)\n\ */
4603: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4604: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4605: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4606: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4607: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4608: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4609: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4610: fflush(stdout);
4611: fprintf(ficparo,"# Covariance matrix\n");
4612: /* # 121 Var(a12)\n\ */
4613: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4614: /* # ...\n\ */
4615: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4616:
4617: for(itimes=1;itimes<=2;itimes++){
4618: jj=0;
4619: for(i=1; i <=nlstate; i++){
4620: for(j=1; j <=nlstate+ndeath; j++){
4621: if(j==i) continue;
4622: for(k=1; k<=ncovmodel;k++){
4623: jj++;
4624: ca[0]= k+'a'-1;ca[1]='\0';
4625: if(itimes==1){
4626: printf("#%1d%1d%d",i,j,k);
4627: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4628: }else{
4629: printf("%1d%1d%d",i,j,k);
4630: fprintf(ficparo,"%1d%1d%d",i,j,k);
4631: /* printf(" %.5le",matcov[i][j]); */
4632: }
4633: ll=0;
4634: for(li=1;li <=nlstate; li++){
4635: for(lj=1;lj <=nlstate+ndeath; lj++){
4636: if(lj==li) continue;
4637: for(lk=1;lk<=ncovmodel;lk++){
4638: ll++;
4639: if(ll<=jj){
4640: cb[0]= lk +'a'-1;cb[1]='\0';
4641: if(ll<jj){
4642: if(itimes==1){
4643: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4644: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4645: }else{
4646: printf(" 0.");
4647: fprintf(ficparo," 0.");
4648: }
4649: }else{
4650: if(itimes==1){
4651: printf(" Var(%s%1d%1d)",ca,i,j);
4652: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4653: }else{
4654: printf(" 0.");
4655: fprintf(ficparo," 0.");
4656: }
4657: }
4658: }
4659: } /* end lk */
4660: } /* end lj */
4661: } /* end li */
4662: printf("\n");
4663: fprintf(ficparo,"\n");
4664: numlinepar++;
4665: } /* end k*/
4666: } /*end j */
4667: } /* end i */
4668: } /* end itimes */
4669:
4670: } /* end of prwizard */
4671: /******************* Gompertz Likelihood ******************************/
4672: double gompertz(double x[])
4673: {
4674: double A,B,L=0.0,sump=0.,num=0.;
4675: int i,n=0; /* n is the size of the sample */
4676:
4677: for (i=0;i<=imx-1 ; i++) {
4678: sump=sump+weight[i];
4679: /* sump=sump+1;*/
4680: num=num+1;
4681: }
4682:
4683:
4684: /* for (i=0; i<=imx; i++)
4685: 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]);*/
4686:
4687: for (i=1;i<=imx ; i++)
4688: {
4689: if (cens[i] == 1 && wav[i]>1)
4690: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4691:
4692: if (cens[i] == 0 && wav[i]>1)
4693: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4694: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4695:
4696: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4697: if (wav[i] > 1 ) { /* ??? */
4698: L=L+A*weight[i];
4699: /* 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]);*/
4700: }
4701: }
4702:
4703: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4704:
4705: return -2*L*num/sump;
4706: }
4707:
1.136 brouard 4708: #ifdef GSL
4709: /******************* Gompertz_f Likelihood ******************************/
4710: double gompertz_f(const gsl_vector *v, void *params)
4711: {
4712: double A,B,LL=0.0,sump=0.,num=0.;
4713: double *x= (double *) v->data;
4714: int i,n=0; /* n is the size of the sample */
4715:
4716: for (i=0;i<=imx-1 ; i++) {
4717: sump=sump+weight[i];
4718: /* sump=sump+1;*/
4719: num=num+1;
4720: }
4721:
4722:
4723: /* for (i=0; i<=imx; i++)
4724: 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]);*/
4725: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4726: for (i=1;i<=imx ; i++)
4727: {
4728: if (cens[i] == 1 && wav[i]>1)
4729: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4730:
4731: if (cens[i] == 0 && wav[i]>1)
4732: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4733: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4734:
4735: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4736: if (wav[i] > 1 ) { /* ??? */
4737: LL=LL+A*weight[i];
4738: /* 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]);*/
4739: }
4740: }
4741:
4742: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4743: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4744:
4745: return -2*LL*num/sump;
4746: }
4747: #endif
4748:
1.126 brouard 4749: /******************* Printing html file ***********/
4750: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4751: int lastpass, int stepm, int weightopt, char model[],\
4752: int imx, double p[],double **matcov,double agemortsup){
4753: int i,k;
4754:
4755: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4756: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4757: for (i=1;i<=2;i++)
4758: 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]));
4759: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4760: fprintf(fichtm,"</ul>");
4761:
4762: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4763:
4764: 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>");
4765:
4766: for (k=agegomp;k<(agemortsup-2);k++)
4767: 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]);
4768:
4769:
4770: fflush(fichtm);
4771: }
4772:
4773: /******************* Gnuplot file **************/
4774: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4775:
4776: char dirfileres[132],optfileres[132];
4777: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4778: int ng;
4779:
4780:
4781: /*#ifdef windows */
4782: fprintf(ficgp,"cd \"%s\" \n",pathc);
4783: /*#endif */
4784:
4785:
4786: strcpy(dirfileres,optionfilefiname);
4787: strcpy(optfileres,"vpl");
4788: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4789: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4790: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4791: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4792: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4793:
4794: }
4795:
1.136 brouard 4796: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4797: {
1.126 brouard 4798:
1.136 brouard 4799: /*-------- data file ----------*/
4800: FILE *fic;
4801: char dummy[]=" ";
4802: int i, j, n;
4803: int linei, month, year,iout;
4804: char line[MAXLINE], linetmp[MAXLINE];
4805: char stra[80], strb[80];
4806: char *stratrunc;
4807: int lstra;
1.126 brouard 4808:
4809:
1.136 brouard 4810: if((fic=fopen(datafile,"r"))==NULL) {
4811: printf("Problem while opening datafile: %s\n", datafile);return 1;
4812: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4813: }
1.126 brouard 4814:
1.136 brouard 4815: i=1;
4816: linei=0;
4817: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4818: linei=linei+1;
4819: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4820: if(line[j] == '\t')
4821: line[j] = ' ';
4822: }
4823: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4824: ;
4825: };
4826: line[j+1]=0; /* Trims blanks at end of line */
4827: if(line[0]=='#'){
4828: fprintf(ficlog,"Comment line\n%s\n",line);
4829: printf("Comment line\n%s\n",line);
4830: continue;
4831: }
4832: trimbb(linetmp,line); /* Trims multiple blanks in line */
4833: for (j=0; line[j]!='\0';j++){
4834: line[j]=linetmp[j];
4835: }
4836:
1.126 brouard 4837:
1.136 brouard 4838: for (j=maxwav;j>=1;j--){
1.137 brouard 4839: cutv(stra, strb, line, ' ');
1.136 brouard 4840: if(strb[0]=='.') { /* Missing status */
4841: lval=-1;
4842: }else{
4843: errno=0;
4844: lval=strtol(strb,&endptr,10);
4845: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4846: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4847: 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);
4848: 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 4849: return 1;
4850: }
4851: }
4852: s[j][i]=lval;
4853:
4854: strcpy(line,stra);
4855: cutv(stra, strb,line,' ');
4856: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4857: }
1.145 brouard 4858: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 4859: month=99;
4860: year=9999;
4861: }else{
1.141 brouard 4862: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d. Exiting.\n",strb, linei,i, line,j);
4863: 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 4864: return 1;
4865: }
4866: anint[j][i]= (double) year;
4867: mint[j][i]= (double)month;
4868: strcpy(line,stra);
4869: } /* ENd Waves */
4870:
4871: cutv(stra, strb,line,' ');
4872: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4873: }
4874: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4875: month=99;
4876: year=9999;
4877: }else{
1.141 brouard 4878: 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);
4879: 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 4880: return 1;
4881: }
4882: andc[i]=(double) year;
4883: moisdc[i]=(double) month;
4884: strcpy(line,stra);
4885:
4886: cutv(stra, strb,line,' ');
4887: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4888: }
1.145 brouard 4889: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 4890: month=99;
4891: year=9999;
4892: }else{
1.141 brouard 4893: 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);
4894: 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 4895: return 1;
4896: }
4897: if (year==9999) {
1.141 brouard 4898: 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);
4899: 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 4900: return 1;
1.126 brouard 4901:
1.136 brouard 4902: }
4903: annais[i]=(double)(year);
4904: moisnais[i]=(double)(month);
4905: strcpy(line,stra);
4906:
4907: cutv(stra, strb,line,' ');
4908: errno=0;
4909: dval=strtod(strb,&endptr);
4910: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4911: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4912: 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 4913: fflush(ficlog);
4914: return 1;
4915: }
4916: weight[i]=dval;
4917: strcpy(line,stra);
4918:
4919: for (j=ncovcol;j>=1;j--){
4920: cutv(stra, strb,line,' ');
4921: if(strb[0]=='.') { /* Missing status */
4922: lval=-1;
4923: }else{
4924: errno=0;
4925: lval=strtol(strb,&endptr,10);
4926: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4927: 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);
4928: 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 4929: return 1;
4930: }
4931: }
4932: if(lval <-1 || lval >1){
1.141 brouard 4933: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4934: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4935: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4936: For example, for multinomial values like 1, 2 and 3,\n \
4937: build V1=0 V2=0 for the reference value (1),\n \
4938: V1=1 V2=0 for (2) \n \
4939: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4940: output of IMaCh is often meaningless.\n \
4941: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 4942: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 4943: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4944: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4945: For example, for multinomial values like 1, 2 and 3,\n \
4946: build V1=0 V2=0 for the reference value (1),\n \
4947: V1=1 V2=0 for (2) \n \
4948: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4949: output of IMaCh is often meaningless.\n \
4950: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
4951: return 1;
4952: }
4953: covar[j][i]=(double)(lval);
4954: strcpy(line,stra);
4955: }
4956: lstra=strlen(stra);
4957:
4958: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
4959: stratrunc = &(stra[lstra-9]);
4960: num[i]=atol(stratrunc);
4961: }
4962: else
4963: num[i]=atol(stra);
4964: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
4965: 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;}*/
4966:
4967: i=i+1;
4968: } /* End loop reading data */
1.126 brouard 4969:
1.136 brouard 4970: *imax=i-1; /* Number of individuals */
4971: fclose(fic);
4972:
4973: return (0);
4974: endread:
4975: printf("Exiting readdata: ");
4976: fclose(fic);
4977: return (1);
1.126 brouard 4978:
4979:
4980:
1.136 brouard 4981: }
1.145 brouard 4982: void removespace(char *str) {
4983: char *p1 = str, *p2 = str;
4984: do
4985: while (*p2 == ' ')
4986: p2++;
4987: while (*p1++ = *p2++);
4988: }
4989:
4990: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
4991: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
4992: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
4993: * - cptcovn or number of covariates k of the models excluding age*products =6
4994: * - cptcovage number of covariates with age*products =2
4995: * - cptcovs number of simple covariates
4996: * - 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
4997: * which is a new column after the 9 (ncovcol) variables.
4998: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
4999: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5000: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5001: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5002: */
1.136 brouard 5003: {
1.145 brouard 5004: int i, j, k, ks;
1.136 brouard 5005: int i1, j1, k1, k2;
5006: char modelsav[80];
1.145 brouard 5007: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5008:
1.145 brouard 5009: /*removespace(model);*/
1.136 brouard 5010: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5011: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5012: j=nbocc(model,'+'); /**< j=Number of '+' */
5013: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5014: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5015: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5016: /* including age products which are counted in cptcovage.
5017: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5018: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5019: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5020: strcpy(modelsav,model);
1.137 brouard 5021: if (strstr(model,"AGE") !=0){
5022: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5023: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5024: return 1;
5025: }
1.141 brouard 5026: if (strstr(model,"v") !=0){
5027: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5028: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5029: return 1;
5030: }
1.136 brouard 5031:
1.145 brouard 5032: /* Design
5033: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5034: * < ncovcol=8 >
5035: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5036: * k= 1 2 3 4 5 6 7 8
5037: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5038: * covar[k,i], value of kth covariate if not including age for individual i:
5039: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5040: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5041: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5042: * Tage[++cptcovage]=k
5043: * if products, new covar are created after ncovcol with k1
5044: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5045: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5046: * 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
5047: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5048: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5049: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5050: * < ncovcol=8 >
5051: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5052: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5053: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5054: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5055: * p Tprod[1]@2={ 6, 5}
5056: *p Tvard[1][1]@4= {7, 8, 5, 6}
5057: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5058: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5059: *How to reorganize?
5060: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5061: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5062: * {2, 1, 4, 8, 5, 6, 3, 7}
5063: * Struct []
5064: */
5065:
1.136 brouard 5066: /* This loop fills the array Tvar from the string 'model'.*/
5067: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5068: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5069: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5070: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5071: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5072: /* k=1 Tvar[1]=2 (from V2) */
5073: /* k=5 Tvar[5] */
5074: /* for (k=1; k<=cptcovn;k++) { */
5075: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5076: /* } */
5077: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5078: /*
5079: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5080: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5081: Tvar[k]=0;
5082: cptcovage=0;
5083: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5084: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5085: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5086: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5087: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5088: /*scanf("%d",i);*/
1.145 brouard 5089: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5090: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5091: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5092: /* covar is not filled and then is empty */
1.136 brouard 5093: cptcovprod--;
1.145 brouard 5094: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5095: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5096: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5097: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5098: /*printf("stre=%s ", stre);*/
1.137 brouard 5099: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5100: cptcovprod--;
1.145 brouard 5101: cutl(stre,strb,strc,'V');
1.136 brouard 5102: Tvar[k]=atoi(stre);
5103: cptcovage++;
5104: Tage[cptcovage]=k;
1.137 brouard 5105: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5106: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5107: cptcovn++;
5108: cptcovprodnoage++;k1++;
5109: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5110: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5111: because this model-covariate is a construction we invent a new column
5112: ncovcol + k1
5113: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5114: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5115: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5116: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5117: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5118: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5119: k2=k2+2;
5120: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5121: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5122: for (i=1; i<=lastobs;i++){
5123: /* Computes the new covariate which is a product of
1.145 brouard 5124: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5125: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5126: }
5127: } /* End age is not in the model */
5128: } /* End if model includes a product */
1.136 brouard 5129: else { /* no more sum */
5130: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5131: /* scanf("%d",i);*/
1.145 brouard 5132: cutl(strd,strc,strb,'V');
5133: ks++; /**< Number of simple covariates */
5134: cptcovn++;
5135: Tvar[k]=atoi(strd);
1.136 brouard 5136: }
1.137 brouard 5137: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5138: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5139: scanf("%d",i);*/
5140: } /* end of loop + */
5141: } /* end model */
5142:
5143: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5144: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5145:
5146: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5147: printf("cptcovprod=%d ", cptcovprod);
5148: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5149:
5150: scanf("%d ",i);*/
5151:
5152:
1.137 brouard 5153: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.136 brouard 5154: endread:
5155: printf("Exiting decodemodel: ");
5156: return (1);
5157: }
5158:
5159: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5160: {
5161: int i, m;
5162:
5163: for (i=1; i<=imx; i++) {
5164: for(m=2; (m<= maxwav); m++) {
5165: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5166: anint[m][i]=9999;
5167: s[m][i]=-1;
5168: }
5169: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5170: *nberr++;
5171: 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);
5172: 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);
5173: s[m][i]=-1;
5174: }
5175: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5176: *nberr++;
5177: 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]);
5178: 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]);
5179: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5180: }
5181: }
5182: }
5183:
5184: for (i=1; i<=imx; i++) {
5185: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5186: for(m=firstpass; (m<= lastpass); m++){
5187: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5188: if (s[m][i] >= nlstate+1) {
5189: if(agedc[i]>0)
5190: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5191: agev[m][i]=agedc[i];
5192: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5193: else {
5194: if ((int)andc[i]!=9999){
5195: nbwarn++;
5196: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5197: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5198: agev[m][i]=-1;
5199: }
5200: }
5201: }
5202: else if(s[m][i] !=9){ /* Standard case, age in fractional
5203: years but with the precision of a month */
5204: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5205: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5206: agev[m][i]=1;
5207: else if(agev[m][i] < *agemin){
5208: *agemin=agev[m][i];
5209: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5210: }
5211: else if(agev[m][i] >*agemax){
5212: *agemax=agev[m][i];
1.156 brouard 5213: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5214: }
5215: /*agev[m][i]=anint[m][i]-annais[i];*/
5216: /* agev[m][i] = age[i]+2*m;*/
5217: }
5218: else { /* =9 */
5219: agev[m][i]=1;
5220: s[m][i]=-1;
5221: }
5222: }
5223: else /*= 0 Unknown */
5224: agev[m][i]=1;
5225: }
5226:
5227: }
5228: for (i=1; i<=imx; i++) {
5229: for(m=firstpass; (m<=lastpass); m++){
5230: if (s[m][i] > (nlstate+ndeath)) {
5231: *nberr++;
5232: 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);
5233: 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);
5234: return 1;
5235: }
5236: }
5237: }
5238:
5239: /*for (i=1; i<=imx; i++){
5240: for (m=firstpass; (m<lastpass); m++){
5241: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5242: }
5243:
5244: }*/
5245:
5246:
1.139 brouard 5247: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5248: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5249:
5250: return (0);
5251: endread:
5252: printf("Exiting calandcheckages: ");
5253: return (1);
5254: }
5255:
5256:
5257: /***********************************************/
5258: /**************** Main Program *****************/
5259: /***********************************************/
5260:
5261: int main(int argc, char *argv[])
5262: {
5263: #ifdef GSL
5264: const gsl_multimin_fminimizer_type *T;
5265: size_t iteri = 0, it;
5266: int rval = GSL_CONTINUE;
5267: int status = GSL_SUCCESS;
5268: double ssval;
5269: #endif
5270: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5271: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5272: int linei, month, year,iout;
5273: int jj, ll, li, lj, lk, imk;
5274: int numlinepar=0; /* Current linenumber of parameter file */
5275: int itimes;
5276: int NDIM=2;
5277: int vpopbased=0;
5278:
5279: char ca[32], cb[32], cc[32];
5280: /* FILE *fichtm; *//* Html File */
5281: /* FILE *ficgp;*/ /*Gnuplot File */
5282: struct stat info;
5283: double agedeb, agefin,hf;
5284: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5285:
5286: double fret;
5287: double **xi,tmp,delta;
5288:
5289: double dum; /* Dummy variable */
5290: double ***p3mat;
5291: double ***mobaverage;
5292: int *indx;
5293: char line[MAXLINE], linepar[MAXLINE];
5294: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5295: char pathr[MAXLINE], pathimach[MAXLINE];
5296: char **bp, *tok, *val; /* pathtot */
5297: int firstobs=1, lastobs=10;
5298: int sdeb, sfin; /* Status at beginning and end */
5299: int c, h , cpt,l;
5300: int ju,jl, mi;
5301: int i1,j1, jk,aa,bb, stepsize, ij;
5302: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5303: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5304: int mobilav=0,popforecast=0;
5305: int hstepm, nhstepm;
5306: int agemortsup;
5307: float sumlpop=0.;
5308: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5309: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5310:
5311: double bage, fage, age, agelim, agebase;
5312: double ftolpl=FTOL;
5313: double **prlim;
5314: double ***param; /* Matrix of parameters */
5315: double *p;
5316: double **matcov; /* Matrix of covariance */
5317: double ***delti3; /* Scale */
5318: double *delti; /* Scale */
5319: double ***eij, ***vareij;
5320: double **varpl; /* Variances of prevalence limits by age */
5321: double *epj, vepp;
5322: double kk1, kk2;
5323: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5324: double **ximort;
1.145 brouard 5325: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5326: int *dcwave;
5327:
5328: char z[1]="c", occ;
5329:
5330: /*char *strt;*/
5331: char strtend[80];
1.126 brouard 5332:
5333: long total_usecs;
5334:
5335: /* setlocale (LC_ALL, ""); */
5336: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5337: /* textdomain (PACKAGE); */
5338: /* setlocale (LC_CTYPE, ""); */
5339: /* setlocale (LC_MESSAGES, ""); */
5340:
5341: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5342: rstart_time = time(NULL);
5343: /* (void) gettimeofday(&start_time,&tzp);*/
5344: start_time = *localtime(&rstart_time);
1.126 brouard 5345: curr_time=start_time;
1.157 brouard 5346: /*tml = *localtime(&start_time.tm_sec);*/
5347: /* strcpy(strstart,asctime(&tml)); */
5348: strcpy(strstart,asctime(&start_time));
1.126 brouard 5349:
5350: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5351: /* tp.tm_sec = tp.tm_sec +86400; */
5352: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5353: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5354: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5355: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5356: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5357: /* strt=asctime(&tmg); */
5358: /* printf("Time(after) =%s",strstart); */
5359: /* (void) time (&time_value);
5360: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5361: * tm = *localtime(&time_value);
5362: * strstart=asctime(&tm);
5363: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5364: */
5365:
5366: nberr=0; /* Number of errors and warnings */
5367: nbwarn=0;
5368: getcwd(pathcd, size);
5369:
5370: printf("\n%s\n%s",version,fullversion);
5371: if(argc <=1){
5372: printf("\nEnter the parameter file name: ");
5373: fgets(pathr,FILENAMELENGTH,stdin);
5374: i=strlen(pathr);
5375: if(pathr[i-1]=='\n')
5376: pathr[i-1]='\0';
1.156 brouard 5377: i=strlen(pathr);
5378: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5379: pathr[i-1]='\0';
1.126 brouard 5380: for (tok = pathr; tok != NULL; ){
5381: printf("Pathr |%s|\n",pathr);
5382: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5383: printf("val= |%s| pathr=%s\n",val,pathr);
5384: strcpy (pathtot, val);
5385: if(pathr[0] == '\0') break; /* Dirty */
5386: }
5387: }
5388: else{
5389: strcpy(pathtot,argv[1]);
5390: }
5391: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5392: /*cygwin_split_path(pathtot,path,optionfile);
5393: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5394: /* cutv(path,optionfile,pathtot,'\\');*/
5395:
5396: /* Split argv[0], imach program to get pathimach */
5397: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5398: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5399: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5400: /* strcpy(pathimach,argv[0]); */
5401: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5402: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5403: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5404: chdir(path); /* Can be a relative path */
5405: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5406: printf("Current directory %s!\n",pathcd);
5407: strcpy(command,"mkdir ");
5408: strcat(command,optionfilefiname);
5409: if((outcmd=system(command)) != 0){
5410: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5411: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5412: /* fclose(ficlog); */
5413: /* exit(1); */
5414: }
5415: /* if((imk=mkdir(optionfilefiname))<0){ */
5416: /* perror("mkdir"); */
5417: /* } */
5418:
5419: /*-------- arguments in the command line --------*/
5420:
5421: /* Log file */
5422: strcat(filelog, optionfilefiname);
5423: strcat(filelog,".log"); /* */
5424: if((ficlog=fopen(filelog,"w"))==NULL) {
5425: printf("Problem with logfile %s\n",filelog);
5426: goto end;
5427: }
5428: fprintf(ficlog,"Log filename:%s\n",filelog);
5429: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5430: fprintf(ficlog,"\nEnter the parameter file name: \n");
5431: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5432: path=%s \n\
5433: optionfile=%s\n\
5434: optionfilext=%s\n\
1.156 brouard 5435: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5436:
5437: printf("Local time (at start):%s",strstart);
5438: fprintf(ficlog,"Local time (at start): %s",strstart);
5439: fflush(ficlog);
5440: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5441: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5442:
5443: /* */
5444: strcpy(fileres,"r");
5445: strcat(fileres, optionfilefiname);
5446: strcat(fileres,".txt"); /* Other files have txt extension */
5447:
5448: /*---------arguments file --------*/
5449:
5450: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5451: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5452: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5453: fflush(ficlog);
1.149 brouard 5454: /* goto end; */
5455: exit(70);
1.126 brouard 5456: }
5457:
5458:
5459:
5460: strcpy(filereso,"o");
5461: strcat(filereso,fileres);
5462: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5463: printf("Problem with Output resultfile: %s\n", filereso);
5464: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5465: fflush(ficlog);
5466: goto end;
5467: }
5468:
5469: /* Reads comments: lines beginning with '#' */
5470: numlinepar=0;
5471: while((c=getc(ficpar))=='#' && c!= EOF){
5472: ungetc(c,ficpar);
5473: fgets(line, MAXLINE, ficpar);
5474: numlinepar++;
1.141 brouard 5475: fputs(line,stdout);
1.126 brouard 5476: fputs(line,ficparo);
5477: fputs(line,ficlog);
5478: }
5479: ungetc(c,ficpar);
5480:
5481: 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);
5482: numlinepar++;
5483: 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);
5484: 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);
5485: 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);
5486: fflush(ficlog);
5487: while((c=getc(ficpar))=='#' && c!= EOF){
5488: ungetc(c,ficpar);
5489: fgets(line, MAXLINE, ficpar);
5490: numlinepar++;
1.141 brouard 5491: fputs(line, stdout);
5492: //puts(line);
1.126 brouard 5493: fputs(line,ficparo);
5494: fputs(line,ficlog);
5495: }
5496: ungetc(c,ficpar);
5497:
5498:
1.145 brouard 5499: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5500: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5501: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5502: v1+v2*age+v2*v3 makes cptcovn = 3
5503: */
5504: if (strlen(model)>1)
1.145 brouard 5505: 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*/
5506: else
5507: ncovmodel=2;
1.126 brouard 5508: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5509: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5510: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5511: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5512: 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);
5513: 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);
5514: fflush(stdout);
5515: fclose (ficlog);
5516: goto end;
5517: }
1.126 brouard 5518: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5519: delti=delti3[1][1];
5520: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5521: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5522: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5523: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5524: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5525: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5526: fclose (ficparo);
5527: fclose (ficlog);
5528: goto end;
5529: exit(0);
5530: }
5531: else if(mle==-3) {
5532: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5533: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5534: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5535: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5536: matcov=matrix(1,npar,1,npar);
5537: }
5538: else{
1.145 brouard 5539: /* Read guessed parameters */
1.126 brouard 5540: /* Reads comments: lines beginning with '#' */
5541: while((c=getc(ficpar))=='#' && c!= EOF){
5542: ungetc(c,ficpar);
5543: fgets(line, MAXLINE, ficpar);
5544: numlinepar++;
1.141 brouard 5545: fputs(line,stdout);
1.126 brouard 5546: fputs(line,ficparo);
5547: fputs(line,ficlog);
5548: }
5549: ungetc(c,ficpar);
5550:
5551: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5552: for(i=1; i <=nlstate; i++){
5553: j=0;
5554: for(jj=1; jj <=nlstate+ndeath; jj++){
5555: if(jj==i) continue;
5556: j++;
5557: fscanf(ficpar,"%1d%1d",&i1,&j1);
5558: if ((i1 != i) && (j1 != j)){
5559: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5560: It might be a problem of design; if ncovcol and the model are correct\n \
5561: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5562: exit(1);
5563: }
5564: fprintf(ficparo,"%1d%1d",i1,j1);
5565: if(mle==1)
5566: printf("%1d%1d",i,j);
5567: fprintf(ficlog,"%1d%1d",i,j);
5568: for(k=1; k<=ncovmodel;k++){
5569: fscanf(ficpar," %lf",¶m[i][j][k]);
5570: if(mle==1){
5571: printf(" %lf",param[i][j][k]);
5572: fprintf(ficlog," %lf",param[i][j][k]);
5573: }
5574: else
5575: fprintf(ficlog," %lf",param[i][j][k]);
5576: fprintf(ficparo," %lf",param[i][j][k]);
5577: }
5578: fscanf(ficpar,"\n");
5579: numlinepar++;
5580: if(mle==1)
5581: printf("\n");
5582: fprintf(ficlog,"\n");
5583: fprintf(ficparo,"\n");
5584: }
5585: }
5586: fflush(ficlog);
5587:
1.145 brouard 5588: /* Reads scales values */
1.126 brouard 5589: p=param[1][1];
5590:
5591: /* Reads comments: lines beginning with '#' */
5592: while((c=getc(ficpar))=='#' && c!= EOF){
5593: ungetc(c,ficpar);
5594: fgets(line, MAXLINE, ficpar);
5595: numlinepar++;
1.141 brouard 5596: fputs(line,stdout);
1.126 brouard 5597: fputs(line,ficparo);
5598: fputs(line,ficlog);
5599: }
5600: ungetc(c,ficpar);
5601:
5602: for(i=1; i <=nlstate; i++){
5603: for(j=1; j <=nlstate+ndeath-1; j++){
5604: fscanf(ficpar,"%1d%1d",&i1,&j1);
5605: if ((i1-i)*(j1-j)!=0){
5606: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5607: exit(1);
5608: }
5609: printf("%1d%1d",i,j);
5610: fprintf(ficparo,"%1d%1d",i1,j1);
5611: fprintf(ficlog,"%1d%1d",i1,j1);
5612: for(k=1; k<=ncovmodel;k++){
5613: fscanf(ficpar,"%le",&delti3[i][j][k]);
5614: printf(" %le",delti3[i][j][k]);
5615: fprintf(ficparo," %le",delti3[i][j][k]);
5616: fprintf(ficlog," %le",delti3[i][j][k]);
5617: }
5618: fscanf(ficpar,"\n");
5619: numlinepar++;
5620: printf("\n");
5621: fprintf(ficparo,"\n");
5622: fprintf(ficlog,"\n");
5623: }
5624: }
5625: fflush(ficlog);
5626:
1.145 brouard 5627: /* Reads covariance matrix */
1.126 brouard 5628: delti=delti3[1][1];
5629:
5630:
5631: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5632:
5633: /* Reads comments: lines beginning with '#' */
5634: while((c=getc(ficpar))=='#' && c!= EOF){
5635: ungetc(c,ficpar);
5636: fgets(line, MAXLINE, ficpar);
5637: numlinepar++;
1.141 brouard 5638: fputs(line,stdout);
1.126 brouard 5639: fputs(line,ficparo);
5640: fputs(line,ficlog);
5641: }
5642: ungetc(c,ficpar);
5643:
5644: matcov=matrix(1,npar,1,npar);
1.131 brouard 5645: for(i=1; i <=npar; i++)
5646: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5647:
1.126 brouard 5648: for(i=1; i <=npar; i++){
1.145 brouard 5649: fscanf(ficpar,"%s",str);
1.126 brouard 5650: if(mle==1)
5651: printf("%s",str);
5652: fprintf(ficlog,"%s",str);
5653: fprintf(ficparo,"%s",str);
5654: for(j=1; j <=i; j++){
5655: fscanf(ficpar," %le",&matcov[i][j]);
5656: if(mle==1){
5657: printf(" %.5le",matcov[i][j]);
5658: }
5659: fprintf(ficlog," %.5le",matcov[i][j]);
5660: fprintf(ficparo," %.5le",matcov[i][j]);
5661: }
5662: fscanf(ficpar,"\n");
5663: numlinepar++;
5664: if(mle==1)
5665: printf("\n");
5666: fprintf(ficlog,"\n");
5667: fprintf(ficparo,"\n");
5668: }
5669: for(i=1; i <=npar; i++)
5670: for(j=i+1;j<=npar;j++)
5671: matcov[i][j]=matcov[j][i];
5672:
5673: if(mle==1)
5674: printf("\n");
5675: fprintf(ficlog,"\n");
5676:
5677: fflush(ficlog);
5678:
5679: /*-------- Rewriting parameter file ----------*/
5680: strcpy(rfileres,"r"); /* "Rparameterfile */
5681: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5682: strcat(rfileres,"."); /* */
5683: strcat(rfileres,optionfilext); /* Other files have txt extension */
5684: if((ficres =fopen(rfileres,"w"))==NULL) {
5685: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5686: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5687: }
5688: fprintf(ficres,"#%s\n",version);
5689: } /* End of mle != -3 */
5690:
5691:
5692: n= lastobs;
5693: num=lvector(1,n);
5694: moisnais=vector(1,n);
5695: annais=vector(1,n);
5696: moisdc=vector(1,n);
5697: andc=vector(1,n);
5698: agedc=vector(1,n);
5699: cod=ivector(1,n);
5700: weight=vector(1,n);
5701: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5702: mint=matrix(1,maxwav,1,n);
5703: anint=matrix(1,maxwav,1,n);
1.131 brouard 5704: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5705: tab=ivector(1,NCOVMAX);
1.144 brouard 5706: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5707:
1.136 brouard 5708: /* Reads data from file datafile */
5709: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5710: goto end;
5711:
5712: /* Calculation of the number of parameters from char model */
1.137 brouard 5713: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5714: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5715: k=3 V4 Tvar[k=3]= 4 (from V4)
5716: k=2 V1 Tvar[k=2]= 1 (from V1)
5717: k=1 Tvar[1]=2 (from V2)
5718: */
5719: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5720: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5721: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5722: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5723: */
5724: /* For model-covariate k tells which data-covariate to use but
5725: because this model-covariate is a construction we invent a new column
5726: ncovcol + k1
5727: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5728: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5729: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5730: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5731: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5732: */
1.145 brouard 5733: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5734: 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 5735: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5736: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5737: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5738: 4 covariates (3 plus signs)
5739: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5740: */
1.136 brouard 5741:
5742: if(decodemodel(model, lastobs) == 1)
5743: goto end;
5744:
1.137 brouard 5745: if((double)(lastobs-imx)/(double)imx > 1.10){
5746: nbwarn++;
5747: 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);
5748: 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);
5749: }
1.136 brouard 5750: /* if(mle==1){*/
1.137 brouard 5751: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5752: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5753: }
5754:
5755: /*-calculation of age at interview from date of interview and age at death -*/
5756: agev=matrix(1,maxwav,1,imx);
5757:
5758: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5759: goto end;
5760:
1.126 brouard 5761:
1.136 brouard 5762: agegomp=(int)agemin;
5763: free_vector(moisnais,1,n);
5764: free_vector(annais,1,n);
1.126 brouard 5765: /* free_matrix(mint,1,maxwav,1,n);
5766: free_matrix(anint,1,maxwav,1,n);*/
5767: free_vector(moisdc,1,n);
5768: free_vector(andc,1,n);
1.145 brouard 5769: /* */
5770:
1.126 brouard 5771: wav=ivector(1,imx);
5772: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5773: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5774: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5775:
5776: /* Concatenates waves */
5777: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5778: /* */
5779:
1.126 brouard 5780: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5781:
5782: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5783: ncodemax[1]=1;
1.145 brouard 5784: Ndum =ivector(-1,NCOVMAX);
5785: if (ncovmodel > 2)
5786: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5787:
5788: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5789: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5790: h=0;
5791:
5792:
5793: /*if (cptcovn > 0) */
1.126 brouard 5794:
1.145 brouard 5795:
1.126 brouard 5796: m=pow(2,cptcoveff);
5797:
1.131 brouard 5798: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5799: 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 */
5800: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5801: 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 5802: h++;
1.141 brouard 5803: if (h>m)
1.136 brouard 5804: h=1;
1.144 brouard 5805: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5806: * h 1 2 3 4
5807: *______________________________
5808: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5809: * 2 2 1 1 1
5810: * 3 i=2 1 2 1 1
5811: * 4 2 2 1 1
5812: * 5 i=3 1 i=2 1 2 1
5813: * 6 2 1 2 1
5814: * 7 i=4 1 2 2 1
5815: * 8 2 2 2 1
5816: * 9 i=5 1 i=3 1 i=2 1 1
5817: * 10 2 1 1 1
5818: * 11 i=6 1 2 1 1
5819: * 12 2 2 1 1
5820: * 13 i=7 1 i=4 1 2 1
5821: * 14 2 1 2 1
5822: * 15 i=8 1 2 2 1
5823: * 16 2 2 2 1
5824: */
1.141 brouard 5825: codtab[h][k]=j;
1.145 brouard 5826: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5827: 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 5828: }
5829: }
5830: }
5831: }
5832: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5833: codtab[1][2]=1;codtab[2][2]=2; */
5834: /* for(i=1; i <=m ;i++){
5835: for(k=1; k <=cptcovn; k++){
1.131 brouard 5836: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5837: }
5838: printf("\n");
5839: }
5840: scanf("%d",i);*/
1.145 brouard 5841:
5842: free_ivector(Ndum,-1,NCOVMAX);
5843:
5844:
1.126 brouard 5845:
5846: /*------------ gnuplot -------------*/
5847: strcpy(optionfilegnuplot,optionfilefiname);
5848: if(mle==-3)
5849: strcat(optionfilegnuplot,"-mort");
5850: strcat(optionfilegnuplot,".gp");
5851:
5852: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5853: printf("Problem with file %s",optionfilegnuplot);
5854: }
5855: else{
5856: fprintf(ficgp,"\n# %s\n", version);
5857: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 5858: //fprintf(ficgp,"set missing 'NaNq'\n");
5859: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 5860: }
5861: /* fclose(ficgp);*/
5862: /*--------- index.htm --------*/
5863:
5864: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5865: if(mle==-3)
5866: strcat(optionfilehtm,"-mort");
5867: strcat(optionfilehtm,".htm");
5868: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 5869: printf("Problem with %s \n",optionfilehtm);
5870: exit(0);
1.126 brouard 5871: }
5872:
5873: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5874: strcat(optionfilehtmcov,"-cov.htm");
5875: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5876: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5877: }
5878: else{
5879: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5880: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5881: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5882: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5883: }
5884:
5885: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5886: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5887: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5888: \n\
5889: <hr size=\"2\" color=\"#EC5E5E\">\
5890: <ul><li><h4>Parameter files</h4>\n\
5891: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5892: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5893: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5894: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5895: - Date and time at start: %s</ul>\n",\
5896: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5897: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5898: fileres,fileres,\
5899: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5900: fflush(fichtm);
5901:
5902: strcpy(pathr,path);
5903: strcat(pathr,optionfilefiname);
5904: chdir(optionfilefiname); /* Move to directory named optionfile */
5905:
5906: /* Calculates basic frequencies. Computes observed prevalence at single age
5907: and prints on file fileres'p'. */
5908: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5909:
5910: fprintf(fichtm,"\n");
5911: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5912: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5913: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5914: imx,agemin,agemax,jmin,jmax,jmean);
5915: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5916: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5917: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5918: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5919: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5920:
5921:
5922: /* For Powell, parameters are in a vector p[] starting at p[1]
5923: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5924: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5925:
5926: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5927:
5928: if (mle==-3){
1.136 brouard 5929: ximort=matrix(1,NDIM,1,NDIM);
5930: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 5931: cens=ivector(1,n);
5932: ageexmed=vector(1,n);
5933: agecens=vector(1,n);
5934: dcwave=ivector(1,n);
5935:
5936: for (i=1; i<=imx; i++){
5937: dcwave[i]=-1;
5938: for (m=firstpass; m<=lastpass; m++)
5939: if (s[m][i]>nlstate) {
5940: dcwave[i]=m;
5941: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5942: break;
5943: }
5944: }
5945:
5946: for (i=1; i<=imx; i++) {
5947: if (wav[i]>0){
5948: ageexmed[i]=agev[mw[1][i]][i];
5949: j=wav[i];
5950: agecens[i]=1.;
5951:
5952: if (ageexmed[i]> 1 && wav[i] > 0){
5953: agecens[i]=agev[mw[j][i]][i];
5954: cens[i]= 1;
5955: }else if (ageexmed[i]< 1)
5956: cens[i]= -1;
5957: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
5958: cens[i]=0 ;
5959: }
5960: else cens[i]=-1;
5961: }
5962:
5963: for (i=1;i<=NDIM;i++) {
5964: for (j=1;j<=NDIM;j++)
5965: ximort[i][j]=(i == j ? 1.0 : 0.0);
5966: }
5967:
1.145 brouard 5968: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 5969: /*printf("%lf %lf", p[1], p[2]);*/
5970:
5971:
1.136 brouard 5972: #ifdef GSL
5973: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
5974: #elsedef
1.126 brouard 5975: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 5976: #endif
1.126 brouard 5977: strcpy(filerespow,"pow-mort");
5978: strcat(filerespow,fileres);
5979: if((ficrespow=fopen(filerespow,"w"))==NULL) {
5980: printf("Problem with resultfile: %s\n", filerespow);
5981: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
5982: }
1.136 brouard 5983: #ifdef GSL
5984: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
5985: #elsedef
1.126 brouard 5986: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 5987: #endif
1.126 brouard 5988: /* for (i=1;i<=nlstate;i++)
5989: for(j=1;j<=nlstate+ndeath;j++)
5990: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
5991: */
5992: fprintf(ficrespow,"\n");
1.136 brouard 5993: #ifdef GSL
5994: /* gsl starts here */
5995: T = gsl_multimin_fminimizer_nmsimplex;
5996: gsl_multimin_fminimizer *sfm = NULL;
5997: gsl_vector *ss, *x;
5998: gsl_multimin_function minex_func;
5999:
6000: /* Initial vertex size vector */
6001: ss = gsl_vector_alloc (NDIM);
6002:
6003: if (ss == NULL){
6004: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6005: }
6006: /* Set all step sizes to 1 */
6007: gsl_vector_set_all (ss, 0.001);
6008:
6009: /* Starting point */
1.126 brouard 6010:
1.136 brouard 6011: x = gsl_vector_alloc (NDIM);
6012:
6013: if (x == NULL){
6014: gsl_vector_free(ss);
6015: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6016: }
6017:
6018: /* Initialize method and iterate */
6019: /* p[1]=0.0268; p[NDIM]=0.083; */
6020: /* gsl_vector_set(x, 0, 0.0268); */
6021: /* gsl_vector_set(x, 1, 0.083); */
6022: gsl_vector_set(x, 0, p[1]);
6023: gsl_vector_set(x, 1, p[2]);
6024:
6025: minex_func.f = &gompertz_f;
6026: minex_func.n = NDIM;
6027: minex_func.params = (void *)&p; /* ??? */
6028:
6029: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6030: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6031:
6032: printf("Iterations beginning .....\n\n");
6033: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6034:
6035: iteri=0;
6036: while (rval == GSL_CONTINUE){
6037: iteri++;
6038: status = gsl_multimin_fminimizer_iterate(sfm);
6039:
6040: if (status) printf("error: %s\n", gsl_strerror (status));
6041: fflush(0);
6042:
6043: if (status)
6044: break;
6045:
6046: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6047: ssval = gsl_multimin_fminimizer_size (sfm);
6048:
6049: if (rval == GSL_SUCCESS)
6050: printf ("converged to a local maximum at\n");
6051:
6052: printf("%5d ", iteri);
6053: for (it = 0; it < NDIM; it++){
6054: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6055: }
6056: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6057: }
6058:
6059: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6060:
6061: gsl_vector_free(x); /* initial values */
6062: gsl_vector_free(ss); /* inital step size */
6063: for (it=0; it<NDIM; it++){
6064: p[it+1]=gsl_vector_get(sfm->x,it);
6065: fprintf(ficrespow," %.12lf", p[it]);
6066: }
6067: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6068: #endif
6069: #ifdef POWELL
6070: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6071: #endif
1.126 brouard 6072: fclose(ficrespow);
6073:
6074: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6075:
6076: for(i=1; i <=NDIM; i++)
6077: for(j=i+1;j<=NDIM;j++)
6078: matcov[i][j]=matcov[j][i];
6079:
6080: printf("\nCovariance matrix\n ");
6081: for(i=1; i <=NDIM; i++) {
6082: for(j=1;j<=NDIM;j++){
6083: printf("%f ",matcov[i][j]);
6084: }
6085: printf("\n ");
6086: }
6087:
6088: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6089: for (i=1;i<=NDIM;i++)
6090: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6091:
6092: lsurv=vector(1,AGESUP);
6093: lpop=vector(1,AGESUP);
6094: tpop=vector(1,AGESUP);
6095: lsurv[agegomp]=100000;
6096:
6097: for (k=agegomp;k<=AGESUP;k++) {
6098: agemortsup=k;
6099: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6100: }
6101:
6102: for (k=agegomp;k<agemortsup;k++)
6103: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6104:
6105: for (k=agegomp;k<agemortsup;k++){
6106: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6107: sumlpop=sumlpop+lpop[k];
6108: }
6109:
6110: tpop[agegomp]=sumlpop;
6111: for (k=agegomp;k<(agemortsup-3);k++){
6112: /* tpop[k+1]=2;*/
6113: tpop[k+1]=tpop[k]-lpop[k];
6114: }
6115:
6116:
6117: printf("\nAge lx qx dx Lx Tx e(x)\n");
6118: for (k=agegomp;k<(agemortsup-2);k++)
6119: 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]);
6120:
6121:
6122: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6123: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6124:
6125: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6126: stepm, weightopt,\
6127: model,imx,p,matcov,agemortsup);
6128:
6129: free_vector(lsurv,1,AGESUP);
6130: free_vector(lpop,1,AGESUP);
6131: free_vector(tpop,1,AGESUP);
1.136 brouard 6132: #ifdef GSL
6133: free_ivector(cens,1,n);
6134: free_vector(agecens,1,n);
6135: free_ivector(dcwave,1,n);
6136: free_matrix(ximort,1,NDIM,1,NDIM);
6137: #endif
1.126 brouard 6138: } /* Endof if mle==-3 */
6139:
6140: else{ /* For mle >=1 */
1.132 brouard 6141: globpr=0;/* debug */
6142: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6143: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6144: for (k=1; k<=npar;k++)
6145: printf(" %d %8.5f",k,p[k]);
6146: printf("\n");
6147: globpr=1; /* to print the contributions */
6148: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6149: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6150: for (k=1; k<=npar;k++)
6151: printf(" %d %8.5f",k,p[k]);
6152: printf("\n");
6153: if(mle>=1){ /* Could be 1 or 2 */
6154: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6155: }
6156:
6157: /*--------- results files --------------*/
6158: 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);
6159:
6160:
6161: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6162: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6163: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6164: for(i=1,jk=1; i <=nlstate; i++){
6165: for(k=1; k <=(nlstate+ndeath); k++){
6166: if (k != i) {
6167: printf("%d%d ",i,k);
6168: fprintf(ficlog,"%d%d ",i,k);
6169: fprintf(ficres,"%1d%1d ",i,k);
6170: for(j=1; j <=ncovmodel; j++){
6171: printf("%lf ",p[jk]);
6172: fprintf(ficlog,"%lf ",p[jk]);
6173: fprintf(ficres,"%lf ",p[jk]);
6174: jk++;
6175: }
6176: printf("\n");
6177: fprintf(ficlog,"\n");
6178: fprintf(ficres,"\n");
6179: }
6180: }
6181: }
6182: if(mle!=0){
6183: /* Computing hessian and covariance matrix */
6184: ftolhess=ftol; /* Usually correct */
6185: hesscov(matcov, p, npar, delti, ftolhess, func);
6186: }
6187: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6188: printf("# Scales (for hessian or gradient estimation)\n");
6189: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6190: for(i=1,jk=1; i <=nlstate; i++){
6191: for(j=1; j <=nlstate+ndeath; j++){
6192: if (j!=i) {
6193: fprintf(ficres,"%1d%1d",i,j);
6194: printf("%1d%1d",i,j);
6195: fprintf(ficlog,"%1d%1d",i,j);
6196: for(k=1; k<=ncovmodel;k++){
6197: printf(" %.5e",delti[jk]);
6198: fprintf(ficlog," %.5e",delti[jk]);
6199: fprintf(ficres," %.5e",delti[jk]);
6200: jk++;
6201: }
6202: printf("\n");
6203: fprintf(ficlog,"\n");
6204: fprintf(ficres,"\n");
6205: }
6206: }
6207: }
6208:
6209: 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");
6210: if(mle>=1)
6211: 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");
6212: 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");
6213: /* # 121 Var(a12)\n\ */
6214: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6215: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6216: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6217: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6218: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6219: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6220: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6221:
6222:
6223: /* Just to have a covariance matrix which will be more understandable
6224: even is we still don't want to manage dictionary of variables
6225: */
6226: for(itimes=1;itimes<=2;itimes++){
6227: jj=0;
6228: for(i=1; i <=nlstate; i++){
6229: for(j=1; j <=nlstate+ndeath; j++){
6230: if(j==i) continue;
6231: for(k=1; k<=ncovmodel;k++){
6232: jj++;
6233: ca[0]= k+'a'-1;ca[1]='\0';
6234: if(itimes==1){
6235: if(mle>=1)
6236: printf("#%1d%1d%d",i,j,k);
6237: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6238: fprintf(ficres,"#%1d%1d%d",i,j,k);
6239: }else{
6240: if(mle>=1)
6241: printf("%1d%1d%d",i,j,k);
6242: fprintf(ficlog,"%1d%1d%d",i,j,k);
6243: fprintf(ficres,"%1d%1d%d",i,j,k);
6244: }
6245: ll=0;
6246: for(li=1;li <=nlstate; li++){
6247: for(lj=1;lj <=nlstate+ndeath; lj++){
6248: if(lj==li) continue;
6249: for(lk=1;lk<=ncovmodel;lk++){
6250: ll++;
6251: if(ll<=jj){
6252: cb[0]= lk +'a'-1;cb[1]='\0';
6253: if(ll<jj){
6254: if(itimes==1){
6255: if(mle>=1)
6256: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6257: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6258: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6259: }else{
6260: if(mle>=1)
6261: printf(" %.5e",matcov[jj][ll]);
6262: fprintf(ficlog," %.5e",matcov[jj][ll]);
6263: fprintf(ficres," %.5e",matcov[jj][ll]);
6264: }
6265: }else{
6266: if(itimes==1){
6267: if(mle>=1)
6268: printf(" Var(%s%1d%1d)",ca,i,j);
6269: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6270: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6271: }else{
6272: if(mle>=1)
6273: printf(" %.5e",matcov[jj][ll]);
6274: fprintf(ficlog," %.5e",matcov[jj][ll]);
6275: fprintf(ficres," %.5e",matcov[jj][ll]);
6276: }
6277: }
6278: }
6279: } /* end lk */
6280: } /* end lj */
6281: } /* end li */
6282: if(mle>=1)
6283: printf("\n");
6284: fprintf(ficlog,"\n");
6285: fprintf(ficres,"\n");
6286: numlinepar++;
6287: } /* end k*/
6288: } /*end j */
6289: } /* end i */
6290: } /* end itimes */
6291:
6292: fflush(ficlog);
6293: fflush(ficres);
6294:
6295: while((c=getc(ficpar))=='#' && c!= EOF){
6296: ungetc(c,ficpar);
6297: fgets(line, MAXLINE, ficpar);
1.141 brouard 6298: fputs(line,stdout);
1.126 brouard 6299: fputs(line,ficparo);
6300: }
6301: ungetc(c,ficpar);
6302:
6303: estepm=0;
6304: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6305: if (estepm==0 || estepm < stepm) estepm=stepm;
6306: if (fage <= 2) {
6307: bage = ageminpar;
6308: fage = agemaxpar;
6309: }
6310:
6311: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6312: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6313: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6314:
6315: while((c=getc(ficpar))=='#' && c!= EOF){
6316: ungetc(c,ficpar);
6317: fgets(line, MAXLINE, ficpar);
1.141 brouard 6318: fputs(line,stdout);
1.126 brouard 6319: fputs(line,ficparo);
6320: }
6321: ungetc(c,ficpar);
6322:
6323: 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);
6324: 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);
6325: 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);
6326: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6327: 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);
6328:
6329: while((c=getc(ficpar))=='#' && c!= EOF){
6330: ungetc(c,ficpar);
6331: fgets(line, MAXLINE, ficpar);
1.141 brouard 6332: fputs(line,stdout);
1.126 brouard 6333: fputs(line,ficparo);
6334: }
6335: ungetc(c,ficpar);
6336:
6337:
6338: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6339: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6340:
6341: fscanf(ficpar,"pop_based=%d\n",&popbased);
6342: fprintf(ficparo,"pop_based=%d\n",popbased);
6343: fprintf(ficres,"pop_based=%d\n",popbased);
6344:
6345: while((c=getc(ficpar))=='#' && c!= EOF){
6346: ungetc(c,ficpar);
6347: fgets(line, MAXLINE, ficpar);
1.141 brouard 6348: fputs(line,stdout);
1.126 brouard 6349: fputs(line,ficparo);
6350: }
6351: ungetc(c,ficpar);
6352:
6353: 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);
6354: 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);
6355: 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);
6356: 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);
6357: 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);
6358: /* day and month of proj2 are not used but only year anproj2.*/
6359:
6360:
6361:
1.145 brouard 6362: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6363: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6364:
6365: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6366: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6367:
6368: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6369: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6370: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6371:
6372: /*------------ free_vector -------------*/
6373: /* chdir(path); */
6374:
6375: free_ivector(wav,1,imx);
6376: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6377: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6378: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6379: free_lvector(num,1,n);
6380: free_vector(agedc,1,n);
6381: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6382: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6383: fclose(ficparo);
6384: fclose(ficres);
6385:
6386:
6387: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6388: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6389: fclose(ficrespl);
6390:
1.145 brouard 6391: #ifdef FREEEXIT2
6392: #include "freeexit2.h"
6393: #endif
6394:
1.126 brouard 6395: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6396: #include "hpijx.h"
6397: fclose(ficrespij);
1.126 brouard 6398:
1.145 brouard 6399: /*-------------- Variance of one-step probabilities---*/
6400: k=1;
1.126 brouard 6401: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6402:
6403:
6404: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6405: for(i=1;i<=AGESUP;i++)
6406: for(j=1;j<=NCOVMAX;j++)
6407: for(k=1;k<=NCOVMAX;k++)
6408: probs[i][j][k]=0.;
6409:
6410: /*---------- Forecasting ------------------*/
6411: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6412: if(prevfcast==1){
6413: /* if(stepm ==1){*/
6414: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6415: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6416: /* } */
6417: /* else{ */
6418: /* erreur=108; */
6419: /* 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); */
6420: /* 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); */
6421: /* } */
6422: }
6423:
6424:
1.127 brouard 6425: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6426:
6427: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6428: /* 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",\
6429: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6430: */
1.126 brouard 6431:
1.127 brouard 6432: if (mobilav!=0) {
6433: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6434: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6435: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6436: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6437: }
1.126 brouard 6438: }
6439:
6440:
1.127 brouard 6441: /*---------- Health expectancies, no variances ------------*/
6442:
1.126 brouard 6443: strcpy(filerese,"e");
6444: strcat(filerese,fileres);
6445: if((ficreseij=fopen(filerese,"w"))==NULL) {
6446: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6447: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6448: }
6449: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6450: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6451: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6452: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6453:
6454: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6455: fprintf(ficreseij,"\n#****** ");
6456: for(j=1;j<=cptcoveff;j++) {
6457: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6458: }
6459: fprintf(ficreseij,"******\n");
6460:
6461: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6462: oldm=oldms;savm=savms;
6463: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6464:
6465: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6466: /*}*/
1.127 brouard 6467: }
6468: fclose(ficreseij);
6469:
6470:
6471: /*---------- Health expectancies and variances ------------*/
6472:
6473:
6474: strcpy(filerest,"t");
6475: strcat(filerest,fileres);
6476: if((ficrest=fopen(filerest,"w"))==NULL) {
6477: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6478: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6479: }
6480: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6481: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6482:
1.126 brouard 6483:
6484: strcpy(fileresstde,"stde");
6485: strcat(fileresstde,fileres);
6486: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6487: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6488: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6489: }
6490: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6491: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6492:
6493: strcpy(filerescve,"cve");
6494: strcat(filerescve,fileres);
6495: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6496: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6497: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6498: }
6499: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6500: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6501:
6502: strcpy(fileresv,"v");
6503: strcat(fileresv,fileres);
6504: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6505: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6506: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6507: }
6508: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6509: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6510:
1.145 brouard 6511: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6512: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6513:
6514: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6515: fprintf(ficrest,"\n#****** ");
1.126 brouard 6516: for(j=1;j<=cptcoveff;j++)
6517: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6518: fprintf(ficrest,"******\n");
6519:
6520: fprintf(ficresstdeij,"\n#****** ");
6521: fprintf(ficrescveij,"\n#****** ");
6522: for(j=1;j<=cptcoveff;j++) {
6523: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6524: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6525: }
6526: fprintf(ficresstdeij,"******\n");
6527: fprintf(ficrescveij,"******\n");
6528:
6529: fprintf(ficresvij,"\n#****** ");
6530: for(j=1;j<=cptcoveff;j++)
6531: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6532: fprintf(ficresvij,"******\n");
6533:
6534: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6535: oldm=oldms;savm=savms;
1.127 brouard 6536: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6537: /*
6538: */
6539: /* goto endfree; */
1.126 brouard 6540:
6541: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6542: pstamp(ficrest);
1.145 brouard 6543:
6544:
1.128 brouard 6545: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6546: oldm=oldms;savm=savms; /* Segmentation fault */
6547: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);
6548: 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 6549: if(vpopbased==1)
6550: 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);
6551: else
6552: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6553: fprintf(ficrest,"# Age e.. (std) ");
6554: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6555: fprintf(ficrest,"\n");
1.126 brouard 6556:
1.128 brouard 6557: epj=vector(1,nlstate+1);
6558: for(age=bage; age <=fage ;age++){
6559: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6560: if (vpopbased==1) {
6561: if(mobilav ==0){
6562: for(i=1; i<=nlstate;i++)
6563: prlim[i][i]=probs[(int)age][i][k];
6564: }else{ /* mobilav */
6565: for(i=1; i<=nlstate;i++)
6566: prlim[i][i]=mobaverage[(int)age][i][k];
6567: }
1.126 brouard 6568: }
6569:
1.128 brouard 6570: fprintf(ficrest," %4.0f",age);
6571: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6572: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6573: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6574: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6575: }
6576: epj[nlstate+1] +=epj[j];
1.126 brouard 6577: }
6578:
1.128 brouard 6579: for(i=1, vepp=0.;i <=nlstate;i++)
6580: for(j=1;j <=nlstate;j++)
6581: vepp += vareij[i][j][(int)age];
6582: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6583: for(j=1;j <=nlstate;j++){
6584: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6585: }
6586: fprintf(ficrest,"\n");
1.126 brouard 6587: }
6588: }
6589: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6590: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6591: free_vector(epj,1,nlstate+1);
1.145 brouard 6592: /*}*/
1.126 brouard 6593: }
6594: free_vector(weight,1,n);
1.145 brouard 6595: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6596: free_imatrix(s,1,maxwav+1,1,n);
6597: free_matrix(anint,1,maxwav,1,n);
6598: free_matrix(mint,1,maxwav,1,n);
6599: free_ivector(cod,1,n);
6600: free_ivector(tab,1,NCOVMAX);
6601: fclose(ficresstdeij);
6602: fclose(ficrescveij);
6603: fclose(ficresvij);
6604: fclose(ficrest);
6605: fclose(ficpar);
6606:
6607: /*------- Variance of period (stable) prevalence------*/
6608:
6609: strcpy(fileresvpl,"vpl");
6610: strcat(fileresvpl,fileres);
6611: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6612: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6613: exit(0);
6614: }
6615: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6616:
1.145 brouard 6617: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6618: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6619:
6620: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6621: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6622: for(j=1;j<=cptcoveff;j++)
6623: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6624: fprintf(ficresvpl,"******\n");
6625:
6626: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6627: oldm=oldms;savm=savms;
6628: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6629: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6630: /*}*/
1.126 brouard 6631: }
6632:
6633: fclose(ficresvpl);
6634:
6635: /*---------- End : free ----------------*/
6636: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6637: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6638: } /* mle==-3 arrives here for freeing */
1.131 brouard 6639: endfree:
1.141 brouard 6640: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6641: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6642: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6643: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6644: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6645: free_matrix(covar,0,NCOVMAX,1,n);
6646: free_matrix(matcov,1,npar,1,npar);
6647: /*free_vector(delti,1,npar);*/
6648: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6649: free_matrix(agev,1,maxwav,1,imx);
6650: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6651:
1.145 brouard 6652: free_ivector(ncodemax,1,NCOVMAX);
6653: free_ivector(Tvar,1,NCOVMAX);
6654: free_ivector(Tprod,1,NCOVMAX);
6655: free_ivector(Tvaraff,1,NCOVMAX);
6656: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6657:
6658: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6659: free_imatrix(codtab,1,100,1,10);
6660: fflush(fichtm);
6661: fflush(ficgp);
6662:
6663:
6664: if((nberr >0) || (nbwarn>0)){
6665: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6666: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6667: }else{
6668: printf("End of Imach\n");
6669: fprintf(ficlog,"End of Imach\n");
6670: }
6671: printf("See log file on %s\n",filelog);
6672: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6673: /*(void) gettimeofday(&end_time,&tzp);*/
6674: rend_time = time(NULL);
6675: end_time = *localtime(&rend_time);
6676: /* tml = *localtime(&end_time.tm_sec); */
6677: strcpy(strtend,asctime(&end_time));
1.126 brouard 6678: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6679: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6680: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6681:
1.157 brouard 6682: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6683: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6684: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6685: /* printf("Total time was %d uSec.\n", total_usecs);*/
6686: /* if(fileappend(fichtm,optionfilehtm)){ */
6687: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6688: fclose(fichtm);
6689: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6690: fclose(fichtmcov);
6691: fclose(ficgp);
6692: fclose(ficlog);
6693: /*------ End -----------*/
6694:
6695:
6696: printf("Before Current directory %s!\n",pathcd);
6697: if(chdir(pathcd) != 0)
6698: printf("Can't move to directory %s!\n",path);
6699: if(getcwd(pathcd,MAXLINE) > 0)
6700: printf("Current directory %s!\n",pathcd);
6701: /*strcat(plotcmd,CHARSEPARATOR);*/
6702: sprintf(plotcmd,"gnuplot");
1.157 brouard 6703: #ifdef _WIN32
1.126 brouard 6704: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6705: #endif
6706: if(!stat(plotcmd,&info)){
1.158 brouard 6707: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6708: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6709: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6710: }else
6711: strcpy(pplotcmd,plotcmd);
1.157 brouard 6712: #ifdef __unix
1.126 brouard 6713: strcpy(plotcmd,GNUPLOTPROGRAM);
6714: if(!stat(plotcmd,&info)){
1.158 brouard 6715: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6716: }else
6717: strcpy(pplotcmd,plotcmd);
6718: #endif
6719: }else
6720: strcpy(pplotcmd,plotcmd);
6721:
6722: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6723: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6724:
6725: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6726: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6727: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6728: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6729: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6730: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6731: }
1.158 brouard 6732: printf(" Successful, please wait...");
1.126 brouard 6733: while (z[0] != 'q') {
6734: /* chdir(path); */
1.154 brouard 6735: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6736: scanf("%s",z);
6737: /* if (z[0] == 'c') system("./imach"); */
6738: if (z[0] == 'e') {
1.158 brouard 6739: #ifdef __APPLE__
1.152 brouard 6740: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6741: #elif __linux
6742: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6743: #else
1.152 brouard 6744: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6745: #endif
6746: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6747: system(pplotcmd);
1.126 brouard 6748: }
6749: else if (z[0] == 'g') system(plotcmd);
6750: else if (z[0] == 'q') exit(0);
6751: }
6752: end:
6753: while (z[0] != 'q') {
6754: printf("\nType q for exiting: ");
6755: scanf("%s",z);
6756: }
6757: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>