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