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