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