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