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