Annotation of imach/src/imach.c, revision 1.164
1.164 ! brouard 1: /* $Id: imach.c,v 1.163 2014/12/16 10:30:11 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.164 ! brouard 4: Revision 1.163 2014/12/16 10:30:11 brouard
! 5: * imach.c (Module): Merging 1.61 to 1.162
! 6:
1.163 brouard 7: Revision 1.162 2014/09/25 11:43:39 brouard
8: Summary: temporary backup 0.99!
9:
1.162 brouard 10: Revision 1.1 2014/09/16 11:06:58 brouard
11: Summary: With some code (wrong) for nlopt
12:
13: Author:
14:
15: Revision 1.161 2014/09/15 20:41:41 brouard
16: Summary: Problem with macro SQR on Intel compiler
17:
1.161 brouard 18: Revision 1.160 2014/09/02 09:24:05 brouard
19: *** empty log message ***
20:
1.160 brouard 21: Revision 1.159 2014/09/01 10:34:10 brouard
22: Summary: WIN32
23: Author: Brouard
24:
1.159 brouard 25: Revision 1.158 2014/08/27 17:11:51 brouard
26: *** empty log message ***
27:
1.158 brouard 28: Revision 1.157 2014/08/27 16:26:55 brouard
29: Summary: Preparing windows Visual studio version
30: Author: Brouard
31:
32: In order to compile on Visual studio, time.h is now correct and time_t
33: and tm struct should be used. difftime should be used but sometimes I
34: just make the differences in raw time format (time(&now).
35: Trying to suppress #ifdef LINUX
36: Add xdg-open for __linux in order to open default browser.
37:
1.157 brouard 38: Revision 1.156 2014/08/25 20:10:10 brouard
39: *** empty log message ***
40:
1.156 brouard 41: Revision 1.155 2014/08/25 18:32:34 brouard
42: Summary: New compile, minor changes
43: Author: Brouard
44:
1.155 brouard 45: Revision 1.154 2014/06/20 17:32:08 brouard
46: Summary: Outputs now all graphs of convergence to period prevalence
47:
1.154 brouard 48: Revision 1.153 2014/06/20 16:45:46 brouard
49: Summary: If 3 live state, convergence to period prevalence on same graph
50: Author: Brouard
51:
1.153 brouard 52: Revision 1.152 2014/06/18 17:54:09 brouard
53: Summary: open browser, use gnuplot on same dir than imach if not found in the path
54:
1.152 brouard 55: Revision 1.151 2014/06/18 16:43:30 brouard
56: *** empty log message ***
57:
1.151 brouard 58: Revision 1.150 2014/06/18 16:42:35 brouard
59: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
60: Author: brouard
61:
1.150 brouard 62: Revision 1.149 2014/06/18 15:51:14 brouard
63: Summary: Some fixes in parameter files errors
64: Author: Nicolas Brouard
65:
1.149 brouard 66: Revision 1.148 2014/06/17 17:38:48 brouard
67: Summary: Nothing new
68: Author: Brouard
69:
70: Just a new packaging for OS/X version 0.98nS
71:
1.148 brouard 72: Revision 1.147 2014/06/16 10:33:11 brouard
73: *** empty log message ***
74:
1.147 brouard 75: Revision 1.146 2014/06/16 10:20:28 brouard
76: Summary: Merge
77: Author: Brouard
78:
79: Merge, before building revised version.
80:
1.146 brouard 81: Revision 1.145 2014/06/10 21:23:15 brouard
82: Summary: Debugging with valgrind
83: Author: Nicolas Brouard
84:
85: Lot of changes in order to output the results with some covariates
86: After the Edimburgh REVES conference 2014, it seems mandatory to
87: improve the code.
88: No more memory valgrind error but a lot has to be done in order to
89: continue the work of splitting the code into subroutines.
90: Also, decodemodel has been improved. Tricode is still not
91: optimal. nbcode should be improved. Documentation has been added in
92: the source code.
93:
1.144 brouard 94: Revision 1.143 2014/01/26 09:45:38 brouard
95: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
96:
97: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
98: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
99:
1.143 brouard 100: Revision 1.142 2014/01/26 03:57:36 brouard
101: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
102:
103: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
104:
1.142 brouard 105: Revision 1.141 2014/01/26 02:42:01 brouard
106: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
107:
1.141 brouard 108: Revision 1.140 2011/09/02 10:37:54 brouard
109: Summary: times.h is ok with mingw32 now.
110:
1.140 brouard 111: Revision 1.139 2010/06/14 07:50:17 brouard
112: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
113: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
114:
1.139 brouard 115: Revision 1.138 2010/04/30 18:19:40 brouard
116: *** empty log message ***
117:
1.138 brouard 118: Revision 1.137 2010/04/29 18:11:38 brouard
119: (Module): Checking covariates for more complex models
120: than V1+V2. A lot of change to be done. Unstable.
121:
1.137 brouard 122: Revision 1.136 2010/04/26 20:30:53 brouard
123: (Module): merging some libgsl code. Fixing computation
124: of likelione (using inter/intrapolation if mle = 0) in order to
125: get same likelihood as if mle=1.
126: Some cleaning of code and comments added.
127:
1.136 brouard 128: Revision 1.135 2009/10/29 15:33:14 brouard
129: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
130:
1.135 brouard 131: Revision 1.134 2009/10/29 13:18:53 brouard
132: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
133:
1.134 brouard 134: Revision 1.133 2009/07/06 10:21:25 brouard
135: just nforces
136:
1.133 brouard 137: Revision 1.132 2009/07/06 08:22:05 brouard
138: Many tings
139:
1.132 brouard 140: Revision 1.131 2009/06/20 16:22:47 brouard
141: Some dimensions resccaled
142:
1.131 brouard 143: Revision 1.130 2009/05/26 06:44:34 brouard
144: (Module): Max Covariate is now set to 20 instead of 8. A
145: lot of cleaning with variables initialized to 0. Trying to make
146: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
147:
1.130 brouard 148: Revision 1.129 2007/08/31 13:49:27 lievre
149: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
150:
1.129 lievre 151: Revision 1.128 2006/06/30 13:02:05 brouard
152: (Module): Clarifications on computing e.j
153:
1.128 brouard 154: Revision 1.127 2006/04/28 18:11:50 brouard
155: (Module): Yes the sum of survivors was wrong since
156: imach-114 because nhstepm was no more computed in the age
157: loop. Now we define nhstepma in the age loop.
158: (Module): In order to speed up (in case of numerous covariates) we
159: compute health expectancies (without variances) in a first step
160: and then all the health expectancies with variances or standard
161: deviation (needs data from the Hessian matrices) which slows the
162: computation.
163: In the future we should be able to stop the program is only health
164: expectancies and graph are needed without standard deviations.
165:
1.127 brouard 166: Revision 1.126 2006/04/28 17:23:28 brouard
167: (Module): Yes the sum of survivors was wrong since
168: imach-114 because nhstepm was no more computed in the age
169: loop. Now we define nhstepma in the age loop.
170: Version 0.98h
171:
1.126 brouard 172: Revision 1.125 2006/04/04 15:20:31 lievre
173: Errors in calculation of health expectancies. Age was not initialized.
174: Forecasting file added.
175:
176: Revision 1.124 2006/03/22 17:13:53 lievre
177: Parameters are printed with %lf instead of %f (more numbers after the comma).
178: The log-likelihood is printed in the log file
179:
180: Revision 1.123 2006/03/20 10:52:43 brouard
181: * imach.c (Module): <title> changed, corresponds to .htm file
182: name. <head> headers where missing.
183:
184: * imach.c (Module): Weights can have a decimal point as for
185: English (a comma might work with a correct LC_NUMERIC environment,
186: otherwise the weight is truncated).
187: Modification of warning when the covariates values are not 0 or
188: 1.
189: Version 0.98g
190:
191: Revision 1.122 2006/03/20 09:45:41 brouard
192: (Module): Weights can have a decimal point as for
193: English (a comma might work with a correct LC_NUMERIC environment,
194: otherwise the weight is truncated).
195: Modification of warning when the covariates values are not 0 or
196: 1.
197: Version 0.98g
198:
199: Revision 1.121 2006/03/16 17:45:01 lievre
200: * imach.c (Module): Comments concerning covariates added
201:
202: * imach.c (Module): refinements in the computation of lli if
203: status=-2 in order to have more reliable computation if stepm is
204: not 1 month. Version 0.98f
205:
206: Revision 1.120 2006/03/16 15:10:38 lievre
207: (Module): refinements in the computation of lli if
208: status=-2 in order to have more reliable computation if stepm is
209: not 1 month. Version 0.98f
210:
211: Revision 1.119 2006/03/15 17:42:26 brouard
212: (Module): Bug if status = -2, the loglikelihood was
213: computed as likelihood omitting the logarithm. Version O.98e
214:
215: Revision 1.118 2006/03/14 18:20:07 brouard
216: (Module): varevsij Comments added explaining the second
217: table of variances if popbased=1 .
218: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
219: (Module): Function pstamp added
220: (Module): Version 0.98d
221:
222: Revision 1.117 2006/03/14 17:16:22 brouard
223: (Module): varevsij Comments added explaining the second
224: table of variances if popbased=1 .
225: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
226: (Module): Function pstamp added
227: (Module): Version 0.98d
228:
229: Revision 1.116 2006/03/06 10:29:27 brouard
230: (Module): Variance-covariance wrong links and
231: varian-covariance of ej. is needed (Saito).
232:
233: Revision 1.115 2006/02/27 12:17:45 brouard
234: (Module): One freematrix added in mlikeli! 0.98c
235:
236: Revision 1.114 2006/02/26 12:57:58 brouard
237: (Module): Some improvements in processing parameter
238: filename with strsep.
239:
240: Revision 1.113 2006/02/24 14:20:24 brouard
241: (Module): Memory leaks checks with valgrind and:
242: datafile was not closed, some imatrix were not freed and on matrix
243: allocation too.
244:
245: Revision 1.112 2006/01/30 09:55:26 brouard
246: (Module): Back to gnuplot.exe instead of wgnuplot.exe
247:
248: Revision 1.111 2006/01/25 20:38:18 brouard
249: (Module): Lots of cleaning and bugs added (Gompertz)
250: (Module): Comments can be added in data file. Missing date values
251: can be a simple dot '.'.
252:
253: Revision 1.110 2006/01/25 00:51:50 brouard
254: (Module): Lots of cleaning and bugs added (Gompertz)
255:
256: Revision 1.109 2006/01/24 19:37:15 brouard
257: (Module): Comments (lines starting with a #) are allowed in data.
258:
259: Revision 1.108 2006/01/19 18:05:42 lievre
260: Gnuplot problem appeared...
261: To be fixed
262:
263: Revision 1.107 2006/01/19 16:20:37 brouard
264: Test existence of gnuplot in imach path
265:
266: Revision 1.106 2006/01/19 13:24:36 brouard
267: Some cleaning and links added in html output
268:
269: Revision 1.105 2006/01/05 20:23:19 lievre
270: *** empty log message ***
271:
272: Revision 1.104 2005/09/30 16:11:43 lievre
273: (Module): sump fixed, loop imx fixed, and simplifications.
274: (Module): If the status is missing at the last wave but we know
275: that the person is alive, then we can code his/her status as -2
276: (instead of missing=-1 in earlier versions) and his/her
277: contributions to the likelihood is 1 - Prob of dying from last
278: health status (= 1-p13= p11+p12 in the easiest case of somebody in
279: the healthy state at last known wave). Version is 0.98
280:
281: Revision 1.103 2005/09/30 15:54:49 lievre
282: (Module): sump fixed, loop imx fixed, and simplifications.
283:
284: Revision 1.102 2004/09/15 17:31:30 brouard
285: Add the possibility to read data file including tab characters.
286:
287: Revision 1.101 2004/09/15 10:38:38 brouard
288: Fix on curr_time
289:
290: Revision 1.100 2004/07/12 18:29:06 brouard
291: Add version for Mac OS X. Just define UNIX in Makefile
292:
293: Revision 1.99 2004/06/05 08:57:40 brouard
294: *** empty log message ***
295:
296: Revision 1.98 2004/05/16 15:05:56 brouard
297: New version 0.97 . First attempt to estimate force of mortality
298: directly from the data i.e. without the need of knowing the health
299: state at each age, but using a Gompertz model: log u =a + b*age .
300: This is the basic analysis of mortality and should be done before any
301: other analysis, in order to test if the mortality estimated from the
302: cross-longitudinal survey is different from the mortality estimated
303: from other sources like vital statistic data.
304:
305: The same imach parameter file can be used but the option for mle should be -3.
306:
1.133 brouard 307: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 308: former routines in order to include the new code within the former code.
309:
310: The output is very simple: only an estimate of the intercept and of
311: the slope with 95% confident intervals.
312:
313: Current limitations:
314: A) Even if you enter covariates, i.e. with the
315: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
316: B) There is no computation of Life Expectancy nor Life Table.
317:
318: Revision 1.97 2004/02/20 13:25:42 lievre
319: Version 0.96d. Population forecasting command line is (temporarily)
320: suppressed.
321:
322: Revision 1.96 2003/07/15 15:38:55 brouard
323: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
324: rewritten within the same printf. Workaround: many printfs.
325:
326: Revision 1.95 2003/07/08 07:54:34 brouard
327: * imach.c (Repository):
328: (Repository): Using imachwizard code to output a more meaningful covariance
329: matrix (cov(a12,c31) instead of numbers.
330:
331: Revision 1.94 2003/06/27 13:00:02 brouard
332: Just cleaning
333:
334: Revision 1.93 2003/06/25 16:33:55 brouard
335: (Module): On windows (cygwin) function asctime_r doesn't
336: exist so I changed back to asctime which exists.
337: (Module): Version 0.96b
338:
339: Revision 1.92 2003/06/25 16:30:45 brouard
340: (Module): On windows (cygwin) function asctime_r doesn't
341: exist so I changed back to asctime which exists.
342:
343: Revision 1.91 2003/06/25 15:30:29 brouard
344: * imach.c (Repository): Duplicated warning errors corrected.
345: (Repository): Elapsed time after each iteration is now output. It
346: helps to forecast when convergence will be reached. Elapsed time
347: is stamped in powell. We created a new html file for the graphs
348: concerning matrix of covariance. It has extension -cov.htm.
349:
350: Revision 1.90 2003/06/24 12:34:15 brouard
351: (Module): Some bugs corrected for windows. Also, when
352: mle=-1 a template is output in file "or"mypar.txt with the design
353: of the covariance matrix to be input.
354:
355: Revision 1.89 2003/06/24 12:30:52 brouard
356: (Module): Some bugs corrected for windows. Also, when
357: mle=-1 a template is output in file "or"mypar.txt with the design
358: of the covariance matrix to be input.
359:
360: Revision 1.88 2003/06/23 17:54:56 brouard
361: * 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.
362:
363: Revision 1.87 2003/06/18 12:26:01 brouard
364: Version 0.96
365:
366: Revision 1.86 2003/06/17 20:04:08 brouard
367: (Module): Change position of html and gnuplot routines and added
368: routine fileappend.
369:
370: Revision 1.85 2003/06/17 13:12:43 brouard
371: * imach.c (Repository): Check when date of death was earlier that
372: current date of interview. It may happen when the death was just
373: prior to the death. In this case, dh was negative and likelihood
374: was wrong (infinity). We still send an "Error" but patch by
375: assuming that the date of death was just one stepm after the
376: interview.
377: (Repository): Because some people have very long ID (first column)
378: we changed int to long in num[] and we added a new lvector for
379: memory allocation. But we also truncated to 8 characters (left
380: truncation)
381: (Repository): No more line truncation errors.
382:
383: Revision 1.84 2003/06/13 21:44:43 brouard
384: * imach.c (Repository): Replace "freqsummary" at a correct
385: place. It differs from routine "prevalence" which may be called
386: many times. Probs is memory consuming and must be used with
387: parcimony.
388: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
389:
390: Revision 1.83 2003/06/10 13:39:11 lievre
391: *** empty log message ***
392:
393: Revision 1.82 2003/06/05 15:57:20 brouard
394: Add log in imach.c and fullversion number is now printed.
395:
396: */
397: /*
398: Interpolated Markov Chain
399:
400: Short summary of the programme:
401:
402: This program computes Healthy Life Expectancies from
403: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
404: first survey ("cross") where individuals from different ages are
405: interviewed on their health status or degree of disability (in the
406: case of a health survey which is our main interest) -2- at least a
407: second wave of interviews ("longitudinal") which measure each change
408: (if any) in individual health status. Health expectancies are
409: computed from the time spent in each health state according to a
410: model. More health states you consider, more time is necessary to reach the
411: Maximum Likelihood of the parameters involved in the model. The
412: simplest model is the multinomial logistic model where pij is the
413: probability to be observed in state j at the second wave
414: conditional to be observed in state i at the first wave. Therefore
415: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
416: 'age' is age and 'sex' is a covariate. If you want to have a more
417: complex model than "constant and age", you should modify the program
418: where the markup *Covariates have to be included here again* invites
419: you to do it. More covariates you add, slower the
420: convergence.
421:
422: The advantage of this computer programme, compared to a simple
423: multinomial logistic model, is clear when the delay between waves is not
424: identical for each individual. Also, if a individual missed an
425: intermediate interview, the information is lost, but taken into
426: account using an interpolation or extrapolation.
427:
428: hPijx is the probability to be observed in state i at age x+h
429: conditional to the observed state i at age x. The delay 'h' can be
430: split into an exact number (nh*stepm) of unobserved intermediate
431: states. This elementary transition (by month, quarter,
432: semester or year) is modelled as a multinomial logistic. The hPx
433: matrix is simply the matrix product of nh*stepm elementary matrices
434: and the contribution of each individual to the likelihood is simply
435: hPijx.
436:
437: Also this programme outputs the covariance matrix of the parameters but also
438: of the life expectancies. It also computes the period (stable) prevalence.
439:
1.133 brouard 440: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
441: Institut national d'études démographiques, Paris.
1.126 brouard 442: This software have been partly granted by Euro-REVES, a concerted action
443: from the European Union.
444: It is copyrighted identically to a GNU software product, ie programme and
445: software can be distributed freely for non commercial use. Latest version
446: can be accessed at http://euroreves.ined.fr/imach .
447:
448: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
449: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
450:
451: **********************************************************************/
452: /*
453: main
454: read parameterfile
455: read datafile
456: concatwav
457: freqsummary
458: if (mle >= 1)
459: mlikeli
460: print results files
461: if mle==1
462: computes hessian
463: read end of parameter file: agemin, agemax, bage, fage, estepm
464: begin-prev-date,...
465: open gnuplot file
466: open html file
1.145 brouard 467: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
468: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
469: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
470: freexexit2 possible for memory heap.
471:
472: h Pij x | pij_nom ficrestpij
473: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
474: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
475: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
476:
477: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
478: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
479: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
480: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
481: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
482:
1.126 brouard 483: forecasting if prevfcast==1 prevforecast call prevalence()
484: health expectancies
485: Variance-covariance of DFLE
486: prevalence()
487: movingaverage()
488: varevsij()
489: if popbased==1 varevsij(,popbased)
490: total life expectancies
491: Variance of period (stable) prevalence
492: end
493: */
494:
495:
496:
497:
498: #include <math.h>
499: #include <stdio.h>
500: #include <stdlib.h>
501: #include <string.h>
1.159 brouard 502:
503: #ifdef _WIN32
504: #include <io.h>
505: #else
1.126 brouard 506: #include <unistd.h>
1.159 brouard 507: #endif
1.126 brouard 508:
509: #include <limits.h>
510: #include <sys/types.h>
511: #include <sys/stat.h>
512: #include <errno.h>
1.159 brouard 513: /* extern int errno; */
1.126 brouard 514:
1.157 brouard 515: /* #ifdef LINUX */
516: /* #include <time.h> */
517: /* #include "timeval.h" */
518: /* #else */
519: /* #include <sys/time.h> */
520: /* #endif */
521:
1.126 brouard 522: #include <time.h>
523:
1.136 brouard 524: #ifdef GSL
525: #include <gsl/gsl_errno.h>
526: #include <gsl/gsl_multimin.h>
527: #endif
528:
1.162 brouard 529: #ifdef NLOPT
530: #include <nlopt.h>
531: typedef struct {
532: double (* function)(double [] );
533: } myfunc_data ;
534: #endif
535:
1.126 brouard 536: /* #include <libintl.h> */
537: /* #define _(String) gettext (String) */
538:
1.141 brouard 539: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 540:
541: #define GNUPLOTPROGRAM "gnuplot"
542: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
543: #define FILENAMELENGTH 132
544:
545: #define GLOCK_ERROR_NOPATH -1 /* empty path */
546: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
547:
1.144 brouard 548: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
549: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 550:
551: #define NINTERVMAX 8
1.144 brouard 552: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
553: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
554: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 555: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 556: #define MAXN 20000
1.144 brouard 557: #define YEARM 12. /**< Number of months per year */
1.126 brouard 558: #define AGESUP 130
559: #define AGEBASE 40
1.164 ! brouard 560: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 561: #ifdef _WIN32
562: #define DIRSEPARATOR '\\'
563: #define CHARSEPARATOR "\\"
564: #define ODIRSEPARATOR '/'
565: #else
1.126 brouard 566: #define DIRSEPARATOR '/'
567: #define CHARSEPARATOR "/"
568: #define ODIRSEPARATOR '\\'
569: #endif
570:
1.164 ! brouard 571: /* $Id: imach.c,v 1.163 2014/12/16 10:30:11 brouard Exp $ */
1.126 brouard 572: /* $State: Exp $ */
573:
1.162 brouard 574: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.164 ! brouard 575: char fullversion[]="$Revision: 1.163 $ $Date: 2014/12/16 10:30:11 $";
1.126 brouard 576: char strstart[80];
577: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 578: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 579: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 580: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
581: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
582: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
583: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
584: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
585: int cptcovprodnoage=0; /**< Number of covariate products without age */
586: int cptcoveff=0; /* Total number of covariates to vary for printing results */
587: int cptcov=0; /* Working variable */
1.126 brouard 588: int npar=NPARMAX;
589: int nlstate=2; /* Number of live states */
590: int ndeath=1; /* Number of dead states */
1.130 brouard 591: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 592: int popbased=0;
593:
594: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 595: int maxwav=0; /* Maxim number of waves */
596: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
597: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
598: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 599: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 600: int mle=1, weightopt=0;
1.126 brouard 601: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
602: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
603: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
604: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 605: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 606: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 607: double **matprod2(); /* test */
1.126 brouard 608: double **oldm, **newm, **savm; /* Working pointers to matrices */
609: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 610: /*FILE *fic ; */ /* Used in readdata only */
611: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 612: FILE *ficlog, *ficrespow;
1.130 brouard 613: int globpr=0; /* Global variable for printing or not */
1.126 brouard 614: double fretone; /* Only one call to likelihood */
1.130 brouard 615: long ipmx=0; /* Number of contributions */
1.126 brouard 616: double sw; /* Sum of weights */
617: char filerespow[FILENAMELENGTH];
618: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
619: FILE *ficresilk;
620: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
621: FILE *ficresprobmorprev;
622: FILE *fichtm, *fichtmcov; /* Html File */
623: FILE *ficreseij;
624: char filerese[FILENAMELENGTH];
625: FILE *ficresstdeij;
626: char fileresstde[FILENAMELENGTH];
627: FILE *ficrescveij;
628: char filerescve[FILENAMELENGTH];
629: FILE *ficresvij;
630: char fileresv[FILENAMELENGTH];
631: FILE *ficresvpl;
632: char fileresvpl[FILENAMELENGTH];
633: char title[MAXLINE];
634: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
635: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
636: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
637: char command[FILENAMELENGTH];
638: int outcmd=0;
639:
640: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
641:
642: char filelog[FILENAMELENGTH]; /* Log file */
643: char filerest[FILENAMELENGTH];
644: char fileregp[FILENAMELENGTH];
645: char popfile[FILENAMELENGTH];
646:
647: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
648:
1.157 brouard 649: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
650: /* struct timezone tzp; */
651: /* extern int gettimeofday(); */
652: struct tm tml, *gmtime(), *localtime();
653:
654: extern time_t time();
655:
656: struct tm start_time, end_time, curr_time, last_time, forecast_time;
657: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
658: struct tm tm;
659:
1.126 brouard 660: char strcurr[80], strfor[80];
661:
662: char *endptr;
663: long lval;
664: double dval;
665:
666: #define NR_END 1
667: #define FREE_ARG char*
668: #define FTOL 1.0e-10
669:
670: #define NRANSI
671: #define ITMAX 200
672:
673: #define TOL 2.0e-4
674:
675: #define CGOLD 0.3819660
676: #define ZEPS 1.0e-10
677: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
678:
679: #define GOLD 1.618034
680: #define GLIMIT 100.0
681: #define TINY 1.0e-20
682:
683: static double maxarg1,maxarg2;
684: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
685: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
686:
687: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
688: #define rint(a) floor(a+0.5)
689:
690: static double sqrarg;
691: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
692: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
693: int agegomp= AGEGOMP;
694:
695: int imx;
696: int stepm=1;
697: /* Stepm, step in month: minimum step interpolation*/
698:
699: int estepm;
700: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
701:
702: int m,nb;
703: long *num;
704: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
705: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
706: double **pmmij, ***probs;
707: double *ageexmed,*agecens;
708: double dateintmean=0;
709:
710: double *weight;
711: int **s; /* Status */
1.141 brouard 712: double *agedc;
1.145 brouard 713: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 714: * covar=matrix(0,NCOVMAX,1,n);
715: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
716: double idx;
717: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 718: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 719: int **codtab; /**< codtab=imatrix(1,100,1,10); */
720: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 721: double *lsurv, *lpop, *tpop;
722:
1.143 brouard 723: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
724: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 725:
726: /**************** split *************************/
727: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
728: {
729: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
730: the name of the file (name), its extension only (ext) and its first part of the name (finame)
731: */
732: char *ss; /* pointer */
733: int l1, l2; /* length counters */
734:
735: l1 = strlen(path ); /* length of path */
736: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
737: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
738: if ( ss == NULL ) { /* no directory, so determine current directory */
739: strcpy( name, path ); /* we got the fullname name because no directory */
740: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
741: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
742: /* get current working directory */
743: /* extern char* getcwd ( char *buf , int len);*/
744: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
745: return( GLOCK_ERROR_GETCWD );
746: }
747: /* got dirc from getcwd*/
748: printf(" DIRC = %s \n",dirc);
749: } else { /* strip direcotry from path */
750: ss++; /* after this, the filename */
751: l2 = strlen( ss ); /* length of filename */
752: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
753: strcpy( name, ss ); /* save file name */
754: strncpy( dirc, path, l1 - l2 ); /* now the directory */
755: dirc[l1-l2] = 0; /* add zero */
756: printf(" DIRC2 = %s \n",dirc);
757: }
758: /* We add a separator at the end of dirc if not exists */
759: l1 = strlen( dirc ); /* length of directory */
760: if( dirc[l1-1] != DIRSEPARATOR ){
761: dirc[l1] = DIRSEPARATOR;
762: dirc[l1+1] = 0;
763: printf(" DIRC3 = %s \n",dirc);
764: }
765: ss = strrchr( name, '.' ); /* find last / */
766: if (ss >0){
767: ss++;
768: strcpy(ext,ss); /* save extension */
769: l1= strlen( name);
770: l2= strlen(ss)+1;
771: strncpy( finame, name, l1-l2);
772: finame[l1-l2]= 0;
773: }
774:
775: return( 0 ); /* we're done */
776: }
777:
778:
779: /******************************************/
780:
781: void replace_back_to_slash(char *s, char*t)
782: {
783: int i;
784: int lg=0;
785: i=0;
786: lg=strlen(t);
787: for(i=0; i<= lg; i++) {
788: (s[i] = t[i]);
789: if (t[i]== '\\') s[i]='/';
790: }
791: }
792:
1.132 brouard 793: char *trimbb(char *out, char *in)
1.137 brouard 794: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 795: char *s;
796: s=out;
797: while (*in != '\0'){
1.137 brouard 798: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 799: in++;
800: }
801: *out++ = *in++;
802: }
803: *out='\0';
804: return s;
805: }
806:
1.145 brouard 807: char *cutl(char *blocc, char *alocc, char *in, char occ)
808: {
809: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
810: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
811: gives blocc="abcdef2ghi" and alocc="j".
812: If occ is not found blocc is null and alocc is equal to in. Returns blocc
813: */
1.160 brouard 814: char *s, *t;
1.145 brouard 815: t=in;s=in;
816: while ((*in != occ) && (*in != '\0')){
817: *alocc++ = *in++;
818: }
819: if( *in == occ){
820: *(alocc)='\0';
821: s=++in;
822: }
823:
824: if (s == t) {/* occ not found */
825: *(alocc-(in-s))='\0';
826: in=s;
827: }
828: while ( *in != '\0'){
829: *blocc++ = *in++;
830: }
831:
832: *blocc='\0';
833: return t;
834: }
1.137 brouard 835: char *cutv(char *blocc, char *alocc, char *in, char occ)
836: {
837: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
838: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
839: gives blocc="abcdef2ghi" and alocc="j".
840: If occ is not found blocc is null and alocc is equal to in. Returns alocc
841: */
842: char *s, *t;
843: t=in;s=in;
844: while (*in != '\0'){
845: while( *in == occ){
846: *blocc++ = *in++;
847: s=in;
848: }
849: *blocc++ = *in++;
850: }
851: if (s == t) /* occ not found */
852: *(blocc-(in-s))='\0';
853: else
854: *(blocc-(in-s)-1)='\0';
855: in=s;
856: while ( *in != '\0'){
857: *alocc++ = *in++;
858: }
859:
860: *alocc='\0';
861: return s;
862: }
863:
1.126 brouard 864: int nbocc(char *s, char occ)
865: {
866: int i,j=0;
867: int lg=20;
868: i=0;
869: lg=strlen(s);
870: for(i=0; i<= lg; i++) {
871: if (s[i] == occ ) j++;
872: }
873: return j;
874: }
875:
1.137 brouard 876: /* void cutv(char *u,char *v, char*t, char occ) */
877: /* { */
878: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
879: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
880: /* gives u="abcdef2ghi" and v="j" *\/ */
881: /* int i,lg,j,p=0; */
882: /* i=0; */
883: /* lg=strlen(t); */
884: /* for(j=0; j<=lg-1; j++) { */
885: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
886: /* } */
1.126 brouard 887:
1.137 brouard 888: /* for(j=0; j<p; j++) { */
889: /* (u[j] = t[j]); */
890: /* } */
891: /* u[p]='\0'; */
1.126 brouard 892:
1.137 brouard 893: /* for(j=0; j<= lg; j++) { */
894: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
895: /* } */
896: /* } */
1.126 brouard 897:
1.160 brouard 898: #ifdef _WIN32
899: char * strsep(char **pp, const char *delim)
900: {
901: char *p, *q;
902:
903: if ((p = *pp) == NULL)
904: return 0;
905: if ((q = strpbrk (p, delim)) != NULL)
906: {
907: *pp = q + 1;
908: *q = '\0';
909: }
910: else
911: *pp = 0;
912: return p;
913: }
914: #endif
915:
1.126 brouard 916: /********************** nrerror ********************/
917:
918: void nrerror(char error_text[])
919: {
920: fprintf(stderr,"ERREUR ...\n");
921: fprintf(stderr,"%s\n",error_text);
922: exit(EXIT_FAILURE);
923: }
924: /*********************** vector *******************/
925: double *vector(int nl, int nh)
926: {
927: double *v;
928: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
929: if (!v) nrerror("allocation failure in vector");
930: return v-nl+NR_END;
931: }
932:
933: /************************ free vector ******************/
934: void free_vector(double*v, int nl, int nh)
935: {
936: free((FREE_ARG)(v+nl-NR_END));
937: }
938:
939: /************************ivector *******************************/
940: int *ivector(long nl,long nh)
941: {
942: int *v;
943: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
944: if (!v) nrerror("allocation failure in ivector");
945: return v-nl+NR_END;
946: }
947:
948: /******************free ivector **************************/
949: void free_ivector(int *v, long nl, long nh)
950: {
951: free((FREE_ARG)(v+nl-NR_END));
952: }
953:
954: /************************lvector *******************************/
955: long *lvector(long nl,long nh)
956: {
957: long *v;
958: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
959: if (!v) nrerror("allocation failure in ivector");
960: return v-nl+NR_END;
961: }
962:
963: /******************free lvector **************************/
964: void free_lvector(long *v, long nl, long nh)
965: {
966: free((FREE_ARG)(v+nl-NR_END));
967: }
968:
969: /******************* imatrix *******************************/
970: int **imatrix(long nrl, long nrh, long ncl, long nch)
971: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
972: {
973: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
974: int **m;
975:
976: /* allocate pointers to rows */
977: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
978: if (!m) nrerror("allocation failure 1 in matrix()");
979: m += NR_END;
980: m -= nrl;
981:
982:
983: /* allocate rows and set pointers to them */
984: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
985: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
986: m[nrl] += NR_END;
987: m[nrl] -= ncl;
988:
989: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
990:
991: /* return pointer to array of pointers to rows */
992: return m;
993: }
994:
995: /****************** free_imatrix *************************/
996: void free_imatrix(m,nrl,nrh,ncl,nch)
997: int **m;
998: long nch,ncl,nrh,nrl;
999: /* free an int matrix allocated by imatrix() */
1000: {
1001: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1002: free((FREE_ARG) (m+nrl-NR_END));
1003: }
1004:
1005: /******************* matrix *******************************/
1006: double **matrix(long nrl, long nrh, long ncl, long nch)
1007: {
1008: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1009: double **m;
1010:
1011: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1012: if (!m) nrerror("allocation failure 1 in matrix()");
1013: m += NR_END;
1014: m -= nrl;
1015:
1016: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1017: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1018: m[nrl] += NR_END;
1019: m[nrl] -= ncl;
1020:
1021: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1022: return m;
1.145 brouard 1023: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1024: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1025: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1026: */
1027: }
1028:
1029: /*************************free matrix ************************/
1030: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1031: {
1032: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1033: free((FREE_ARG)(m+nrl-NR_END));
1034: }
1035:
1036: /******************* ma3x *******************************/
1037: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1038: {
1039: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1040: double ***m;
1041:
1042: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1043: if (!m) nrerror("allocation failure 1 in matrix()");
1044: m += NR_END;
1045: m -= nrl;
1046:
1047: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1048: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1049: m[nrl] += NR_END;
1050: m[nrl] -= ncl;
1051:
1052: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1053:
1054: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1055: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1056: m[nrl][ncl] += NR_END;
1057: m[nrl][ncl] -= nll;
1058: for (j=ncl+1; j<=nch; j++)
1059: m[nrl][j]=m[nrl][j-1]+nlay;
1060:
1061: for (i=nrl+1; i<=nrh; i++) {
1062: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1063: for (j=ncl+1; j<=nch; j++)
1064: m[i][j]=m[i][j-1]+nlay;
1065: }
1066: return m;
1067: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1068: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1069: */
1070: }
1071:
1072: /*************************free ma3x ************************/
1073: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1074: {
1075: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1076: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1077: free((FREE_ARG)(m+nrl-NR_END));
1078: }
1079:
1080: /*************** function subdirf ***********/
1081: char *subdirf(char fileres[])
1082: {
1083: /* Caution optionfilefiname is hidden */
1084: strcpy(tmpout,optionfilefiname);
1085: strcat(tmpout,"/"); /* Add to the right */
1086: strcat(tmpout,fileres);
1087: return tmpout;
1088: }
1089:
1090: /*************** function subdirf2 ***********/
1091: char *subdirf2(char fileres[], char *preop)
1092: {
1093:
1094: /* Caution optionfilefiname is hidden */
1095: strcpy(tmpout,optionfilefiname);
1096: strcat(tmpout,"/");
1097: strcat(tmpout,preop);
1098: strcat(tmpout,fileres);
1099: return tmpout;
1100: }
1101:
1102: /*************** function subdirf3 ***********/
1103: char *subdirf3(char fileres[], char *preop, char *preop2)
1104: {
1105:
1106: /* Caution optionfilefiname is hidden */
1107: strcpy(tmpout,optionfilefiname);
1108: strcat(tmpout,"/");
1109: strcat(tmpout,preop);
1110: strcat(tmpout,preop2);
1111: strcat(tmpout,fileres);
1112: return tmpout;
1113: }
1114:
1.162 brouard 1115: char *asc_diff_time(long time_sec, char ascdiff[])
1116: {
1117: long sec_left, days, hours, minutes;
1118: days = (time_sec) / (60*60*24);
1119: sec_left = (time_sec) % (60*60*24);
1120: hours = (sec_left) / (60*60) ;
1121: sec_left = (sec_left) %(60*60);
1122: minutes = (sec_left) /60;
1123: sec_left = (sec_left) % (60);
1124: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1125: return ascdiff;
1126: }
1127:
1.126 brouard 1128: /***************** f1dim *************************/
1129: extern int ncom;
1130: extern double *pcom,*xicom;
1131: extern double (*nrfunc)(double []);
1132:
1133: double f1dim(double x)
1134: {
1135: int j;
1136: double f;
1137: double *xt;
1138:
1139: xt=vector(1,ncom);
1140: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1141: f=(*nrfunc)(xt);
1142: free_vector(xt,1,ncom);
1143: return f;
1144: }
1145:
1146: /*****************brent *************************/
1147: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1148: {
1149: int iter;
1150: double a,b,d,etemp;
1.159 brouard 1151: double fu=0,fv,fw,fx;
1.164 ! brouard 1152: double ftemp=0.;
1.126 brouard 1153: double p,q,r,tol1,tol2,u,v,w,x,xm;
1154: double e=0.0;
1155:
1156: a=(ax < cx ? ax : cx);
1157: b=(ax > cx ? ax : cx);
1158: x=w=v=bx;
1159: fw=fv=fx=(*f)(x);
1160: for (iter=1;iter<=ITMAX;iter++) {
1161: xm=0.5*(a+b);
1162: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1163: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1164: printf(".");fflush(stdout);
1165: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1166: #ifdef DEBUGBRENT
1.126 brouard 1167: 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);
1168: 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);
1169: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1170: #endif
1171: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1172: *xmin=x;
1173: return fx;
1174: }
1175: ftemp=fu;
1176: if (fabs(e) > tol1) {
1177: r=(x-w)*(fx-fv);
1178: q=(x-v)*(fx-fw);
1179: p=(x-v)*q-(x-w)*r;
1180: q=2.0*(q-r);
1181: if (q > 0.0) p = -p;
1182: q=fabs(q);
1183: etemp=e;
1184: e=d;
1185: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1186: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1187: else {
1188: d=p/q;
1189: u=x+d;
1190: if (u-a < tol2 || b-u < tol2)
1191: d=SIGN(tol1,xm-x);
1192: }
1193: } else {
1194: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1195: }
1196: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1197: fu=(*f)(u);
1198: if (fu <= fx) {
1199: if (u >= x) a=x; else b=x;
1200: SHFT(v,w,x,u)
1201: SHFT(fv,fw,fx,fu)
1202: } else {
1203: if (u < x) a=u; else b=u;
1204: if (fu <= fw || w == x) {
1205: v=w;
1206: w=u;
1207: fv=fw;
1208: fw=fu;
1209: } else if (fu <= fv || v == x || v == w) {
1210: v=u;
1211: fv=fu;
1212: }
1213: }
1214: }
1215: nrerror("Too many iterations in brent");
1216: *xmin=x;
1217: return fx;
1218: }
1219:
1220: /****************** mnbrak ***********************/
1221:
1222: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1223: double (*func)(double))
1224: {
1225: double ulim,u,r,q, dum;
1226: double fu;
1227:
1228: *fa=(*func)(*ax);
1229: *fb=(*func)(*bx);
1230: if (*fb > *fa) {
1231: SHFT(dum,*ax,*bx,dum)
1232: SHFT(dum,*fb,*fa,dum)
1233: }
1234: *cx=(*bx)+GOLD*(*bx-*ax);
1235: *fc=(*func)(*cx);
1.162 brouard 1236: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1237: r=(*bx-*ax)*(*fb-*fc);
1238: q=(*bx-*cx)*(*fb-*fa);
1239: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1240: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1241: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1242: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1243: fu=(*func)(u);
1.163 brouard 1244: #ifdef DEBUG
1245: /* f(x)=A(x-u)**2+f(u) */
1246: double A, fparabu;
1247: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1248: fparabu= *fa - A*(*ax-u)*(*ax-u);
1249: printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1250: fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1251: #endif
1.162 brouard 1252: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1253: fu=(*func)(u);
1254: if (fu < *fc) {
1255: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1256: SHFT(*fb,*fc,fu,(*func)(u))
1257: }
1.162 brouard 1258: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1259: u=ulim;
1260: fu=(*func)(u);
1261: } else {
1262: u=(*cx)+GOLD*(*cx-*bx);
1263: fu=(*func)(u);
1264: }
1265: SHFT(*ax,*bx,*cx,u)
1266: SHFT(*fa,*fb,*fc,fu)
1267: }
1268: }
1269:
1270: /*************** linmin ************************/
1.162 brouard 1271: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1272: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1273: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1274: the value of func at the returned location p . This is actually all accomplished by calling the
1275: routines mnbrak and brent .*/
1.126 brouard 1276: int ncom;
1277: double *pcom,*xicom;
1278: double (*nrfunc)(double []);
1279:
1280: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1281: {
1282: double brent(double ax, double bx, double cx,
1283: double (*f)(double), double tol, double *xmin);
1284: double f1dim(double x);
1285: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1286: double *fc, double (*func)(double));
1287: int j;
1288: double xx,xmin,bx,ax;
1289: double fx,fb,fa;
1290:
1291: ncom=n;
1292: pcom=vector(1,n);
1293: xicom=vector(1,n);
1294: nrfunc=func;
1295: for (j=1;j<=n;j++) {
1296: pcom[j]=p[j];
1297: xicom[j]=xi[j];
1298: }
1299: ax=0.0;
1300: xx=1.0;
1.162 brouard 1301: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1302: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1.126 brouard 1303: #ifdef DEBUG
1304: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1305: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1306: #endif
1307: for (j=1;j<=n;j++) {
1308: xi[j] *= xmin;
1309: p[j] += xi[j];
1310: }
1311: free_vector(xicom,1,n);
1312: free_vector(pcom,1,n);
1313: }
1314:
1315:
1316: /*************** powell ************************/
1.162 brouard 1317: /*
1318: Minimization of a function func of n variables. Input consists of an initial starting point
1319: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1320: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1321: such that failure to decrease by more than this amount on one iteration signals doneness. On
1322: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1323: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1324: */
1.126 brouard 1325: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1326: double (*func)(double []))
1327: {
1328: void linmin(double p[], double xi[], int n, double *fret,
1329: double (*func)(double []));
1330: int i,ibig,j;
1331: double del,t,*pt,*ptt,*xit;
1332: double fp,fptt;
1333: double *xits;
1334: int niterf, itmp;
1335:
1336: pt=vector(1,n);
1337: ptt=vector(1,n);
1338: xit=vector(1,n);
1339: xits=vector(1,n);
1340: *fret=(*func)(p);
1341: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1342: rcurr_time = time(NULL);
1.126 brouard 1343: for (*iter=1;;++(*iter)) {
1344: fp=(*fret);
1345: ibig=0;
1346: del=0.0;
1.157 brouard 1347: rlast_time=rcurr_time;
1348: /* (void) gettimeofday(&curr_time,&tzp); */
1349: rcurr_time = time(NULL);
1350: curr_time = *localtime(&rcurr_time);
1351: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1352: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1353: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1354: for (i=1;i<=n;i++) {
1355: printf(" %d %.12f",i, p[i]);
1356: fprintf(ficlog," %d %.12lf",i, p[i]);
1357: fprintf(ficrespow," %.12lf", p[i]);
1358: }
1359: printf("\n");
1360: fprintf(ficlog,"\n");
1361: fprintf(ficrespow,"\n");fflush(ficrespow);
1362: if(*iter <=3){
1.157 brouard 1363: tml = *localtime(&rcurr_time);
1364: strcpy(strcurr,asctime(&tml));
1365: rforecast_time=rcurr_time;
1.126 brouard 1366: itmp = strlen(strcurr);
1367: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1368: strcurr[itmp-1]='\0';
1.162 brouard 1369: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1370: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1371: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1372: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1373: forecast_time = *localtime(&rforecast_time);
1374: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1375: itmp = strlen(strfor);
1376: if(strfor[itmp-1]=='\n')
1377: strfor[itmp-1]='\0';
1.157 brouard 1378: printf(" - if your program needs %d iterations to converge, convergence will be \n reached in %s i.e.\n on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1379: fprintf(ficlog," - if your program needs %d iterations to converge, convergence will be \n reached in %s i.e.\n on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126 brouard 1380: }
1381: }
1382: for (i=1;i<=n;i++) {
1383: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1384: fptt=(*fret);
1385: #ifdef DEBUG
1.164 ! brouard 1386: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
! 1387: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1388: #endif
1389: printf("%d",i);fflush(stdout);
1390: fprintf(ficlog,"%d",i);fflush(ficlog);
1391: linmin(p,xit,n,fret,func);
1392: if (fabs(fptt-(*fret)) > del) {
1393: del=fabs(fptt-(*fret));
1394: ibig=i;
1395: }
1396: #ifdef DEBUG
1397: printf("%d %.12e",i,(*fret));
1398: fprintf(ficlog,"%d %.12e",i,(*fret));
1399: for (j=1;j<=n;j++) {
1400: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1401: printf(" x(%d)=%.12e",j,xit[j]);
1402: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1403: }
1404: for(j=1;j<=n;j++) {
1.162 brouard 1405: printf(" p(%d)=%.12e",j,p[j]);
1406: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1407: }
1408: printf("\n");
1409: fprintf(ficlog,"\n");
1410: #endif
1.162 brouard 1411: } /* end i */
1.126 brouard 1412: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1413: #ifdef DEBUG
1414: int k[2],l;
1415: k[0]=1;
1416: k[1]=-1;
1417: printf("Max: %.12e",(*func)(p));
1418: fprintf(ficlog,"Max: %.12e",(*func)(p));
1419: for (j=1;j<=n;j++) {
1420: printf(" %.12e",p[j]);
1421: fprintf(ficlog," %.12e",p[j]);
1422: }
1423: printf("\n");
1424: fprintf(ficlog,"\n");
1425: for(l=0;l<=1;l++) {
1426: for (j=1;j<=n;j++) {
1427: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1428: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1429: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1430: }
1431: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1432: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1433: }
1434: #endif
1435:
1436:
1437: free_vector(xit,1,n);
1438: free_vector(xits,1,n);
1439: free_vector(ptt,1,n);
1440: free_vector(pt,1,n);
1441: return;
1442: }
1443: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1444: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1445: ptt[j]=2.0*p[j]-pt[j];
1446: xit[j]=p[j]-pt[j];
1447: pt[j]=p[j];
1448: }
1449: fptt=(*func)(ptt);
1.161 brouard 1450: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1451: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1452: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1453: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1454: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1455: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1456: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1457: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1458: /* or best gain on one ancient line 'del' with total */
1459: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1460: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1461:
1.161 brouard 1462: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1463: t= t- del*SQR(fp-fptt);
1464: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1465: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1466: #ifdef DEBUG
1467: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1468: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1469: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1470: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1471: printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
1472: fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
1473: #endif
1474: if (t < 0.0) { /* Then we use it for last direction */
1475: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1476: for (j=1;j<=n;j++) {
1.161 brouard 1477: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1478: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1479: }
1.161 brouard 1480: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1481: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1482:
1.126 brouard 1483: #ifdef DEBUG
1.164 ! brouard 1484: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
! 1485: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1486: for(j=1;j<=n;j++){
1487: printf(" %.12e",xit[j]);
1488: fprintf(ficlog," %.12e",xit[j]);
1489: }
1490: printf("\n");
1491: fprintf(ficlog,"\n");
1492: #endif
1.162 brouard 1493: } /* end of t negative */
1494: } /* end if (fptt < fp) */
1.126 brouard 1495: }
1496: }
1497:
1498: /**** Prevalence limit (stable or period prevalence) ****************/
1499:
1500: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1501: {
1502: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1503: matrix by transitions matrix until convergence is reached */
1504:
1505: int i, ii,j,k;
1506: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1507: /* double **matprod2(); */ /* test */
1.131 brouard 1508: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1509: double **newm;
1510: double agefin, delaymax=50 ; /* Max number of years to converge */
1511:
1512: for (ii=1;ii<=nlstate+ndeath;ii++)
1513: for (j=1;j<=nlstate+ndeath;j++){
1514: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1515: }
1516:
1517: cov[1]=1.;
1518:
1519: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1520: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1521: newm=savm;
1522: /* Covariates have to be included here again */
1.138 brouard 1523: cov[2]=agefin;
1524:
1525: for (k=1; k<=cptcovn;k++) {
1526: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1527: /*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 1528: }
1.145 brouard 1529: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1530: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1531: /* 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 1532:
1533: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1534: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1535: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1536: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1537: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1538: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1539:
1.126 brouard 1540: savm=oldm;
1541: oldm=newm;
1542: maxmax=0.;
1543: for(j=1;j<=nlstate;j++){
1544: min=1.;
1545: max=0.;
1546: for(i=1; i<=nlstate; i++) {
1547: sumnew=0;
1548: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1549: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1550: /*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 1551: max=FMAX(max,prlim[i][j]);
1552: min=FMIN(min,prlim[i][j]);
1553: }
1554: maxmin=max-min;
1555: maxmax=FMAX(maxmax,maxmin);
1556: }
1557: if(maxmax < ftolpl){
1558: return prlim;
1559: }
1560: }
1561: }
1562:
1563: /*************** transition probabilities ***************/
1564:
1565: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1566: {
1.138 brouard 1567: /* According to parameters values stored in x and the covariate's values stored in cov,
1568: computes the probability to be observed in state j being in state i by appying the
1569: model to the ncovmodel covariates (including constant and age).
1570: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1571: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1572: ncth covariate in the global vector x is given by the formula:
1573: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1574: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1575: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1576: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1577: Outputs ps[i][j] the probability to be observed in j being in j according to
1578: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1579: */
1580: double s1, lnpijopii;
1.126 brouard 1581: /*double t34;*/
1.164 ! brouard 1582: int i,j, nc, ii, jj;
1.126 brouard 1583:
1584: for(i=1; i<= nlstate; i++){
1585: for(j=1; j<i;j++){
1.138 brouard 1586: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1587: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1588: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1589: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1590: }
1.138 brouard 1591: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1592: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1593: }
1594: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1595: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1596: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1597: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1598: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1599: }
1.138 brouard 1600: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1601: }
1602: }
1603:
1604: for(i=1; i<= nlstate; i++){
1605: s1=0;
1.131 brouard 1606: for(j=1; j<i; j++){
1.138 brouard 1607: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1608: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1609: }
1610: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1611: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1612: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1613: }
1.138 brouard 1614: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1615: ps[i][i]=1./(s1+1.);
1.138 brouard 1616: /* Computing other pijs */
1.126 brouard 1617: for(j=1; j<i; j++)
1618: ps[i][j]= exp(ps[i][j])*ps[i][i];
1619: for(j=i+1; j<=nlstate+ndeath; j++)
1620: ps[i][j]= exp(ps[i][j])*ps[i][i];
1621: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1622: } /* end i */
1623:
1624: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1625: for(jj=1; jj<= nlstate+ndeath; jj++){
1626: ps[ii][jj]=0;
1627: ps[ii][ii]=1;
1628: }
1629: }
1630:
1.145 brouard 1631:
1632: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1633: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1634: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1635: /* } */
1636: /* printf("\n "); */
1637: /* } */
1638: /* printf("\n ");printf("%lf ",cov[2]);*/
1639: /*
1.126 brouard 1640: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1641: goto end;*/
1642: return ps;
1643: }
1644:
1645: /**************** Product of 2 matrices ******************/
1646:
1.145 brouard 1647: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1648: {
1649: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1650: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1651: /* in, b, out are matrice of pointers which should have been initialized
1652: before: only the contents of out is modified. The function returns
1653: a pointer to pointers identical to out */
1.145 brouard 1654: int i, j, k;
1.126 brouard 1655: for(i=nrl; i<= nrh; i++)
1.145 brouard 1656: for(k=ncolol; k<=ncoloh; k++){
1657: out[i][k]=0.;
1658: for(j=ncl; j<=nch; j++)
1659: out[i][k] +=in[i][j]*b[j][k];
1660: }
1.126 brouard 1661: return out;
1662: }
1663:
1664:
1665: /************* Higher Matrix Product ***************/
1666:
1667: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1668: {
1669: /* Computes the transition matrix starting at age 'age' over
1670: 'nhstepm*hstepm*stepm' months (i.e. until
1671: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1672: nhstepm*hstepm matrices.
1673: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1674: (typically every 2 years instead of every month which is too big
1675: for the memory).
1676: Model is determined by parameters x and covariates have to be
1677: included manually here.
1678:
1679: */
1680:
1681: int i, j, d, h, k;
1.131 brouard 1682: double **out, cov[NCOVMAX+1];
1.126 brouard 1683: double **newm;
1684:
1685: /* Hstepm could be zero and should return the unit matrix */
1686: for (i=1;i<=nlstate+ndeath;i++)
1687: for (j=1;j<=nlstate+ndeath;j++){
1688: oldm[i][j]=(i==j ? 1.0 : 0.0);
1689: po[i][j][0]=(i==j ? 1.0 : 0.0);
1690: }
1691: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1692: for(h=1; h <=nhstepm; h++){
1693: for(d=1; d <=hstepm; d++){
1694: newm=savm;
1695: /* Covariates have to be included here again */
1696: cov[1]=1.;
1697: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1698: for (k=1; k<=cptcovn;k++)
1699: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1700: for (k=1; k<=cptcovage;k++)
1701: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1702: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1703: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1704:
1705:
1706: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1707: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1708: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1709: pmij(pmmij,cov,ncovmodel,x,nlstate));
1710: savm=oldm;
1711: oldm=newm;
1712: }
1713: for(i=1; i<=nlstate+ndeath; i++)
1714: for(j=1;j<=nlstate+ndeath;j++) {
1715: po[i][j][h]=newm[i][j];
1.128 brouard 1716: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1717: }
1.128 brouard 1718: /*printf("h=%d ",h);*/
1.126 brouard 1719: } /* end h */
1.128 brouard 1720: /* printf("\n H=%d \n",h); */
1.126 brouard 1721: return po;
1722: }
1723:
1.162 brouard 1724: #ifdef NLOPT
1725: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1726: double fret;
1727: double *xt;
1728: int j;
1729: myfunc_data *d2 = (myfunc_data *) pd;
1730: /* xt = (p1-1); */
1731: xt=vector(1,n);
1732: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1733:
1734: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1735: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1736: printf("Function = %.12lf ",fret);
1737: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1738: printf("\n");
1739: free_vector(xt,1,n);
1740: return fret;
1741: }
1742: #endif
1.126 brouard 1743:
1744: /*************** log-likelihood *************/
1745: double func( double *x)
1746: {
1747: int i, ii, j, k, mi, d, kk;
1.131 brouard 1748: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1749: double **out;
1750: double sw; /* Sum of weights */
1751: double lli; /* Individual log likelihood */
1752: int s1, s2;
1753: double bbh, survp;
1754: long ipmx;
1755: /*extern weight */
1756: /* We are differentiating ll according to initial status */
1757: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1758: /*for(i=1;i<imx;i++)
1759: printf(" %d\n",s[4][i]);
1760: */
1.162 brouard 1761:
1762: ++countcallfunc;
1763:
1.126 brouard 1764: cov[1]=1.;
1765:
1766: for(k=1; k<=nlstate; k++) ll[k]=0.;
1767:
1768: if(mle==1){
1769: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1770: /* Computes the values of the ncovmodel covariates of the model
1771: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1772: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1773: to be observed in j being in i according to the model.
1774: */
1.145 brouard 1775: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1776: cov[2+k]=covar[Tvar[k]][i];
1777: }
1.137 brouard 1778: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1779: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1780: has been calculated etc */
1.126 brouard 1781: for(mi=1; mi<= wav[i]-1; mi++){
1782: for (ii=1;ii<=nlstate+ndeath;ii++)
1783: for (j=1;j<=nlstate+ndeath;j++){
1784: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1785: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1786: }
1787: for(d=0; d<dh[mi][i]; d++){
1788: newm=savm;
1789: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1790: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1791: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1792: }
1793: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1794: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1795: savm=oldm;
1796: oldm=newm;
1797: } /* end mult */
1798:
1799: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1800: /* But now since version 0.9 we anticipate for bias at large stepm.
1801: * If stepm is larger than one month (smallest stepm) and if the exact delay
1802: * (in months) between two waves is not a multiple of stepm, we rounded to
1803: * the nearest (and in case of equal distance, to the lowest) interval but now
1804: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1805: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1806: * probability in order to take into account the bias as a fraction of the way
1807: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1808: * -stepm/2 to stepm/2 .
1809: * For stepm=1 the results are the same as for previous versions of Imach.
1810: * For stepm > 1 the results are less biased than in previous versions.
1811: */
1812: s1=s[mw[mi][i]][i];
1813: s2=s[mw[mi+1][i]][i];
1814: bbh=(double)bh[mi][i]/(double)stepm;
1815: /* bias bh is positive if real duration
1816: * is higher than the multiple of stepm and negative otherwise.
1817: */
1818: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1819: if( s2 > nlstate){
1820: /* i.e. if s2 is a death state and if the date of death is known
1821: then the contribution to the likelihood is the probability to
1822: die between last step unit time and current step unit time,
1823: which is also equal to probability to die before dh
1824: minus probability to die before dh-stepm .
1825: In version up to 0.92 likelihood was computed
1826: as if date of death was unknown. Death was treated as any other
1827: health state: the date of the interview describes the actual state
1828: and not the date of a change in health state. The former idea was
1829: to consider that at each interview the state was recorded
1830: (healthy, disable or death) and IMaCh was corrected; but when we
1831: introduced the exact date of death then we should have modified
1832: the contribution of an exact death to the likelihood. This new
1833: contribution is smaller and very dependent of the step unit
1834: stepm. It is no more the probability to die between last interview
1835: and month of death but the probability to survive from last
1836: interview up to one month before death multiplied by the
1837: probability to die within a month. Thanks to Chris
1838: Jackson for correcting this bug. Former versions increased
1839: mortality artificially. The bad side is that we add another loop
1840: which slows down the processing. The difference can be up to 10%
1841: lower mortality.
1842: */
1843: lli=log(out[s1][s2] - savm[s1][s2]);
1844:
1845:
1846: } else if (s2==-2) {
1847: for (j=1,survp=0. ; j<=nlstate; j++)
1848: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1849: /*survp += out[s1][j]; */
1850: lli= log(survp);
1851: }
1852:
1853: else if (s2==-4) {
1854: for (j=3,survp=0. ; j<=nlstate; j++)
1855: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1856: lli= log(survp);
1857: }
1858:
1859: else if (s2==-5) {
1860: for (j=1,survp=0. ; j<=2; j++)
1861: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1862: lli= log(survp);
1863: }
1864:
1865: else{
1866: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1867: /* 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 */
1868: }
1869: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1870: /*if(lli ==000.0)*/
1871: /*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); */
1872: ipmx +=1;
1873: sw += weight[i];
1874: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1875: } /* end of wave */
1876: } /* end of individual */
1877: } else if(mle==2){
1878: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1879: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1880: for(mi=1; mi<= wav[i]-1; mi++){
1881: for (ii=1;ii<=nlstate+ndeath;ii++)
1882: for (j=1;j<=nlstate+ndeath;j++){
1883: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1884: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1885: }
1886: for(d=0; d<=dh[mi][i]; d++){
1887: newm=savm;
1888: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1889: for (kk=1; kk<=cptcovage;kk++) {
1890: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1891: }
1892: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1893: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1894: savm=oldm;
1895: oldm=newm;
1896: } /* end mult */
1897:
1898: s1=s[mw[mi][i]][i];
1899: s2=s[mw[mi+1][i]][i];
1900: bbh=(double)bh[mi][i]/(double)stepm;
1901: 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 */
1902: ipmx +=1;
1903: sw += weight[i];
1904: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1905: } /* end of wave */
1906: } /* end of individual */
1907: } else if(mle==3){ /* exponential inter-extrapolation */
1908: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1909: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1910: for(mi=1; mi<= wav[i]-1; mi++){
1911: for (ii=1;ii<=nlstate+ndeath;ii++)
1912: for (j=1;j<=nlstate+ndeath;j++){
1913: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1914: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1915: }
1916: for(d=0; d<dh[mi][i]; d++){
1917: newm=savm;
1918: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1919: for (kk=1; kk<=cptcovage;kk++) {
1920: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1921: }
1922: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1923: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1924: savm=oldm;
1925: oldm=newm;
1926: } /* end mult */
1927:
1928: s1=s[mw[mi][i]][i];
1929: s2=s[mw[mi+1][i]][i];
1930: bbh=(double)bh[mi][i]/(double)stepm;
1931: 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 */
1932: ipmx +=1;
1933: sw += weight[i];
1934: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1935: } /* end of wave */
1936: } /* end of individual */
1937: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1938: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1939: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1940: for(mi=1; mi<= wav[i]-1; mi++){
1941: for (ii=1;ii<=nlstate+ndeath;ii++)
1942: for (j=1;j<=nlstate+ndeath;j++){
1943: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1944: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1945: }
1946: for(d=0; d<dh[mi][i]; d++){
1947: newm=savm;
1948: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1949: for (kk=1; kk<=cptcovage;kk++) {
1950: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1951: }
1952:
1953: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1954: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1955: savm=oldm;
1956: oldm=newm;
1957: } /* end mult */
1958:
1959: s1=s[mw[mi][i]][i];
1960: s2=s[mw[mi+1][i]][i];
1961: if( s2 > nlstate){
1962: lli=log(out[s1][s2] - savm[s1][s2]);
1963: }else{
1964: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1965: }
1966: ipmx +=1;
1967: sw += weight[i];
1968: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1969: /* 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]); */
1970: } /* end of wave */
1971: } /* end of individual */
1972: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1973: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1974: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1975: for(mi=1; mi<= wav[i]-1; mi++){
1976: for (ii=1;ii<=nlstate+ndeath;ii++)
1977: for (j=1;j<=nlstate+ndeath;j++){
1978: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1979: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1980: }
1981: for(d=0; d<dh[mi][i]; d++){
1982: newm=savm;
1983: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1984: for (kk=1; kk<=cptcovage;kk++) {
1985: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1986: }
1987:
1988: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1989: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1990: savm=oldm;
1991: oldm=newm;
1992: } /* end mult */
1993:
1994: s1=s[mw[mi][i]][i];
1995: s2=s[mw[mi+1][i]][i];
1996: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1997: ipmx +=1;
1998: sw += weight[i];
1999: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2000: /*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]);*/
2001: } /* end of wave */
2002: } /* end of individual */
2003: } /* End of if */
2004: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2005: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2006: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2007: return -l;
2008: }
2009:
2010: /*************** log-likelihood *************/
2011: double funcone( double *x)
2012: {
2013: /* Same as likeli but slower because of a lot of printf and if */
2014: int i, ii, j, k, mi, d, kk;
1.131 brouard 2015: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2016: double **out;
2017: double lli; /* Individual log likelihood */
2018: double llt;
2019: int s1, s2;
2020: double bbh, survp;
2021: /*extern weight */
2022: /* We are differentiating ll according to initial status */
2023: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2024: /*for(i=1;i<imx;i++)
2025: printf(" %d\n",s[4][i]);
2026: */
2027: cov[1]=1.;
2028:
2029: for(k=1; k<=nlstate; k++) ll[k]=0.;
2030:
2031: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2032: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2033: for(mi=1; mi<= wav[i]-1; mi++){
2034: for (ii=1;ii<=nlstate+ndeath;ii++)
2035: for (j=1;j<=nlstate+ndeath;j++){
2036: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2037: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2038: }
2039: for(d=0; d<dh[mi][i]; d++){
2040: newm=savm;
2041: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2042: for (kk=1; kk<=cptcovage;kk++) {
2043: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2044: }
1.145 brouard 2045: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2046: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2047: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2048: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2049: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2050: savm=oldm;
2051: oldm=newm;
2052: } /* end mult */
2053:
2054: s1=s[mw[mi][i]][i];
2055: s2=s[mw[mi+1][i]][i];
2056: bbh=(double)bh[mi][i]/(double)stepm;
2057: /* bias is positive if real duration
2058: * is higher than the multiple of stepm and negative otherwise.
2059: */
2060: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2061: lli=log(out[s1][s2] - savm[s1][s2]);
2062: } else if (s2==-2) {
2063: for (j=1,survp=0. ; j<=nlstate; j++)
2064: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2065: lli= log(survp);
2066: }else if (mle==1){
2067: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2068: } else if(mle==2){
2069: 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 */
2070: } else if(mle==3){ /* exponential inter-extrapolation */
2071: 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 */
2072: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2073: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2074: } else{ /* mle=0 back to 1 */
2075: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2076: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2077: } /* End of if */
2078: ipmx +=1;
2079: sw += weight[i];
2080: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2081: /*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 2082: if(globpr){
1.141 brouard 2083: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2084: %11.6f %11.6f %11.6f ", \
2085: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2086: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2087: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2088: llt +=ll[k]*gipmx/gsw;
2089: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2090: }
2091: fprintf(ficresilk," %10.6f\n", -llt);
2092: }
2093: } /* end of wave */
2094: } /* end of individual */
2095: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2096: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2097: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2098: if(globpr==0){ /* First time we count the contributions and weights */
2099: gipmx=ipmx;
2100: gsw=sw;
2101: }
2102: return -l;
2103: }
2104:
2105:
2106: /*************** function likelione ***********/
2107: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2108: {
2109: /* This routine should help understanding what is done with
2110: the selection of individuals/waves and
2111: to check the exact contribution to the likelihood.
2112: Plotting could be done.
2113: */
2114: int k;
2115:
2116: if(*globpri !=0){ /* Just counts and sums, no printings */
2117: strcpy(fileresilk,"ilk");
2118: strcat(fileresilk,fileres);
2119: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2120: printf("Problem with resultfile: %s\n", fileresilk);
2121: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2122: }
2123: 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");
2124: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2125: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2126: for(k=1; k<=nlstate; k++)
2127: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2128: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2129: }
2130:
2131: *fretone=(*funcone)(p);
2132: if(*globpri !=0){
2133: fclose(ficresilk);
2134: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2135: fflush(fichtm);
2136: }
2137: return;
2138: }
2139:
2140:
2141: /*********** Maximum Likelihood Estimation ***************/
2142:
2143: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2144: {
2145: int i,j, iter;
2146: double **xi;
2147: double fret;
2148: double fretone; /* Only one call to likelihood */
2149: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2150:
2151: #ifdef NLOPT
2152: int creturn;
2153: nlopt_opt opt;
2154: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2155: double *lb;
2156: double minf; /* the minimum objective value, upon return */
2157: double * p1; /* Shifted parameters from 0 instead of 1 */
2158: myfunc_data dinst, *d = &dinst;
2159: #endif
2160:
2161:
1.126 brouard 2162: xi=matrix(1,npar,1,npar);
2163: for (i=1;i<=npar;i++)
2164: for (j=1;j<=npar;j++)
2165: xi[i][j]=(i==j ? 1.0 : 0.0);
2166: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2167: strcpy(filerespow,"pow");
2168: strcat(filerespow,fileres);
2169: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2170: printf("Problem with resultfile: %s\n", filerespow);
2171: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2172: }
2173: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2174: for (i=1;i<=nlstate;i++)
2175: for(j=1;j<=nlstate+ndeath;j++)
2176: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2177: fprintf(ficrespow,"\n");
1.162 brouard 2178: #ifdef POWELL
1.126 brouard 2179: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2180: #endif
1.126 brouard 2181:
1.162 brouard 2182: #ifdef NLOPT
2183: #ifdef NEWUOA
2184: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2185: #else
2186: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2187: #endif
2188: lb=vector(0,npar-1);
2189: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2190: nlopt_set_lower_bounds(opt, lb);
2191: nlopt_set_initial_step1(opt, 0.1);
2192:
2193: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2194: d->function = func;
2195: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2196: nlopt_set_min_objective(opt, myfunc, d);
2197: nlopt_set_xtol_rel(opt, ftol);
2198: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2199: printf("nlopt failed! %d\n",creturn);
2200: }
2201: else {
2202: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2203: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2204: iter=1; /* not equal */
2205: }
2206: nlopt_destroy(opt);
2207: #endif
1.126 brouard 2208: free_matrix(xi,1,npar,1,npar);
2209: fclose(ficrespow);
1.162 brouard 2210: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2211: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2212: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2213:
2214: }
2215:
2216: /**** Computes Hessian and covariance matrix ***/
2217: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2218: {
2219: double **a,**y,*x,pd;
2220: double **hess;
1.164 ! brouard 2221: int i, j;
1.126 brouard 2222: int *indx;
2223:
2224: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2225: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2226: void lubksb(double **a, int npar, int *indx, double b[]) ;
2227: void ludcmp(double **a, int npar, int *indx, double *d) ;
2228: double gompertz(double p[]);
2229: hess=matrix(1,npar,1,npar);
2230:
2231: printf("\nCalculation of the hessian matrix. Wait...\n");
2232: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2233: for (i=1;i<=npar;i++){
2234: printf("%d",i);fflush(stdout);
2235: fprintf(ficlog,"%d",i);fflush(ficlog);
2236:
2237: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2238:
2239: /* printf(" %f ",p[i]);
2240: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2241: }
2242:
2243: for (i=1;i<=npar;i++) {
2244: for (j=1;j<=npar;j++) {
2245: if (j>i) {
2246: printf(".%d%d",i,j);fflush(stdout);
2247: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2248: hess[i][j]=hessij(p,delti,i,j,func,npar);
2249:
2250: hess[j][i]=hess[i][j];
2251: /*printf(" %lf ",hess[i][j]);*/
2252: }
2253: }
2254: }
2255: printf("\n");
2256: fprintf(ficlog,"\n");
2257:
2258: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2259: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2260:
2261: a=matrix(1,npar,1,npar);
2262: y=matrix(1,npar,1,npar);
2263: x=vector(1,npar);
2264: indx=ivector(1,npar);
2265: for (i=1;i<=npar;i++)
2266: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2267: ludcmp(a,npar,indx,&pd);
2268:
2269: for (j=1;j<=npar;j++) {
2270: for (i=1;i<=npar;i++) x[i]=0;
2271: x[j]=1;
2272: lubksb(a,npar,indx,x);
2273: for (i=1;i<=npar;i++){
2274: matcov[i][j]=x[i];
2275: }
2276: }
2277:
2278: printf("\n#Hessian matrix#\n");
2279: fprintf(ficlog,"\n#Hessian matrix#\n");
2280: for (i=1;i<=npar;i++) {
2281: for (j=1;j<=npar;j++) {
2282: printf("%.3e ",hess[i][j]);
2283: fprintf(ficlog,"%.3e ",hess[i][j]);
2284: }
2285: printf("\n");
2286: fprintf(ficlog,"\n");
2287: }
2288:
2289: /* Recompute Inverse */
2290: for (i=1;i<=npar;i++)
2291: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2292: ludcmp(a,npar,indx,&pd);
2293:
2294: /* printf("\n#Hessian matrix recomputed#\n");
2295:
2296: for (j=1;j<=npar;j++) {
2297: for (i=1;i<=npar;i++) x[i]=0;
2298: x[j]=1;
2299: lubksb(a,npar,indx,x);
2300: for (i=1;i<=npar;i++){
2301: y[i][j]=x[i];
2302: printf("%.3e ",y[i][j]);
2303: fprintf(ficlog,"%.3e ",y[i][j]);
2304: }
2305: printf("\n");
2306: fprintf(ficlog,"\n");
2307: }
2308: */
2309:
2310: free_matrix(a,1,npar,1,npar);
2311: free_matrix(y,1,npar,1,npar);
2312: free_vector(x,1,npar);
2313: free_ivector(indx,1,npar);
2314: free_matrix(hess,1,npar,1,npar);
2315:
2316:
2317: }
2318:
2319: /*************** hessian matrix ****************/
2320: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2321: {
2322: int i;
2323: int l=1, lmax=20;
2324: double k1,k2;
1.132 brouard 2325: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2326: double res;
2327: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2328: double fx;
2329: int k=0,kmax=10;
2330: double l1;
2331:
2332: fx=func(x);
2333: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2334: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2335: l1=pow(10,l);
2336: delts=delt;
2337: for(k=1 ; k <kmax; k=k+1){
2338: delt = delta*(l1*k);
2339: p2[theta]=x[theta] +delt;
1.145 brouard 2340: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2341: p2[theta]=x[theta]-delt;
2342: k2=func(p2)-fx;
2343: /*res= (k1-2.0*fx+k2)/delt/delt; */
2344: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2345:
1.132 brouard 2346: #ifdef DEBUGHESS
1.126 brouard 2347: 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);
2348: 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);
2349: #endif
2350: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2351: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2352: k=kmax;
2353: }
2354: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 ! brouard 2355: k=kmax; l=lmax*10;
1.126 brouard 2356: }
2357: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2358: delts=delt;
2359: }
2360: }
2361: }
2362: delti[theta]=delts;
2363: return res;
2364:
2365: }
2366:
2367: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2368: {
2369: int i;
1.164 ! brouard 2370: int l=1, lmax=20;
1.126 brouard 2371: double k1,k2,k3,k4,res,fx;
1.132 brouard 2372: double p2[MAXPARM+1];
1.126 brouard 2373: int k;
2374:
2375: fx=func(x);
2376: for (k=1; k<=2; k++) {
2377: for (i=1;i<=npar;i++) p2[i]=x[i];
2378: p2[thetai]=x[thetai]+delti[thetai]/k;
2379: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2380: k1=func(p2)-fx;
2381:
2382: p2[thetai]=x[thetai]+delti[thetai]/k;
2383: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2384: k2=func(p2)-fx;
2385:
2386: p2[thetai]=x[thetai]-delti[thetai]/k;
2387: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2388: k3=func(p2)-fx;
2389:
2390: p2[thetai]=x[thetai]-delti[thetai]/k;
2391: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2392: k4=func(p2)-fx;
2393: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2394: #ifdef DEBUG
2395: 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);
2396: 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);
2397: #endif
2398: }
2399: return res;
2400: }
2401:
2402: /************** Inverse of matrix **************/
2403: void ludcmp(double **a, int n, int *indx, double *d)
2404: {
2405: int i,imax,j,k;
2406: double big,dum,sum,temp;
2407: double *vv;
2408:
2409: vv=vector(1,n);
2410: *d=1.0;
2411: for (i=1;i<=n;i++) {
2412: big=0.0;
2413: for (j=1;j<=n;j++)
2414: if ((temp=fabs(a[i][j])) > big) big=temp;
2415: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2416: vv[i]=1.0/big;
2417: }
2418: for (j=1;j<=n;j++) {
2419: for (i=1;i<j;i++) {
2420: sum=a[i][j];
2421: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2422: a[i][j]=sum;
2423: }
2424: big=0.0;
2425: for (i=j;i<=n;i++) {
2426: sum=a[i][j];
2427: for (k=1;k<j;k++)
2428: sum -= a[i][k]*a[k][j];
2429: a[i][j]=sum;
2430: if ( (dum=vv[i]*fabs(sum)) >= big) {
2431: big=dum;
2432: imax=i;
2433: }
2434: }
2435: if (j != imax) {
2436: for (k=1;k<=n;k++) {
2437: dum=a[imax][k];
2438: a[imax][k]=a[j][k];
2439: a[j][k]=dum;
2440: }
2441: *d = -(*d);
2442: vv[imax]=vv[j];
2443: }
2444: indx[j]=imax;
2445: if (a[j][j] == 0.0) a[j][j]=TINY;
2446: if (j != n) {
2447: dum=1.0/(a[j][j]);
2448: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2449: }
2450: }
2451: free_vector(vv,1,n); /* Doesn't work */
2452: ;
2453: }
2454:
2455: void lubksb(double **a, int n, int *indx, double b[])
2456: {
2457: int i,ii=0,ip,j;
2458: double sum;
2459:
2460: for (i=1;i<=n;i++) {
2461: ip=indx[i];
2462: sum=b[ip];
2463: b[ip]=b[i];
2464: if (ii)
2465: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2466: else if (sum) ii=i;
2467: b[i]=sum;
2468: }
2469: for (i=n;i>=1;i--) {
2470: sum=b[i];
2471: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2472: b[i]=sum/a[i][i];
2473: }
2474: }
2475:
2476: void pstamp(FILE *fichier)
2477: {
2478: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2479: }
2480:
2481: /************ Frequencies ********************/
2482: 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[])
2483: { /* Some frequencies */
2484:
1.164 ! brouard 2485: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2486: int first;
2487: double ***freq; /* Frequencies */
2488: double *pp, **prop;
2489: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2490: char fileresp[FILENAMELENGTH];
2491:
2492: pp=vector(1,nlstate);
2493: prop=matrix(1,nlstate,iagemin,iagemax+3);
2494: strcpy(fileresp,"p");
2495: strcat(fileresp,fileres);
2496: if((ficresp=fopen(fileresp,"w"))==NULL) {
2497: printf("Problem with prevalence resultfile: %s\n", fileresp);
2498: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2499: exit(0);
2500: }
2501: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2502: j1=0;
2503:
2504: j=cptcoveff;
2505: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2506:
2507: first=1;
2508:
1.145 brouard 2509: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2510: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2511: /* j1++;
2512: */
2513: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2514: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2515: scanf("%d", i);*/
2516: for (i=-5; i<=nlstate+ndeath; i++)
2517: for (jk=-5; jk<=nlstate+ndeath; jk++)
2518: for(m=iagemin; m <= iagemax+3; m++)
2519: freq[i][jk][m]=0;
1.143 brouard 2520:
2521: for (i=1; i<=nlstate; i++)
2522: for(m=iagemin; m <= iagemax+3; m++)
2523: prop[i][m]=0;
1.126 brouard 2524:
2525: dateintsum=0;
2526: k2cpt=0;
2527: for (i=1; i<=imx; i++) {
2528: bool=1;
1.144 brouard 2529: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2530: for (z1=1; z1<=cptcoveff; z1++)
2531: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2532: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2533: bool=0;
1.145 brouard 2534: /* 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",
2535: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2536: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2537: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2538: }
1.126 brouard 2539: }
1.144 brouard 2540:
1.126 brouard 2541: if (bool==1){
2542: for(m=firstpass; m<=lastpass; m++){
2543: k2=anint[m][i]+(mint[m][i]/12.);
2544: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2545: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2546: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2547: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2548: if (m<lastpass) {
2549: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2550: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2551: }
2552:
2553: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2554: dateintsum=dateintsum+k2;
2555: k2cpt++;
2556: }
2557: /*}*/
2558: }
2559: }
1.145 brouard 2560: } /* end i */
1.126 brouard 2561:
2562: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2563: pstamp(ficresp);
2564: if (cptcovn>0) {
2565: fprintf(ficresp, "\n#********** Variable ");
2566: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2567: fprintf(ficresp, "**********\n#");
1.143 brouard 2568: fprintf(ficlog, "\n#********** Variable ");
2569: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2570: fprintf(ficlog, "**********\n#");
1.126 brouard 2571: }
2572: for(i=1; i<=nlstate;i++)
2573: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2574: fprintf(ficresp, "\n");
2575:
2576: for(i=iagemin; i <= iagemax+3; i++){
2577: if(i==iagemax+3){
2578: fprintf(ficlog,"Total");
2579: }else{
2580: if(first==1){
2581: first=0;
2582: printf("See log file for details...\n");
2583: }
2584: fprintf(ficlog,"Age %d", i);
2585: }
2586: for(jk=1; jk <=nlstate ; jk++){
2587: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2588: pp[jk] += freq[jk][m][i];
2589: }
2590: for(jk=1; jk <=nlstate ; jk++){
2591: for(m=-1, pos=0; m <=0 ; m++)
2592: pos += freq[jk][m][i];
2593: if(pp[jk]>=1.e-10){
2594: if(first==1){
1.132 brouard 2595: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2596: }
2597: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2598: }else{
2599: if(first==1)
2600: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2601: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2602: }
2603: }
2604:
2605: for(jk=1; jk <=nlstate ; jk++){
2606: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2607: pp[jk] += freq[jk][m][i];
2608: }
2609: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2610: pos += pp[jk];
2611: posprop += prop[jk][i];
2612: }
2613: for(jk=1; jk <=nlstate ; jk++){
2614: if(pos>=1.e-5){
2615: if(first==1)
2616: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2617: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2618: }else{
2619: if(first==1)
2620: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2621: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2622: }
2623: if( i <= iagemax){
2624: if(pos>=1.e-5){
2625: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2626: /*probs[i][jk][j1]= pp[jk]/pos;*/
2627: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2628: }
2629: else
2630: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2631: }
2632: }
2633:
2634: for(jk=-1; jk <=nlstate+ndeath; jk++)
2635: for(m=-1; m <=nlstate+ndeath; m++)
2636: if(freq[jk][m][i] !=0 ) {
2637: if(first==1)
2638: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2639: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2640: }
2641: if(i <= iagemax)
2642: fprintf(ficresp,"\n");
2643: if(first==1)
2644: printf("Others in log...\n");
2645: fprintf(ficlog,"\n");
2646: }
1.145 brouard 2647: /*}*/
1.126 brouard 2648: }
2649: dateintmean=dateintsum/k2cpt;
2650:
2651: fclose(ficresp);
2652: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2653: free_vector(pp,1,nlstate);
2654: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2655: /* End of Freq */
2656: }
2657:
2658: /************ Prevalence ********************/
2659: 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)
2660: {
2661: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2662: in each health status at the date of interview (if between dateprev1 and dateprev2).
2663: We still use firstpass and lastpass as another selection.
2664: */
2665:
1.164 ! brouard 2666: int i, m, jk, j1, bool, z1,j;
! 2667:
! 2668: double **prop;
! 2669: double posprop;
1.126 brouard 2670: double y2; /* in fractional years */
2671: int iagemin, iagemax;
1.145 brouard 2672: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2673:
2674: iagemin= (int) agemin;
2675: iagemax= (int) agemax;
2676: /*pp=vector(1,nlstate);*/
2677: prop=matrix(1,nlstate,iagemin,iagemax+3);
2678: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2679: j1=0;
2680:
1.145 brouard 2681: /*j=cptcoveff;*/
1.126 brouard 2682: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2683:
1.145 brouard 2684: first=1;
2685: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2686: /*for(i1=1; i1<=ncodemax[k1];i1++){
2687: j1++;*/
1.126 brouard 2688:
2689: for (i=1; i<=nlstate; i++)
2690: for(m=iagemin; m <= iagemax+3; m++)
2691: prop[i][m]=0.0;
2692:
2693: for (i=1; i<=imx; i++) { /* Each individual */
2694: bool=1;
2695: if (cptcovn>0) {
2696: for (z1=1; z1<=cptcoveff; z1++)
2697: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2698: bool=0;
2699: }
2700: if (bool==1) {
2701: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2702: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2703: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2704: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2705: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2706: 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);
2707: if (s[m][i]>0 && s[m][i]<=nlstate) {
2708: /*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]]);*/
2709: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2710: prop[s[m][i]][iagemax+3] += weight[i];
2711: }
2712: }
2713: } /* end selection of waves */
2714: }
2715: }
2716: for(i=iagemin; i <= iagemax+3; i++){
2717: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2718: posprop += prop[jk][i];
2719: }
1.145 brouard 2720:
1.126 brouard 2721: for(jk=1; jk <=nlstate ; jk++){
2722: if( i <= iagemax){
2723: if(posprop>=1.e-5){
2724: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2725: } else{
2726: if(first==1){
2727: first=0;
2728: 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]);
2729: }
2730: }
1.126 brouard 2731: }
2732: }/* end jk */
2733: }/* end i */
1.145 brouard 2734: /*} *//* end i1 */
2735: } /* end j1 */
1.126 brouard 2736:
2737: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2738: /*free_vector(pp,1,nlstate);*/
2739: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2740: } /* End of prevalence */
2741:
2742: /************* Waves Concatenation ***************/
2743:
2744: 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)
2745: {
2746: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2747: Death is a valid wave (if date is known).
2748: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2749: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2750: and mw[mi+1][i]. dh depends on stepm.
2751: */
2752:
2753: int i, mi, m;
2754: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2755: double sum=0., jmean=0.;*/
2756: int first;
2757: int j, k=0,jk, ju, jl;
2758: double sum=0.;
2759: first=0;
1.164 ! brouard 2760: jmin=100000;
1.126 brouard 2761: jmax=-1;
2762: jmean=0.;
2763: for(i=1; i<=imx; i++){
2764: mi=0;
2765: m=firstpass;
2766: while(s[m][i] <= nlstate){
2767: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2768: mw[++mi][i]=m;
2769: if(m >=lastpass)
2770: break;
2771: else
2772: m++;
2773: }/* end while */
2774: if (s[m][i] > nlstate){
2775: mi++; /* Death is another wave */
2776: /* if(mi==0) never been interviewed correctly before death */
2777: /* Only death is a correct wave */
2778: mw[mi][i]=m;
2779: }
2780:
2781: wav[i]=mi;
2782: if(mi==0){
2783: nbwarn++;
2784: if(first==0){
2785: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2786: first=1;
2787: }
2788: if(first==1){
2789: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2790: }
2791: } /* end mi==0 */
2792: } /* End individuals */
2793:
2794: for(i=1; i<=imx; i++){
2795: for(mi=1; mi<wav[i];mi++){
2796: if (stepm <=0)
2797: dh[mi][i]=1;
2798: else{
2799: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2800: if (agedc[i] < 2*AGESUP) {
2801: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2802: if(j==0) j=1; /* Survives at least one month after exam */
2803: else if(j<0){
2804: nberr++;
2805: 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]);
2806: j=1; /* Temporary Dangerous patch */
2807: 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);
2808: 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]);
2809: 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);
2810: }
2811: k=k+1;
2812: if (j >= jmax){
2813: jmax=j;
2814: ijmax=i;
2815: }
2816: if (j <= jmin){
2817: jmin=j;
2818: ijmin=i;
2819: }
2820: sum=sum+j;
2821: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2822: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2823: }
2824: }
2825: else{
2826: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2827: /* 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]); */
2828:
2829: k=k+1;
2830: if (j >= jmax) {
2831: jmax=j;
2832: ijmax=i;
2833: }
2834: else if (j <= jmin){
2835: jmin=j;
2836: ijmin=i;
2837: }
2838: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2839: /*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]);*/
2840: if(j<0){
2841: nberr++;
2842: 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]);
2843: 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]);
2844: }
2845: sum=sum+j;
2846: }
2847: jk= j/stepm;
2848: jl= j -jk*stepm;
2849: ju= j -(jk+1)*stepm;
2850: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2851: if(jl==0){
2852: dh[mi][i]=jk;
2853: bh[mi][i]=0;
2854: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2855: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2856: dh[mi][i]=jk+1;
2857: bh[mi][i]=ju;
2858: }
2859: }else{
2860: if(jl <= -ju){
2861: dh[mi][i]=jk;
2862: bh[mi][i]=jl; /* bias is positive if real duration
2863: * is higher than the multiple of stepm and negative otherwise.
2864: */
2865: }
2866: else{
2867: dh[mi][i]=jk+1;
2868: bh[mi][i]=ju;
2869: }
2870: if(dh[mi][i]==0){
2871: dh[mi][i]=1; /* At least one step */
2872: bh[mi][i]=ju; /* At least one step */
2873: /* 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);*/
2874: }
2875: } /* end if mle */
2876: }
2877: } /* end wave */
2878: }
2879: jmean=sum/k;
2880: 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 2881: 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 2882: }
2883:
2884: /*********** Tricode ****************************/
1.145 brouard 2885: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2886: {
1.144 brouard 2887: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2888: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2889: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2890: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2891: /* nbcode[Tvar[j]][1]=
1.144 brouard 2892: */
1.130 brouard 2893:
1.145 brouard 2894: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2895: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2896: int cptcode=0; /* Modality max of covariates j */
2897: int modmincovj=0; /* Modality min of covariates j */
2898:
2899:
1.126 brouard 2900: cptcoveff=0;
2901:
1.145 brouard 2902: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2903: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2904:
1.145 brouard 2905: /* Loop on covariates without age and products */
2906: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2907: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2908: modality of this covariate Vj*/
1.145 brouard 2909: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2910: * If product of Vn*Vm, still boolean *:
2911: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2912: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2913: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2914: modality of the nth covariate of individual i. */
1.145 brouard 2915: if (ij > modmaxcovj)
2916: modmaxcovj=ij;
2917: else if (ij < modmincovj)
2918: modmincovj=ij;
2919: if ((ij < -1) && (ij > NCOVMAX)){
2920: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2921: exit(1);
2922: }else
1.136 brouard 2923: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2924: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2925: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2926: /* getting the maximum value of the modality of the covariate
2927: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2928: female is 1, then modmaxcovj=1.*/
1.126 brouard 2929: }
1.145 brouard 2930: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2931: cptcode=modmaxcovj;
1.137 brouard 2932: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2933: /*for (i=0; i<=cptcode; i++) {*/
2934: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2935: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2936: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2937: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2938: }
2939: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2940: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2941: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2942:
1.136 brouard 2943: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2944: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2945: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2946: modmincovj=3; modmaxcovj = 7;
2947: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2948: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2949: variables V1_1 and V1_2.
2950: nbcode[Tvar[j]][ij]=k;
2951: nbcode[Tvar[j]][1]=0;
2952: nbcode[Tvar[j]][2]=1;
2953: nbcode[Tvar[j]][3]=2;
2954: */
2955: ij=1; /* ij is similar to i but can jumps over null modalities */
2956: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2957: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2958: /*recode from 0 */
1.131 brouard 2959: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2960: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2961: k is a modality. If we have model=V1+V1*sex
2962: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2963: ij++;
2964: }
2965: if (ij > ncodemax[j]) break;
1.137 brouard 2966: } /* end of loop on */
2967: } /* end of loop on modality */
2968: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2969:
1.145 brouard 2970: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2971:
1.145 brouard 2972: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2973: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2974: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2975: Ndum[ij]++;
2976: }
1.126 brouard 2977:
2978: ij=1;
1.145 brouard 2979: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2980: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2981: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2982: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2983: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2984: ij++;
1.145 brouard 2985: }else
2986: Tvaraff[ij]=0;
1.126 brouard 2987: }
1.131 brouard 2988: ij--;
1.144 brouard 2989: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2990:
1.126 brouard 2991: }
2992:
1.145 brouard 2993:
1.126 brouard 2994: /*********** Health Expectancies ****************/
2995:
1.127 brouard 2996: 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 2997:
2998: {
2999: /* Health expectancies, no variances */
1.164 ! brouard 3000: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3001: int nhstepma, nstepma; /* Decreasing with age */
3002: double age, agelim, hf;
3003: double ***p3mat;
3004: double eip;
3005:
3006: pstamp(ficreseij);
3007: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3008: fprintf(ficreseij,"# Age");
3009: for(i=1; i<=nlstate;i++){
3010: for(j=1; j<=nlstate;j++){
3011: fprintf(ficreseij," e%1d%1d ",i,j);
3012: }
3013: fprintf(ficreseij," e%1d. ",i);
3014: }
3015: fprintf(ficreseij,"\n");
3016:
3017:
3018: if(estepm < stepm){
3019: printf ("Problem %d lower than %d\n",estepm, stepm);
3020: }
3021: else hstepm=estepm;
3022: /* We compute the life expectancy from trapezoids spaced every estepm months
3023: * This is mainly to measure the difference between two models: for example
3024: * if stepm=24 months pijx are given only every 2 years and by summing them
3025: * we are calculating an estimate of the Life Expectancy assuming a linear
3026: * progression in between and thus overestimating or underestimating according
3027: * to the curvature of the survival function. If, for the same date, we
3028: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3029: * to compare the new estimate of Life expectancy with the same linear
3030: * hypothesis. A more precise result, taking into account a more precise
3031: * curvature will be obtained if estepm is as small as stepm. */
3032:
3033: /* For example we decided to compute the life expectancy with the smallest unit */
3034: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3035: nhstepm is the number of hstepm from age to agelim
3036: nstepm is the number of stepm from age to agelin.
3037: Look at hpijx to understand the reason of that which relies in memory size
3038: and note for a fixed period like estepm months */
3039: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3040: survival function given by stepm (the optimization length). Unfortunately it
3041: means that if the survival funtion is printed only each two years of age and if
3042: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3043: results. So we changed our mind and took the option of the best precision.
3044: */
3045: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3046:
3047: agelim=AGESUP;
3048: /* If stepm=6 months */
3049: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3050: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3051:
3052: /* nhstepm age range expressed in number of stepm */
3053: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3054: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3055: /* if (stepm >= YEARM) hstepm=1;*/
3056: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3057: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3058:
3059: for (age=bage; age<=fage; age ++){
3060: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3061: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3062: /* if (stepm >= YEARM) hstepm=1;*/
3063: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3064:
3065: /* If stepm=6 months */
3066: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3067: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3068:
3069: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3070:
3071: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3072:
3073: printf("%d|",(int)age);fflush(stdout);
3074: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3075:
3076: /* Computing expectancies */
3077: for(i=1; i<=nlstate;i++)
3078: for(j=1; j<=nlstate;j++)
3079: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3080: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3081:
3082: /* 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]);*/
3083:
3084: }
3085:
3086: fprintf(ficreseij,"%3.0f",age );
3087: for(i=1; i<=nlstate;i++){
3088: eip=0;
3089: for(j=1; j<=nlstate;j++){
3090: eip +=eij[i][j][(int)age];
3091: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3092: }
3093: fprintf(ficreseij,"%9.4f", eip );
3094: }
3095: fprintf(ficreseij,"\n");
3096:
3097: }
3098: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3099: printf("\n");
3100: fprintf(ficlog,"\n");
3101:
3102: }
3103:
1.127 brouard 3104: 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 3105:
3106: {
3107: /* Covariances of health expectancies eij and of total life expectancies according
3108: to initial status i, ei. .
3109: */
3110: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3111: int nhstepma, nstepma; /* Decreasing with age */
3112: double age, agelim, hf;
3113: double ***p3matp, ***p3matm, ***varhe;
3114: double **dnewm,**doldm;
3115: double *xp, *xm;
3116: double **gp, **gm;
3117: double ***gradg, ***trgradg;
3118: int theta;
3119:
3120: double eip, vip;
3121:
3122: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3123: xp=vector(1,npar);
3124: xm=vector(1,npar);
3125: dnewm=matrix(1,nlstate*nlstate,1,npar);
3126: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3127:
3128: pstamp(ficresstdeij);
3129: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3130: fprintf(ficresstdeij,"# Age");
3131: for(i=1; i<=nlstate;i++){
3132: for(j=1; j<=nlstate;j++)
3133: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3134: fprintf(ficresstdeij," e%1d. ",i);
3135: }
3136: fprintf(ficresstdeij,"\n");
3137:
3138: pstamp(ficrescveij);
3139: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3140: fprintf(ficrescveij,"# Age");
3141: for(i=1; i<=nlstate;i++)
3142: for(j=1; j<=nlstate;j++){
3143: cptj= (j-1)*nlstate+i;
3144: for(i2=1; i2<=nlstate;i2++)
3145: for(j2=1; j2<=nlstate;j2++){
3146: cptj2= (j2-1)*nlstate+i2;
3147: if(cptj2 <= cptj)
3148: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3149: }
3150: }
3151: fprintf(ficrescveij,"\n");
3152:
3153: if(estepm < stepm){
3154: printf ("Problem %d lower than %d\n",estepm, stepm);
3155: }
3156: else hstepm=estepm;
3157: /* We compute the life expectancy from trapezoids spaced every estepm months
3158: * This is mainly to measure the difference between two models: for example
3159: * if stepm=24 months pijx are given only every 2 years and by summing them
3160: * we are calculating an estimate of the Life Expectancy assuming a linear
3161: * progression in between and thus overestimating or underestimating according
3162: * to the curvature of the survival function. If, for the same date, we
3163: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3164: * to compare the new estimate of Life expectancy with the same linear
3165: * hypothesis. A more precise result, taking into account a more precise
3166: * curvature will be obtained if estepm is as small as stepm. */
3167:
3168: /* For example we decided to compute the life expectancy with the smallest unit */
3169: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3170: nhstepm is the number of hstepm from age to agelim
3171: nstepm is the number of stepm from age to agelin.
3172: Look at hpijx to understand the reason of that which relies in memory size
3173: and note for a fixed period like estepm months */
3174: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3175: survival function given by stepm (the optimization length). Unfortunately it
3176: means that if the survival funtion is printed only each two years of age and if
3177: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3178: results. So we changed our mind and took the option of the best precision.
3179: */
3180: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3181:
3182: /* If stepm=6 months */
3183: /* nhstepm age range expressed in number of stepm */
3184: agelim=AGESUP;
3185: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3186: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3187: /* if (stepm >= YEARM) hstepm=1;*/
3188: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3189:
3190: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3191: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3192: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3193: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3194: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3195: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3196:
3197: for (age=bage; age<=fage; age ++){
3198: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3199: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3200: /* if (stepm >= YEARM) hstepm=1;*/
3201: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3202:
3203: /* If stepm=6 months */
3204: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3205: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3206:
3207: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3208:
3209: /* Computing Variances of health expectancies */
3210: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3211: decrease memory allocation */
3212: for(theta=1; theta <=npar; theta++){
3213: for(i=1; i<=npar; i++){
3214: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3215: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3216: }
3217: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3218: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3219:
3220: for(j=1; j<= nlstate; j++){
3221: for(i=1; i<=nlstate; i++){
3222: for(h=0; h<=nhstepm-1; h++){
3223: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3224: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3225: }
3226: }
3227: }
3228:
3229: for(ij=1; ij<= nlstate*nlstate; ij++)
3230: for(h=0; h<=nhstepm-1; h++){
3231: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3232: }
3233: }/* End theta */
3234:
3235:
3236: for(h=0; h<=nhstepm-1; h++)
3237: for(j=1; j<=nlstate*nlstate;j++)
3238: for(theta=1; theta <=npar; theta++)
3239: trgradg[h][j][theta]=gradg[h][theta][j];
3240:
3241:
3242: for(ij=1;ij<=nlstate*nlstate;ij++)
3243: for(ji=1;ji<=nlstate*nlstate;ji++)
3244: varhe[ij][ji][(int)age] =0.;
3245:
3246: printf("%d|",(int)age);fflush(stdout);
3247: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3248: for(h=0;h<=nhstepm-1;h++){
3249: for(k=0;k<=nhstepm-1;k++){
3250: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3251: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3252: for(ij=1;ij<=nlstate*nlstate;ij++)
3253: for(ji=1;ji<=nlstate*nlstate;ji++)
3254: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3255: }
3256: }
3257:
3258: /* Computing expectancies */
3259: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3260: for(i=1; i<=nlstate;i++)
3261: for(j=1; j<=nlstate;j++)
3262: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3263: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3264:
3265: /* 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]);*/
3266:
3267: }
3268:
3269: fprintf(ficresstdeij,"%3.0f",age );
3270: for(i=1; i<=nlstate;i++){
3271: eip=0.;
3272: vip=0.;
3273: for(j=1; j<=nlstate;j++){
3274: eip += eij[i][j][(int)age];
3275: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3276: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3277: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3278: }
3279: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3280: }
3281: fprintf(ficresstdeij,"\n");
3282:
3283: fprintf(ficrescveij,"%3.0f",age );
3284: for(i=1; i<=nlstate;i++)
3285: for(j=1; j<=nlstate;j++){
3286: cptj= (j-1)*nlstate+i;
3287: for(i2=1; i2<=nlstate;i2++)
3288: for(j2=1; j2<=nlstate;j2++){
3289: cptj2= (j2-1)*nlstate+i2;
3290: if(cptj2 <= cptj)
3291: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3292: }
3293: }
3294: fprintf(ficrescveij,"\n");
3295:
3296: }
3297: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3298: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3299: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3300: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3301: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3302: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3303: printf("\n");
3304: fprintf(ficlog,"\n");
3305:
3306: free_vector(xm,1,npar);
3307: free_vector(xp,1,npar);
3308: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3309: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3310: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3311: }
3312:
3313: /************ Variance ******************/
3314: 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[])
3315: {
3316: /* Variance of health expectancies */
3317: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3318: /* double **newm;*/
3319: double **dnewm,**doldm;
3320: double **dnewmp,**doldmp;
3321: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 ! brouard 3322: int k;
1.126 brouard 3323: double *xp;
3324: double **gp, **gm; /* for var eij */
3325: double ***gradg, ***trgradg; /*for var eij */
3326: double **gradgp, **trgradgp; /* for var p point j */
3327: double *gpp, *gmp; /* for var p point j */
3328: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3329: double ***p3mat;
3330: double age,agelim, hf;
3331: double ***mobaverage;
3332: int theta;
3333: char digit[4];
3334: char digitp[25];
3335:
3336: char fileresprobmorprev[FILENAMELENGTH];
3337:
3338: if(popbased==1){
3339: if(mobilav!=0)
3340: strcpy(digitp,"-populbased-mobilav-");
3341: else strcpy(digitp,"-populbased-nomobil-");
3342: }
3343: else
3344: strcpy(digitp,"-stablbased-");
3345:
3346: if (mobilav!=0) {
3347: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3348: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3349: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3350: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3351: }
3352: }
3353:
3354: strcpy(fileresprobmorprev,"prmorprev");
3355: sprintf(digit,"%-d",ij);
3356: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3357: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3358: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3359: strcat(fileresprobmorprev,fileres);
3360: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3361: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3362: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3363: }
3364: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3365:
3366: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3367: pstamp(ficresprobmorprev);
3368: 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);
3369: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3370: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3371: fprintf(ficresprobmorprev," p.%-d SE",j);
3372: for(i=1; i<=nlstate;i++)
3373: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3374: }
3375: fprintf(ficresprobmorprev,"\n");
3376: fprintf(ficgp,"\n# Routine varevsij");
3377: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3378: 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");
3379: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3380: /* } */
3381: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3382: pstamp(ficresvij);
3383: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3384: if(popbased==1)
1.128 brouard 3385: 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 3386: else
3387: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3388: fprintf(ficresvij,"# Age");
3389: for(i=1; i<=nlstate;i++)
3390: for(j=1; j<=nlstate;j++)
3391: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3392: fprintf(ficresvij,"\n");
3393:
3394: xp=vector(1,npar);
3395: dnewm=matrix(1,nlstate,1,npar);
3396: doldm=matrix(1,nlstate,1,nlstate);
3397: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3398: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3399:
3400: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3401: gpp=vector(nlstate+1,nlstate+ndeath);
3402: gmp=vector(nlstate+1,nlstate+ndeath);
3403: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3404:
3405: if(estepm < stepm){
3406: printf ("Problem %d lower than %d\n",estepm, stepm);
3407: }
3408: else hstepm=estepm;
3409: /* For example we decided to compute the life expectancy with the smallest unit */
3410: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3411: nhstepm is the number of hstepm from age to agelim
3412: nstepm is the number of stepm from age to agelin.
1.128 brouard 3413: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3414: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3415: survival function given by stepm (the optimization length). Unfortunately it
3416: means that if the survival funtion is printed every two years of age and if
3417: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3418: results. So we changed our mind and took the option of the best precision.
3419: */
3420: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3421: agelim = AGESUP;
3422: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3423: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3424: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3425: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3426: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3427: gp=matrix(0,nhstepm,1,nlstate);
3428: gm=matrix(0,nhstepm,1,nlstate);
3429:
3430:
3431: for(theta=1; theta <=npar; theta++){
3432: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3433: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3434: }
3435: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3436: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3437:
3438: if (popbased==1) {
3439: if(mobilav ==0){
3440: for(i=1; i<=nlstate;i++)
3441: prlim[i][i]=probs[(int)age][i][ij];
3442: }else{ /* mobilav */
3443: for(i=1; i<=nlstate;i++)
3444: prlim[i][i]=mobaverage[(int)age][i][ij];
3445: }
3446: }
3447:
3448: for(j=1; j<= nlstate; j++){
3449: for(h=0; h<=nhstepm; h++){
3450: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3451: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3452: }
3453: }
3454: /* This for computing probability of death (h=1 means
3455: computed over hstepm matrices product = hstepm*stepm months)
3456: as a weighted average of prlim.
3457: */
3458: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3459: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3460: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3461: }
3462: /* end probability of death */
3463:
3464: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3465: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3466: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3467: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3468:
3469: if (popbased==1) {
3470: if(mobilav ==0){
3471: for(i=1; i<=nlstate;i++)
3472: prlim[i][i]=probs[(int)age][i][ij];
3473: }else{ /* mobilav */
3474: for(i=1; i<=nlstate;i++)
3475: prlim[i][i]=mobaverage[(int)age][i][ij];
3476: }
3477: }
3478:
1.128 brouard 3479: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3480: for(h=0; h<=nhstepm; h++){
3481: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3482: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3483: }
3484: }
3485: /* This for computing probability of death (h=1 means
3486: computed over hstepm matrices product = hstepm*stepm months)
3487: as a weighted average of prlim.
3488: */
3489: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3490: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3491: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3492: }
3493: /* end probability of death */
3494:
3495: for(j=1; j<= nlstate; j++) /* vareij */
3496: for(h=0; h<=nhstepm; h++){
3497: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3498: }
3499:
3500: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3501: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3502: }
3503:
3504: } /* End theta */
3505:
3506: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3507:
3508: for(h=0; h<=nhstepm; h++) /* veij */
3509: for(j=1; j<=nlstate;j++)
3510: for(theta=1; theta <=npar; theta++)
3511: trgradg[h][j][theta]=gradg[h][theta][j];
3512:
3513: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3514: for(theta=1; theta <=npar; theta++)
3515: trgradgp[j][theta]=gradgp[theta][j];
3516:
3517:
3518: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3519: for(i=1;i<=nlstate;i++)
3520: for(j=1;j<=nlstate;j++)
3521: vareij[i][j][(int)age] =0.;
3522:
3523: for(h=0;h<=nhstepm;h++){
3524: for(k=0;k<=nhstepm;k++){
3525: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3526: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3527: for(i=1;i<=nlstate;i++)
3528: for(j=1;j<=nlstate;j++)
3529: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3530: }
3531: }
3532:
3533: /* pptj */
3534: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3535: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3536: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3537: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3538: varppt[j][i]=doldmp[j][i];
3539: /* end ppptj */
3540: /* x centered again */
3541: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3542: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3543:
3544: if (popbased==1) {
3545: if(mobilav ==0){
3546: for(i=1; i<=nlstate;i++)
3547: prlim[i][i]=probs[(int)age][i][ij];
3548: }else{ /* mobilav */
3549: for(i=1; i<=nlstate;i++)
3550: prlim[i][i]=mobaverage[(int)age][i][ij];
3551: }
3552: }
3553:
3554: /* This for computing probability of death (h=1 means
3555: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3556: as a weighted average of prlim.
3557: */
3558: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3559: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3560: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3561: }
3562: /* end probability of death */
3563:
3564: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3565: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3566: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3567: for(i=1; i<=nlstate;i++){
3568: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3569: }
3570: }
3571: fprintf(ficresprobmorprev,"\n");
3572:
3573: fprintf(ficresvij,"%.0f ",age );
3574: for(i=1; i<=nlstate;i++)
3575: for(j=1; j<=nlstate;j++){
3576: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3577: }
3578: fprintf(ficresvij,"\n");
3579: free_matrix(gp,0,nhstepm,1,nlstate);
3580: free_matrix(gm,0,nhstepm,1,nlstate);
3581: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3582: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3583: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3584: } /* End age */
3585: free_vector(gpp,nlstate+1,nlstate+ndeath);
3586: free_vector(gmp,nlstate+1,nlstate+ndeath);
3587: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3588: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3589: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3590: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3591: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3592: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3593: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3594: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3595: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3596: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3597: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3598: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3599: 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);
3600: /* 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);
3601: */
3602: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3603: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3604:
3605: free_vector(xp,1,npar);
3606: free_matrix(doldm,1,nlstate,1,nlstate);
3607: free_matrix(dnewm,1,nlstate,1,npar);
3608: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3609: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3610: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3611: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3612: fclose(ficresprobmorprev);
3613: fflush(ficgp);
3614: fflush(fichtm);
3615: } /* end varevsij */
3616:
3617: /************ Variance of prevlim ******************/
3618: 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[])
3619: {
3620: /* Variance of prevalence limit */
3621: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 ! brouard 3622:
1.126 brouard 3623: double **dnewm,**doldm;
3624: int i, j, nhstepm, hstepm;
3625: double *xp;
3626: double *gp, *gm;
3627: double **gradg, **trgradg;
3628: double age,agelim;
3629: int theta;
3630:
3631: pstamp(ficresvpl);
3632: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3633: fprintf(ficresvpl,"# Age");
3634: for(i=1; i<=nlstate;i++)
3635: fprintf(ficresvpl," %1d-%1d",i,i);
3636: fprintf(ficresvpl,"\n");
3637:
3638: xp=vector(1,npar);
3639: dnewm=matrix(1,nlstate,1,npar);
3640: doldm=matrix(1,nlstate,1,nlstate);
3641:
3642: hstepm=1*YEARM; /* Every year of age */
3643: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3644: agelim = AGESUP;
3645: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3646: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3647: if (stepm >= YEARM) hstepm=1;
3648: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3649: gradg=matrix(1,npar,1,nlstate);
3650: gp=vector(1,nlstate);
3651: gm=vector(1,nlstate);
3652:
3653: for(theta=1; theta <=npar; theta++){
3654: for(i=1; i<=npar; i++){ /* Computes gradient */
3655: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3656: }
3657: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3658: for(i=1;i<=nlstate;i++)
3659: gp[i] = prlim[i][i];
3660:
3661: for(i=1; i<=npar; i++) /* Computes gradient */
3662: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3663: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3664: for(i=1;i<=nlstate;i++)
3665: gm[i] = prlim[i][i];
3666:
3667: for(i=1;i<=nlstate;i++)
3668: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3669: } /* End theta */
3670:
3671: trgradg =matrix(1,nlstate,1,npar);
3672:
3673: for(j=1; j<=nlstate;j++)
3674: for(theta=1; theta <=npar; theta++)
3675: trgradg[j][theta]=gradg[theta][j];
3676:
3677: for(i=1;i<=nlstate;i++)
3678: varpl[i][(int)age] =0.;
3679: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3680: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3681: for(i=1;i<=nlstate;i++)
3682: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3683:
3684: fprintf(ficresvpl,"%.0f ",age );
3685: for(i=1; i<=nlstate;i++)
3686: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3687: fprintf(ficresvpl,"\n");
3688: free_vector(gp,1,nlstate);
3689: free_vector(gm,1,nlstate);
3690: free_matrix(gradg,1,npar,1,nlstate);
3691: free_matrix(trgradg,1,nlstate,1,npar);
3692: } /* End age */
3693:
3694: free_vector(xp,1,npar);
3695: free_matrix(doldm,1,nlstate,1,npar);
3696: free_matrix(dnewm,1,nlstate,1,nlstate);
3697:
3698: }
3699:
3700: /************ Variance of one-step probabilities ******************/
3701: 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[])
3702: {
1.164 ! brouard 3703: int i, j=0, k1, l1, tj;
1.126 brouard 3704: int k2, l2, j1, z1;
1.164 ! brouard 3705: int k=0, l;
1.145 brouard 3706: int first=1, first1, first2;
1.126 brouard 3707: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3708: double **dnewm,**doldm;
3709: double *xp;
3710: double *gp, *gm;
3711: double **gradg, **trgradg;
3712: double **mu;
1.164 ! brouard 3713: double age, cov[NCOVMAX+1];
1.126 brouard 3714: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3715: int theta;
3716: char fileresprob[FILENAMELENGTH];
3717: char fileresprobcov[FILENAMELENGTH];
3718: char fileresprobcor[FILENAMELENGTH];
3719: double ***varpij;
3720:
3721: strcpy(fileresprob,"prob");
3722: strcat(fileresprob,fileres);
3723: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3724: printf("Problem with resultfile: %s\n", fileresprob);
3725: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3726: }
3727: strcpy(fileresprobcov,"probcov");
3728: strcat(fileresprobcov,fileres);
3729: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3730: printf("Problem with resultfile: %s\n", fileresprobcov);
3731: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3732: }
3733: strcpy(fileresprobcor,"probcor");
3734: strcat(fileresprobcor,fileres);
3735: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3736: printf("Problem with resultfile: %s\n", fileresprobcor);
3737: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3738: }
3739: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3740: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3741: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3742: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3743: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3744: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3745: pstamp(ficresprob);
3746: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3747: fprintf(ficresprob,"# Age");
3748: pstamp(ficresprobcov);
3749: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3750: fprintf(ficresprobcov,"# Age");
3751: pstamp(ficresprobcor);
3752: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3753: fprintf(ficresprobcor,"# Age");
3754:
3755:
3756: for(i=1; i<=nlstate;i++)
3757: for(j=1; j<=(nlstate+ndeath);j++){
3758: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3759: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3760: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3761: }
3762: /* fprintf(ficresprob,"\n");
3763: fprintf(ficresprobcov,"\n");
3764: fprintf(ficresprobcor,"\n");
3765: */
1.131 brouard 3766: xp=vector(1,npar);
1.126 brouard 3767: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3768: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3769: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3770: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3771: first=1;
3772: fprintf(ficgp,"\n# Routine varprob");
3773: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3774: fprintf(fichtm,"\n");
3775:
3776: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3777: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3778: file %s<br>\n",optionfilehtmcov);
3779: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3780: and drawn. It helps understanding how is the covariance between two incidences.\
3781: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3782: 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. \
3783: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3784: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3785: standard deviations wide on each axis. <br>\
3786: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3787: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3788: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3789:
3790: cov[1]=1;
1.145 brouard 3791: /* tj=cptcoveff; */
3792: tj = (int) pow(2,cptcoveff);
1.126 brouard 3793: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3794: j1=0;
1.145 brouard 3795: for(j1=1; j1<=tj;j1++){
3796: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3797: /*j1++;*/
1.126 brouard 3798: if (cptcovn>0) {
3799: fprintf(ficresprob, "\n#********** Variable ");
3800: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3801: fprintf(ficresprob, "**********\n#\n");
3802: fprintf(ficresprobcov, "\n#********** Variable ");
3803: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3804: fprintf(ficresprobcov, "**********\n#\n");
3805:
3806: fprintf(ficgp, "\n#********** Variable ");
3807: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3808: fprintf(ficgp, "**********\n#\n");
3809:
3810:
3811: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3812: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3813: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3814:
3815: fprintf(ficresprobcor, "\n#********** Variable ");
3816: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3817: fprintf(ficresprobcor, "**********\n#");
3818: }
3819:
1.145 brouard 3820: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3821: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3822: gp=vector(1,(nlstate)*(nlstate+ndeath));
3823: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3824: for (age=bage; age<=fage; age ++){
3825: cov[2]=age;
3826: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3827: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3828: * 1 1 1 1 1
3829: * 2 2 1 1 1
3830: * 3 1 2 1 1
3831: */
3832: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3833: }
3834: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3835: for (k=1; k<=cptcovprod;k++)
3836: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3837:
3838:
3839: for(theta=1; theta <=npar; theta++){
3840: for(i=1; i<=npar; i++)
3841: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3842:
3843: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3844:
3845: k=0;
3846: for(i=1; i<= (nlstate); i++){
3847: for(j=1; j<=(nlstate+ndeath);j++){
3848: k=k+1;
3849: gp[k]=pmmij[i][j];
3850: }
3851: }
3852:
3853: for(i=1; i<=npar; i++)
3854: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3855:
3856: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3857: k=0;
3858: for(i=1; i<=(nlstate); i++){
3859: for(j=1; j<=(nlstate+ndeath);j++){
3860: k=k+1;
3861: gm[k]=pmmij[i][j];
3862: }
3863: }
3864:
3865: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3866: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3867: }
3868:
3869: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3870: for(theta=1; theta <=npar; theta++)
3871: trgradg[j][theta]=gradg[theta][j];
3872:
3873: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3874: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3875:
3876: pmij(pmmij,cov,ncovmodel,x,nlstate);
3877:
3878: k=0;
3879: for(i=1; i<=(nlstate); i++){
3880: for(j=1; j<=(nlstate+ndeath);j++){
3881: k=k+1;
3882: mu[k][(int) age]=pmmij[i][j];
3883: }
3884: }
3885: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3886: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3887: varpij[i][j][(int)age] = doldm[i][j];
3888:
3889: /*printf("\n%d ",(int)age);
3890: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3891: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3892: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3893: }*/
3894:
3895: fprintf(ficresprob,"\n%d ",(int)age);
3896: fprintf(ficresprobcov,"\n%d ",(int)age);
3897: fprintf(ficresprobcor,"\n%d ",(int)age);
3898:
3899: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3900: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3901: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3902: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3903: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3904: }
3905: i=0;
3906: for (k=1; k<=(nlstate);k++){
3907: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3908: i++;
1.126 brouard 3909: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3910: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3911: for (j=1; j<=i;j++){
1.145 brouard 3912: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3913: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3914: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3915: }
3916: }
3917: }/* end of loop for state */
3918: } /* end of loop for age */
1.145 brouard 3919: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3920: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3921: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3922: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3923:
1.126 brouard 3924: /* Confidence intervalle of pij */
3925: /*
1.131 brouard 3926: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3927: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3928: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3929: 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);
3930: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3931: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3932: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3933: */
3934:
3935: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3936: first1=1;first2=2;
1.126 brouard 3937: for (k2=1; k2<=(nlstate);k2++){
3938: for (l2=1; l2<=(nlstate+ndeath);l2++){
3939: if(l2==k2) continue;
3940: j=(k2-1)*(nlstate+ndeath)+l2;
3941: for (k1=1; k1<=(nlstate);k1++){
3942: for (l1=1; l1<=(nlstate+ndeath);l1++){
3943: if(l1==k1) continue;
3944: i=(k1-1)*(nlstate+ndeath)+l1;
3945: if(i<=j) continue;
3946: for (age=bage; age<=fage; age ++){
3947: if ((int)age %5==0){
3948: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3949: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3950: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3951: mu1=mu[i][(int) age]/stepm*YEARM ;
3952: mu2=mu[j][(int) age]/stepm*YEARM;
3953: c12=cv12/sqrt(v1*v2);
3954: /* Computing eigen value of matrix of covariance */
3955: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3956: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3957: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3958: if(first2==1){
3959: first1=0;
3960: 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);
3961: }
3962: 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);
3963: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3964: /* lc2=fabs(lc2); */
1.135 brouard 3965: }
3966:
1.126 brouard 3967: /* Eigen vectors */
3968: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3969: /*v21=sqrt(1.-v11*v11); *//* error */
3970: v21=(lc1-v1)/cv12*v11;
3971: v12=-v21;
3972: v22=v11;
3973: tnalp=v21/v11;
3974: if(first1==1){
3975: first1=0;
3976: 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);
3977: }
3978: 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);
3979: /*printf(fignu*/
3980: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3981: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3982: if(first==1){
3983: first=0;
3984: fprintf(ficgp,"\nset parametric;unset label");
3985: 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 3986: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3987: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3988: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3989: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3990: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3991: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3992: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3993: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3994: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3995: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3996: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3997: 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",\
3998: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3999: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4000: }else{
4001: first=0;
4002: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4003: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4004: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4005: 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",\
4006: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4007: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4008: }/* if first */
4009: } /* age mod 5 */
4010: } /* end loop age */
4011: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4012: first=1;
4013: } /*l12 */
4014: } /* k12 */
4015: } /*l1 */
4016: }/* k1 */
1.145 brouard 4017: /* } /* loop covariates */
1.126 brouard 4018: }
4019: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4020: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4021: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4022: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4023: free_vector(xp,1,npar);
4024: fclose(ficresprob);
4025: fclose(ficresprobcov);
4026: fclose(ficresprobcor);
4027: fflush(ficgp);
4028: fflush(fichtmcov);
4029: }
4030:
4031:
4032: /******************* Printing html file ***********/
4033: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4034: int lastpass, int stepm, int weightopt, char model[],\
4035: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4036: int popforecast, int estepm ,\
4037: double jprev1, double mprev1,double anprev1, \
4038: double jprev2, double mprev2,double anprev2){
4039: int jj1, k1, i1, cpt;
4040:
4041: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4042: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4043: </ul>");
4044: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4045: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4046: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4047: fprintf(fichtm,"\
4048: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4049: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4050: fprintf(fichtm,"\
4051: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4052: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4053: fprintf(fichtm,"\
1.128 brouard 4054: - (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 4055: <a href=\"%s\">%s</a> <br>\n",
4056: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4057: fprintf(fichtm,"\
4058: - Population projections by age and states: \
4059: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4060:
4061: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4062:
1.145 brouard 4063: m=pow(2,cptcoveff);
1.126 brouard 4064: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4065:
4066: jj1=0;
4067: for(k1=1; k1<=m;k1++){
4068: for(i1=1; i1<=ncodemax[k1];i1++){
4069: jj1++;
4070: if (cptcovn > 0) {
4071: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4072: for (cpt=1; cpt<=cptcoveff;cpt++)
4073: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4074: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4075: }
4076: /* Pij */
1.145 brouard 4077: 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> \
4078: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4079: /* Quasi-incidences */
4080: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4081: 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> \
4082: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4083: /* Period (stable) prevalence in each health state */
1.154 brouard 4084: for(cpt=1; cpt<=nlstate;cpt++){
1.164 ! brouard 4085: fprintf(fichtm,"<br>- Convergence from cross-sectional prevalence in each state (1 to %d) to period (stable) prevalence in specific state %d <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
1.154 brouard 4086: <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 4087: }
4088: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4089: 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> \
4090: <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 4091: }
4092: } /* end i1 */
4093: }/* End k1 */
4094: fprintf(fichtm,"</ul>");
4095:
4096:
4097: fprintf(fichtm,"\
4098: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4099: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4100:
4101: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4102: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4103: fprintf(fichtm,"\
4104: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4105: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4106:
4107: fprintf(fichtm,"\
4108: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4109: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4110: fprintf(fichtm,"\
4111: - 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): \
4112: <a href=\"%s\">%s</a> <br>\n</li>",
4113: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4114: fprintf(fichtm,"\
4115: - (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): \
4116: <a href=\"%s\">%s</a> <br>\n</li>",
4117: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4118: fprintf(fichtm,"\
1.128 brouard 4119: - 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 4120: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4121: fprintf(fichtm,"\
1.128 brouard 4122: - 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",
4123: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4124: fprintf(fichtm,"\
4125: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4126: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4127:
4128: /* if(popforecast==1) fprintf(fichtm,"\n */
4129: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4130: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4131: /* <br>",fileres,fileres,fileres,fileres); */
4132: /* else */
4133: /* 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); */
4134: fflush(fichtm);
4135: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4136:
1.145 brouard 4137: m=pow(2,cptcoveff);
1.126 brouard 4138: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4139:
4140: jj1=0;
4141: for(k1=1; k1<=m;k1++){
4142: for(i1=1; i1<=ncodemax[k1];i1++){
4143: jj1++;
4144: if (cptcovn > 0) {
4145: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4146: for (cpt=1; cpt<=cptcoveff;cpt++)
4147: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4148: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4149: }
4150: for(cpt=1; cpt<=nlstate;cpt++) {
4151: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4152: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4153: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4154: }
4155: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4156: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4157: true period expectancies (those weighted with period prevalences are also\
4158: drawn in addition to the population based expectancies computed using\
4159: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4160: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4161: } /* end i1 */
4162: }/* End k1 */
4163: fprintf(fichtm,"</ul>");
4164: fflush(fichtm);
4165: }
4166:
4167: /******************* Gnuplot file **************/
4168: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4169:
4170: char dirfileres[132],optfileres[132];
1.164 ! brouard 4171: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4172: int ng=0;
1.126 brouard 4173: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4174: /* printf("Problem with file %s",optionfilegnuplot); */
4175: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4176: /* } */
4177:
4178: /*#ifdef windows */
4179: fprintf(ficgp,"cd \"%s\" \n",pathc);
4180: /*#endif */
4181: m=pow(2,cptcoveff);
4182:
4183: strcpy(dirfileres,optionfilefiname);
4184: strcpy(optfileres,"vpl");
4185: /* 1eme*/
1.153 brouard 4186: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4187: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4188: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4189: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4190: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4191: fprintf(ficgp,"set xlabel \"Age\" \n\
4192: set ylabel \"Probability\" \n\
1.145 brouard 4193: set ter png small size 320, 240\n\
1.126 brouard 4194: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4195:
4196: for (i=1; i<= nlstate ; i ++) {
4197: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4198: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4199: }
1.145 brouard 4200: 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 4201: for (i=1; i<= nlstate ; i ++) {
4202: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4203: else fprintf(ficgp," \%%*lf (\%%*lf)");
4204: }
1.145 brouard 4205: 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 4206: for (i=1; i<= nlstate ; i ++) {
4207: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4208: else fprintf(ficgp," \%%*lf (\%%*lf)");
4209: }
1.145 brouard 4210: 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 4211: }
4212: }
4213: /*2 eme*/
1.153 brouard 4214: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4215: for (k1=1; k1<= m ; k1 ++) {
4216: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4217: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4218:
4219: for (i=1; i<= nlstate+1 ; i ++) {
4220: k=2*i;
4221: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4222: for (j=1; j<= nlstate+1 ; j ++) {
4223: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4224: else fprintf(ficgp," \%%*lf (\%%*lf)");
4225: }
4226: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4227: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4228: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4229: for (j=1; j<= nlstate+1 ; j ++) {
4230: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4231: else fprintf(ficgp," \%%*lf (\%%*lf)");
4232: }
1.145 brouard 4233: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4234: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4235: for (j=1; j<= nlstate+1 ; j ++) {
4236: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4237: else fprintf(ficgp," \%%*lf (\%%*lf)");
4238: }
1.145 brouard 4239: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4240: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4241: }
4242: }
4243:
4244: /*3eme*/
4245:
4246: for (k1=1; k1<= m ; k1 ++) {
4247: for (cpt=1; cpt<= nlstate ; cpt ++) {
4248: /* k=2+nlstate*(2*cpt-2); */
4249: k=2+(nlstate+1)*(cpt-1);
4250: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4251: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4252: 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);
4253: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4254: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4255: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4256: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4257: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4258: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4259:
4260: */
4261: for (i=1; i< nlstate ; i ++) {
4262: 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);
4263: /* 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);*/
4264:
4265: }
4266: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4267: }
4268: }
4269:
4270: /* CV preval stable (period) */
1.153 brouard 4271: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4272: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4273: k=3;
1.153 brouard 4274: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4275: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4276: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4277: set ter png small size 320, 240\n\
1.126 brouard 4278: unset log y\n\
1.153 brouard 4279: plot [%.f:%.f] ", ageminpar, agemaxpar);
4280: for (i=1; i<= nlstate ; i ++){
4281: if(i==1)
4282: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4283: else
4284: fprintf(ficgp,", '' ");
1.154 brouard 4285: l=(nlstate+ndeath)*(i-1)+1;
4286: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4287: for (j=1; j<= (nlstate-1) ; j ++)
4288: fprintf(ficgp,"+$%d",k+l+j);
4289: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4290: } /* nlstate */
4291: fprintf(ficgp,"\n");
4292: } /* end cpt state*/
4293: } /* end covariate */
1.126 brouard 4294:
4295: /* proba elementaires */
4296: for(i=1,jk=1; i <=nlstate; i++){
4297: for(k=1; k <=(nlstate+ndeath); k++){
4298: if (k != i) {
4299: for(j=1; j <=ncovmodel; j++){
4300: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4301: jk++;
4302: fprintf(ficgp,"\n");
4303: }
4304: }
4305: }
4306: }
1.145 brouard 4307: /*goto avoid;*/
1.126 brouard 4308: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4309: for(jk=1; jk <=m; jk++) {
1.145 brouard 4310: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4311: if (ng==2)
4312: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4313: else
4314: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4315: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4316: i=1;
4317: for(k2=1; k2<=nlstate; k2++) {
4318: k3=i;
4319: for(k=1; k<=(nlstate+ndeath); k++) {
4320: if (k != k2){
4321: if(ng==2)
4322: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4323: else
4324: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4325: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4326: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4327: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4328: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4329: /* ij++; */
4330: /* } */
4331: /* else */
1.126 brouard 4332: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4333: }
4334: fprintf(ficgp,")/(1");
4335:
4336: for(k1=1; k1 <=nlstate; k1++){
4337: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4338: ij=1;
4339: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4340: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4341: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4342: /* ij++; */
4343: /* } */
4344: /* else */
1.126 brouard 4345: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4346: }
4347: fprintf(ficgp,")");
4348: }
4349: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4350: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4351: i=i+ncovmodel;
4352: }
4353: } /* end k */
4354: } /* end k2 */
4355: } /* end jk */
4356: } /* end ng */
1.164 ! brouard 4357: /* avoid: */
1.126 brouard 4358: fflush(ficgp);
4359: } /* end gnuplot */
4360:
4361:
4362: /*************** Moving average **************/
4363: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4364:
4365: int i, cpt, cptcod;
4366: int modcovmax =1;
4367: int mobilavrange, mob;
4368: double age;
4369:
4370: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4371: a covariate has 2 modalities */
4372: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4373:
4374: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4375: if(mobilav==1) mobilavrange=5; /* default */
4376: else mobilavrange=mobilav;
4377: for (age=bage; age<=fage; age++)
4378: for (i=1; i<=nlstate;i++)
4379: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4380: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4381: /* We keep the original values on the extreme ages bage, fage and for
4382: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4383: we use a 5 terms etc. until the borders are no more concerned.
4384: */
4385: for (mob=3;mob <=mobilavrange;mob=mob+2){
4386: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4387: for (i=1; i<=nlstate;i++){
4388: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4389: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4390: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4391: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4392: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4393: }
4394: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4395: }
4396: }
4397: }/* end age */
4398: }/* end mob */
4399: }else return -1;
4400: return 0;
4401: }/* End movingaverage */
4402:
4403:
4404: /************** Forecasting ******************/
4405: 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){
4406: /* proj1, year, month, day of starting projection
4407: agemin, agemax range of age
4408: dateprev1 dateprev2 range of dates during which prevalence is computed
4409: anproj2 year of en of projection (same day and month as proj1).
4410: */
1.164 ! brouard 4411: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4412: double agec; /* generic age */
4413: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4414: double *popeffectif,*popcount;
4415: double ***p3mat;
4416: double ***mobaverage;
4417: char fileresf[FILENAMELENGTH];
4418:
4419: agelim=AGESUP;
4420: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4421:
4422: strcpy(fileresf,"f");
4423: strcat(fileresf,fileres);
4424: if((ficresf=fopen(fileresf,"w"))==NULL) {
4425: printf("Problem with forecast resultfile: %s\n", fileresf);
4426: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4427: }
4428: printf("Computing forecasting: result on file '%s' \n", fileresf);
4429: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4430:
4431: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4432:
4433: if (mobilav!=0) {
4434: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4435: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4436: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4437: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4438: }
4439: }
4440:
4441: stepsize=(int) (stepm+YEARM-1)/YEARM;
4442: if (stepm<=12) stepsize=1;
4443: if(estepm < stepm){
4444: printf ("Problem %d lower than %d\n",estepm, stepm);
4445: }
4446: else hstepm=estepm;
4447:
4448: hstepm=hstepm/stepm;
4449: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4450: fractional in yp1 */
4451: anprojmean=yp;
4452: yp2=modf((yp1*12),&yp);
4453: mprojmean=yp;
4454: yp1=modf((yp2*30.5),&yp);
4455: jprojmean=yp;
4456: if(jprojmean==0) jprojmean=1;
4457: if(mprojmean==0) jprojmean=1;
4458:
4459: i1=cptcoveff;
4460: if (cptcovn < 1){i1=1;}
4461:
4462: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4463:
4464: fprintf(ficresf,"#****** Routine prevforecast **\n");
4465:
4466: /* if (h==(int)(YEARM*yearp)){ */
4467: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4468: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4469: k=k+1;
4470: fprintf(ficresf,"\n#******");
4471: for(j=1;j<=cptcoveff;j++) {
4472: 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]]);
4473: }
4474: fprintf(ficresf,"******\n");
4475: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4476: for(j=1; j<=nlstate+ndeath;j++){
4477: for(i=1; i<=nlstate;i++)
4478: fprintf(ficresf," p%d%d",i,j);
4479: fprintf(ficresf," p.%d",j);
4480: }
4481: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4482: fprintf(ficresf,"\n");
4483: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4484:
4485: for (agec=fage; agec>=(ageminpar-1); agec--){
4486: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4487: nhstepm = nhstepm/hstepm;
4488: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4489: oldm=oldms;savm=savms;
4490: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4491:
4492: for (h=0; h<=nhstepm; h++){
4493: if (h*hstepm/YEARM*stepm ==yearp) {
4494: fprintf(ficresf,"\n");
4495: for(j=1;j<=cptcoveff;j++)
4496: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4497: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4498: }
4499: for(j=1; j<=nlstate+ndeath;j++) {
4500: ppij=0.;
4501: for(i=1; i<=nlstate;i++) {
4502: if (mobilav==1)
4503: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4504: else {
4505: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4506: }
4507: if (h*hstepm/YEARM*stepm== yearp) {
4508: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4509: }
4510: } /* end i */
4511: if (h*hstepm/YEARM*stepm==yearp) {
4512: fprintf(ficresf," %.3f", ppij);
4513: }
4514: }/* end j */
4515: } /* end h */
4516: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4517: } /* end agec */
4518: } /* end yearp */
4519: } /* end cptcod */
4520: } /* end cptcov */
4521:
4522: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4523:
4524: fclose(ficresf);
4525: }
4526:
4527: /************** Forecasting *****not tested NB*************/
4528: 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){
4529:
4530: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4531: int *popage;
4532: double calagedatem, agelim, kk1, kk2;
4533: double *popeffectif,*popcount;
4534: double ***p3mat,***tabpop,***tabpopprev;
4535: double ***mobaverage;
4536: char filerespop[FILENAMELENGTH];
4537:
4538: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4539: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4540: agelim=AGESUP;
4541: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4542:
4543: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4544:
4545:
4546: strcpy(filerespop,"pop");
4547: strcat(filerespop,fileres);
4548: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4549: printf("Problem with forecast resultfile: %s\n", filerespop);
4550: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4551: }
4552: printf("Computing forecasting: result on file '%s' \n", filerespop);
4553: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4554:
4555: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4556:
4557: if (mobilav!=0) {
4558: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4559: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4560: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4561: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4562: }
4563: }
4564:
4565: stepsize=(int) (stepm+YEARM-1)/YEARM;
4566: if (stepm<=12) stepsize=1;
4567:
4568: agelim=AGESUP;
4569:
4570: hstepm=1;
4571: hstepm=hstepm/stepm;
4572:
4573: if (popforecast==1) {
4574: if((ficpop=fopen(popfile,"r"))==NULL) {
4575: printf("Problem with population file : %s\n",popfile);exit(0);
4576: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4577: }
4578: popage=ivector(0,AGESUP);
4579: popeffectif=vector(0,AGESUP);
4580: popcount=vector(0,AGESUP);
4581:
4582: i=1;
4583: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4584:
4585: imx=i;
4586: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4587: }
4588:
4589: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4590: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4591: k=k+1;
4592: fprintf(ficrespop,"\n#******");
4593: for(j=1;j<=cptcoveff;j++) {
4594: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4595: }
4596: fprintf(ficrespop,"******\n");
4597: fprintf(ficrespop,"# Age");
4598: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4599: if (popforecast==1) fprintf(ficrespop," [Population]");
4600:
4601: for (cpt=0; cpt<=0;cpt++) {
4602: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4603:
4604: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4605: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4606: nhstepm = nhstepm/hstepm;
4607:
4608: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4609: oldm=oldms;savm=savms;
4610: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4611:
4612: for (h=0; h<=nhstepm; h++){
4613: if (h==(int) (calagedatem+YEARM*cpt)) {
4614: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4615: }
4616: for(j=1; j<=nlstate+ndeath;j++) {
4617: kk1=0.;kk2=0;
4618: for(i=1; i<=nlstate;i++) {
4619: if (mobilav==1)
4620: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4621: else {
4622: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4623: }
4624: }
4625: if (h==(int)(calagedatem+12*cpt)){
4626: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4627: /*fprintf(ficrespop," %.3f", kk1);
4628: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4629: }
4630: }
4631: for(i=1; i<=nlstate;i++){
4632: kk1=0.;
4633: for(j=1; j<=nlstate;j++){
4634: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4635: }
4636: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4637: }
4638:
4639: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4640: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4641: }
4642: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4643: }
4644: }
4645:
4646: /******/
4647:
4648: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4649: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4650: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4651: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4652: nhstepm = nhstepm/hstepm;
4653:
4654: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4655: oldm=oldms;savm=savms;
4656: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4657: for (h=0; h<=nhstepm; h++){
4658: if (h==(int) (calagedatem+YEARM*cpt)) {
4659: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4660: }
4661: for(j=1; j<=nlstate+ndeath;j++) {
4662: kk1=0.;kk2=0;
4663: for(i=1; i<=nlstate;i++) {
4664: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4665: }
4666: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4667: }
4668: }
4669: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4670: }
4671: }
4672: }
4673: }
4674:
4675: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4676:
4677: if (popforecast==1) {
4678: free_ivector(popage,0,AGESUP);
4679: free_vector(popeffectif,0,AGESUP);
4680: free_vector(popcount,0,AGESUP);
4681: }
4682: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4683: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4684: fclose(ficrespop);
4685: } /* End of popforecast */
4686:
4687: int fileappend(FILE *fichier, char *optionfich)
4688: {
4689: if((fichier=fopen(optionfich,"a"))==NULL) {
4690: printf("Problem with file: %s\n", optionfich);
4691: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4692: return (0);
4693: }
4694: fflush(fichier);
4695: return (1);
4696: }
4697:
4698:
4699: /**************** function prwizard **********************/
4700: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4701: {
4702:
4703: /* Wizard to print covariance matrix template */
4704:
1.164 ! brouard 4705: char ca[32], cb[32];
! 4706: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4707: int numlinepar;
4708:
4709: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4710: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4711: for(i=1; i <=nlstate; i++){
4712: jj=0;
4713: for(j=1; j <=nlstate+ndeath; j++){
4714: if(j==i) continue;
4715: jj++;
4716: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4717: printf("%1d%1d",i,j);
4718: fprintf(ficparo,"%1d%1d",i,j);
4719: for(k=1; k<=ncovmodel;k++){
4720: /* printf(" %lf",param[i][j][k]); */
4721: /* fprintf(ficparo," %lf",param[i][j][k]); */
4722: printf(" 0.");
4723: fprintf(ficparo," 0.");
4724: }
4725: printf("\n");
4726: fprintf(ficparo,"\n");
4727: }
4728: }
4729: printf("# Scales (for hessian or gradient estimation)\n");
4730: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4731: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4732: for(i=1; i <=nlstate; i++){
4733: jj=0;
4734: for(j=1; j <=nlstate+ndeath; j++){
4735: if(j==i) continue;
4736: jj++;
4737: fprintf(ficparo,"%1d%1d",i,j);
4738: printf("%1d%1d",i,j);
4739: fflush(stdout);
4740: for(k=1; k<=ncovmodel;k++){
4741: /* printf(" %le",delti3[i][j][k]); */
4742: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4743: printf(" 0.");
4744: fprintf(ficparo," 0.");
4745: }
4746: numlinepar++;
4747: printf("\n");
4748: fprintf(ficparo,"\n");
4749: }
4750: }
4751: printf("# Covariance matrix\n");
4752: /* # 121 Var(a12)\n\ */
4753: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4754: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4755: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4756: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4757: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4758: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4759: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4760: fflush(stdout);
4761: fprintf(ficparo,"# Covariance matrix\n");
4762: /* # 121 Var(a12)\n\ */
4763: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4764: /* # ...\n\ */
4765: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4766:
4767: for(itimes=1;itimes<=2;itimes++){
4768: jj=0;
4769: for(i=1; i <=nlstate; i++){
4770: for(j=1; j <=nlstate+ndeath; j++){
4771: if(j==i) continue;
4772: for(k=1; k<=ncovmodel;k++){
4773: jj++;
4774: ca[0]= k+'a'-1;ca[1]='\0';
4775: if(itimes==1){
4776: printf("#%1d%1d%d",i,j,k);
4777: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4778: }else{
4779: printf("%1d%1d%d",i,j,k);
4780: fprintf(ficparo,"%1d%1d%d",i,j,k);
4781: /* printf(" %.5le",matcov[i][j]); */
4782: }
4783: ll=0;
4784: for(li=1;li <=nlstate; li++){
4785: for(lj=1;lj <=nlstate+ndeath; lj++){
4786: if(lj==li) continue;
4787: for(lk=1;lk<=ncovmodel;lk++){
4788: ll++;
4789: if(ll<=jj){
4790: cb[0]= lk +'a'-1;cb[1]='\0';
4791: if(ll<jj){
4792: if(itimes==1){
4793: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4794: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4795: }else{
4796: printf(" 0.");
4797: fprintf(ficparo," 0.");
4798: }
4799: }else{
4800: if(itimes==1){
4801: printf(" Var(%s%1d%1d)",ca,i,j);
4802: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4803: }else{
4804: printf(" 0.");
4805: fprintf(ficparo," 0.");
4806: }
4807: }
4808: }
4809: } /* end lk */
4810: } /* end lj */
4811: } /* end li */
4812: printf("\n");
4813: fprintf(ficparo,"\n");
4814: numlinepar++;
4815: } /* end k*/
4816: } /*end j */
4817: } /* end i */
4818: } /* end itimes */
4819:
4820: } /* end of prwizard */
4821: /******************* Gompertz Likelihood ******************************/
4822: double gompertz(double x[])
4823: {
4824: double A,B,L=0.0,sump=0.,num=0.;
4825: int i,n=0; /* n is the size of the sample */
4826:
4827: for (i=0;i<=imx-1 ; i++) {
4828: sump=sump+weight[i];
4829: /* sump=sump+1;*/
4830: num=num+1;
4831: }
4832:
4833:
4834: /* for (i=0; i<=imx; i++)
4835: 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]);*/
4836:
4837: for (i=1;i<=imx ; i++)
4838: {
4839: if (cens[i] == 1 && wav[i]>1)
4840: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4841:
4842: if (cens[i] == 0 && wav[i]>1)
4843: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4844: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4845:
4846: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4847: if (wav[i] > 1 ) { /* ??? */
4848: L=L+A*weight[i];
4849: /* 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]);*/
4850: }
4851: }
4852:
4853: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4854:
4855: return -2*L*num/sump;
4856: }
4857:
1.136 brouard 4858: #ifdef GSL
4859: /******************* Gompertz_f Likelihood ******************************/
4860: double gompertz_f(const gsl_vector *v, void *params)
4861: {
4862: double A,B,LL=0.0,sump=0.,num=0.;
4863: double *x= (double *) v->data;
4864: int i,n=0; /* n is the size of the sample */
4865:
4866: for (i=0;i<=imx-1 ; i++) {
4867: sump=sump+weight[i];
4868: /* sump=sump+1;*/
4869: num=num+1;
4870: }
4871:
4872:
4873: /* for (i=0; i<=imx; i++)
4874: 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]);*/
4875: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4876: for (i=1;i<=imx ; i++)
4877: {
4878: if (cens[i] == 1 && wav[i]>1)
4879: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4880:
4881: if (cens[i] == 0 && wav[i]>1)
4882: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4883: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4884:
4885: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4886: if (wav[i] > 1 ) { /* ??? */
4887: LL=LL+A*weight[i];
4888: /* 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]);*/
4889: }
4890: }
4891:
4892: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4893: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4894:
4895: return -2*LL*num/sump;
4896: }
4897: #endif
4898:
1.126 brouard 4899: /******************* Printing html file ***********/
4900: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4901: int lastpass, int stepm, int weightopt, char model[],\
4902: int imx, double p[],double **matcov,double agemortsup){
4903: int i,k;
4904:
4905: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4906: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4907: for (i=1;i<=2;i++)
4908: 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]));
4909: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4910: fprintf(fichtm,"</ul>");
4911:
4912: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4913:
4914: 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>");
4915:
4916: for (k=agegomp;k<(agemortsup-2);k++)
4917: 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]);
4918:
4919:
4920: fflush(fichtm);
4921: }
4922:
4923: /******************* Gnuplot file **************/
4924: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4925:
4926: char dirfileres[132],optfileres[132];
1.164 ! brouard 4927:
1.126 brouard 4928: int ng;
4929:
4930:
4931: /*#ifdef windows */
4932: fprintf(ficgp,"cd \"%s\" \n",pathc);
4933: /*#endif */
4934:
4935:
4936: strcpy(dirfileres,optionfilefiname);
4937: strcpy(optfileres,"vpl");
4938: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4939: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4940: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4941: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4942: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4943:
4944: }
4945:
1.136 brouard 4946: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4947: {
1.126 brouard 4948:
1.136 brouard 4949: /*-------- data file ----------*/
4950: FILE *fic;
4951: char dummy[]=" ";
1.164 ! brouard 4952: int i=0, j=0, n=0;
1.136 brouard 4953: int linei, month, year,iout;
4954: char line[MAXLINE], linetmp[MAXLINE];
1.164 ! brouard 4955: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 4956: char *stratrunc;
4957: int lstra;
1.126 brouard 4958:
4959:
1.136 brouard 4960: if((fic=fopen(datafile,"r"))==NULL) {
4961: printf("Problem while opening datafile: %s\n", datafile);return 1;
4962: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4963: }
1.126 brouard 4964:
1.136 brouard 4965: i=1;
4966: linei=0;
4967: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4968: linei=linei+1;
4969: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4970: if(line[j] == '\t')
4971: line[j] = ' ';
4972: }
4973: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4974: ;
4975: };
4976: line[j+1]=0; /* Trims blanks at end of line */
4977: if(line[0]=='#'){
4978: fprintf(ficlog,"Comment line\n%s\n",line);
4979: printf("Comment line\n%s\n",line);
4980: continue;
4981: }
4982: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 ! brouard 4983: strcpy(line, linetmp);
1.136 brouard 4984:
1.126 brouard 4985:
1.136 brouard 4986: for (j=maxwav;j>=1;j--){
1.137 brouard 4987: cutv(stra, strb, line, ' ');
1.136 brouard 4988: if(strb[0]=='.') { /* Missing status */
4989: lval=-1;
4990: }else{
4991: errno=0;
4992: lval=strtol(strb,&endptr,10);
4993: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4994: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4995: 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);
4996: 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 4997: return 1;
4998: }
4999: }
5000: s[j][i]=lval;
5001:
5002: strcpy(line,stra);
5003: cutv(stra, strb,line,' ');
5004: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5005: }
1.145 brouard 5006: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 5007: month=99;
5008: year=9999;
5009: }else{
1.141 brouard 5010: 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);
5011: 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 5012: return 1;
5013: }
5014: anint[j][i]= (double) year;
5015: mint[j][i]= (double)month;
5016: strcpy(line,stra);
5017: } /* ENd Waves */
5018:
5019: cutv(stra, strb,line,' ');
5020: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5021: }
5022: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5023: month=99;
5024: year=9999;
5025: }else{
1.141 brouard 5026: 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);
5027: 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 5028: return 1;
5029: }
5030: andc[i]=(double) year;
5031: moisdc[i]=(double) month;
5032: strcpy(line,stra);
5033:
5034: cutv(stra, strb,line,' ');
5035: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5036: }
1.145 brouard 5037: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 5038: month=99;
5039: year=9999;
5040: }else{
1.141 brouard 5041: 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);
5042: 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 5043: return 1;
5044: }
5045: if (year==9999) {
1.141 brouard 5046: 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);
5047: 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 5048: return 1;
1.126 brouard 5049:
1.136 brouard 5050: }
5051: annais[i]=(double)(year);
5052: moisnais[i]=(double)(month);
5053: strcpy(line,stra);
5054:
5055: cutv(stra, strb,line,' ');
5056: errno=0;
5057: dval=strtod(strb,&endptr);
5058: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5059: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5060: 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 5061: fflush(ficlog);
5062: return 1;
5063: }
5064: weight[i]=dval;
5065: strcpy(line,stra);
5066:
5067: for (j=ncovcol;j>=1;j--){
5068: cutv(stra, strb,line,' ');
5069: if(strb[0]=='.') { /* Missing status */
5070: lval=-1;
5071: }else{
5072: errno=0;
5073: lval=strtol(strb,&endptr,10);
5074: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5075: 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);
5076: 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 5077: return 1;
5078: }
5079: }
5080: if(lval <-1 || lval >1){
1.141 brouard 5081: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5082: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5083: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5084: For example, for multinomial values like 1, 2 and 3,\n \
5085: build V1=0 V2=0 for the reference value (1),\n \
5086: V1=1 V2=0 for (2) \n \
5087: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5088: output of IMaCh is often meaningless.\n \
5089: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5090: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5091: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5092: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5093: For example, for multinomial values like 1, 2 and 3,\n \
5094: build V1=0 V2=0 for the reference value (1),\n \
5095: V1=1 V2=0 for (2) \n \
5096: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5097: output of IMaCh is often meaningless.\n \
5098: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5099: return 1;
5100: }
5101: covar[j][i]=(double)(lval);
5102: strcpy(line,stra);
5103: }
5104: lstra=strlen(stra);
5105:
5106: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5107: stratrunc = &(stra[lstra-9]);
5108: num[i]=atol(stratrunc);
5109: }
5110: else
5111: num[i]=atol(stra);
5112: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5113: 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;}*/
5114:
5115: i=i+1;
5116: } /* End loop reading data */
1.126 brouard 5117:
1.136 brouard 5118: *imax=i-1; /* Number of individuals */
5119: fclose(fic);
5120:
5121: return (0);
1.164 ! brouard 5122: /* endread: */
1.136 brouard 5123: printf("Exiting readdata: ");
5124: fclose(fic);
5125: return (1);
1.126 brouard 5126:
5127:
5128:
1.136 brouard 5129: }
1.145 brouard 5130: void removespace(char *str) {
5131: char *p1 = str, *p2 = str;
5132: do
5133: while (*p2 == ' ')
5134: p2++;
5135: while (*p1++ = *p2++);
5136: }
5137:
5138: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5139: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5140: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5141: * - cptcovn or number of covariates k of the models excluding age*products =6
5142: * - cptcovage number of covariates with age*products =2
5143: * - cptcovs number of simple covariates
5144: * - 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
5145: * which is a new column after the 9 (ncovcol) variables.
5146: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5147: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5148: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5149: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5150: */
1.136 brouard 5151: {
1.145 brouard 5152: int i, j, k, ks;
1.164 ! brouard 5153: int j1, k1, k2;
1.136 brouard 5154: char modelsav[80];
1.145 brouard 5155: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5156:
1.145 brouard 5157: /*removespace(model);*/
1.136 brouard 5158: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5159: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5160: j=nbocc(model,'+'); /**< j=Number of '+' */
5161: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5162: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5163: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5164: /* including age products which are counted in cptcovage.
5165: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5166: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5167: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5168: strcpy(modelsav,model);
1.137 brouard 5169: if (strstr(model,"AGE") !=0){
5170: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5171: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5172: return 1;
5173: }
1.141 brouard 5174: if (strstr(model,"v") !=0){
5175: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5176: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5177: return 1;
5178: }
1.136 brouard 5179:
1.145 brouard 5180: /* Design
5181: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5182: * < ncovcol=8 >
5183: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5184: * k= 1 2 3 4 5 6 7 8
5185: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5186: * covar[k,i], value of kth covariate if not including age for individual i:
5187: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5188: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5189: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5190: * Tage[++cptcovage]=k
5191: * if products, new covar are created after ncovcol with k1
5192: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5193: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5194: * 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
5195: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5196: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5197: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5198: * < ncovcol=8 >
5199: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5200: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5201: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5202: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5203: * p Tprod[1]@2={ 6, 5}
5204: *p Tvard[1][1]@4= {7, 8, 5, 6}
5205: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5206: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5207: *How to reorganize?
5208: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5209: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5210: * {2, 1, 4, 8, 5, 6, 3, 7}
5211: * Struct []
5212: */
5213:
1.136 brouard 5214: /* This loop fills the array Tvar from the string 'model'.*/
5215: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5216: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5217: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5218: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5219: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5220: /* k=1 Tvar[1]=2 (from V2) */
5221: /* k=5 Tvar[5] */
5222: /* for (k=1; k<=cptcovn;k++) { */
5223: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5224: /* } */
5225: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5226: /*
5227: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5228: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5229: Tvar[k]=0;
5230: cptcovage=0;
5231: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5232: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5233: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5234: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5235: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5236: /*scanf("%d",i);*/
1.145 brouard 5237: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5238: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5239: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5240: /* covar is not filled and then is empty */
1.136 brouard 5241: cptcovprod--;
1.145 brouard 5242: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5243: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5244: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5245: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5246: /*printf("stre=%s ", stre);*/
1.137 brouard 5247: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5248: cptcovprod--;
1.145 brouard 5249: cutl(stre,strb,strc,'V');
1.136 brouard 5250: Tvar[k]=atoi(stre);
5251: cptcovage++;
5252: Tage[cptcovage]=k;
1.137 brouard 5253: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5254: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5255: cptcovn++;
5256: cptcovprodnoage++;k1++;
5257: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5258: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5259: because this model-covariate is a construction we invent a new column
5260: ncovcol + k1
5261: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5262: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5263: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5264: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5265: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5266: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5267: k2=k2+2;
5268: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5269: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5270: for (i=1; i<=lastobs;i++){
5271: /* Computes the new covariate which is a product of
1.145 brouard 5272: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5273: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5274: }
5275: } /* End age is not in the model */
5276: } /* End if model includes a product */
1.136 brouard 5277: else { /* no more sum */
5278: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5279: /* scanf("%d",i);*/
1.145 brouard 5280: cutl(strd,strc,strb,'V');
5281: ks++; /**< Number of simple covariates */
5282: cptcovn++;
5283: Tvar[k]=atoi(strd);
1.136 brouard 5284: }
1.137 brouard 5285: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5286: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5287: scanf("%d",i);*/
5288: } /* end of loop + */
5289: } /* end model */
5290:
5291: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5292: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5293:
5294: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5295: printf("cptcovprod=%d ", cptcovprod);
5296: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5297:
5298: scanf("%d ",i);*/
5299:
5300:
1.137 brouard 5301: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 ! brouard 5302: /*endread:*/
1.136 brouard 5303: printf("Exiting decodemodel: ");
5304: return (1);
5305: }
5306:
5307: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5308: {
5309: int i, m;
5310:
5311: for (i=1; i<=imx; i++) {
5312: for(m=2; (m<= maxwav); m++) {
5313: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5314: anint[m][i]=9999;
5315: s[m][i]=-1;
5316: }
5317: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5318: *nberr++;
5319: 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);
5320: 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);
5321: s[m][i]=-1;
5322: }
5323: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5324: *nberr++;
5325: 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]);
5326: 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]);
5327: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5328: }
5329: }
5330: }
5331:
5332: for (i=1; i<=imx; i++) {
5333: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5334: for(m=firstpass; (m<= lastpass); m++){
5335: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5336: if (s[m][i] >= nlstate+1) {
5337: if(agedc[i]>0)
5338: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5339: agev[m][i]=agedc[i];
5340: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5341: else {
5342: if ((int)andc[i]!=9999){
5343: nbwarn++;
5344: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5345: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5346: agev[m][i]=-1;
5347: }
5348: }
5349: }
5350: else if(s[m][i] !=9){ /* Standard case, age in fractional
5351: years but with the precision of a month */
5352: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5353: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5354: agev[m][i]=1;
5355: else if(agev[m][i] < *agemin){
5356: *agemin=agev[m][i];
5357: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5358: }
5359: else if(agev[m][i] >*agemax){
5360: *agemax=agev[m][i];
1.156 brouard 5361: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5362: }
5363: /*agev[m][i]=anint[m][i]-annais[i];*/
5364: /* agev[m][i] = age[i]+2*m;*/
5365: }
5366: else { /* =9 */
5367: agev[m][i]=1;
5368: s[m][i]=-1;
5369: }
5370: }
5371: else /*= 0 Unknown */
5372: agev[m][i]=1;
5373: }
5374:
5375: }
5376: for (i=1; i<=imx; i++) {
5377: for(m=firstpass; (m<=lastpass); m++){
5378: if (s[m][i] > (nlstate+ndeath)) {
5379: *nberr++;
5380: 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);
5381: 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);
5382: return 1;
5383: }
5384: }
5385: }
5386:
5387: /*for (i=1; i<=imx; i++){
5388: for (m=firstpass; (m<lastpass); m++){
5389: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5390: }
5391:
5392: }*/
5393:
5394:
1.139 brouard 5395: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5396: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5397:
5398: return (0);
1.164 ! brouard 5399: /* endread:*/
1.136 brouard 5400: printf("Exiting calandcheckages: ");
5401: return (1);
5402: }
5403:
5404:
5405: /***********************************************/
5406: /**************** Main Program *****************/
5407: /***********************************************/
5408:
5409: int main(int argc, char *argv[])
5410: {
5411: #ifdef GSL
5412: const gsl_multimin_fminimizer_type *T;
5413: size_t iteri = 0, it;
5414: int rval = GSL_CONTINUE;
5415: int status = GSL_SUCCESS;
5416: double ssval;
5417: #endif
5418: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 ! brouard 5419: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
! 5420:
! 5421: int jj, ll, li, lj, lk;
1.136 brouard 5422: int numlinepar=0; /* Current linenumber of parameter file */
5423: int itimes;
5424: int NDIM=2;
5425: int vpopbased=0;
5426:
1.164 ! brouard 5427: char ca[32], cb[32];
1.136 brouard 5428: /* FILE *fichtm; *//* Html File */
5429: /* FILE *ficgp;*/ /*Gnuplot File */
5430: struct stat info;
1.164 ! brouard 5431: double agedeb;
1.136 brouard 5432: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5433:
5434:
5435: double dum; /* Dummy variable */
5436: double ***p3mat;
5437: double ***mobaverage;
1.164 ! brouard 5438:
! 5439: char line[MAXLINE];
1.136 brouard 5440: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5441: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 ! brouard 5442: char *tok, *val; /* pathtot */
1.136 brouard 5443: int firstobs=1, lastobs=10;
1.164 ! brouard 5444: int c, h , cpt;
! 5445: int jl;
! 5446: int i1, j1, jk, stepsize;
! 5447: int *tab;
1.136 brouard 5448: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5449: int mobilav=0,popforecast=0;
5450: int hstepm, nhstepm;
5451: int agemortsup;
5452: float sumlpop=0.;
5453: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5454: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5455:
1.164 ! brouard 5456: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5457: double ftolpl=FTOL;
5458: double **prlim;
5459: double ***param; /* Matrix of parameters */
5460: double *p;
5461: double **matcov; /* Matrix of covariance */
5462: double ***delti3; /* Scale */
5463: double *delti; /* Scale */
5464: double ***eij, ***vareij;
5465: double **varpl; /* Variances of prevalence limits by age */
5466: double *epj, vepp;
1.164 ! brouard 5467:
1.136 brouard 5468: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5469: double **ximort;
1.145 brouard 5470: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5471: int *dcwave;
5472:
1.164 ! brouard 5473: char z[1]="c";
1.136 brouard 5474:
5475: /*char *strt;*/
5476: char strtend[80];
1.126 brouard 5477:
1.164 ! brouard 5478:
1.126 brouard 5479: /* setlocale (LC_ALL, ""); */
5480: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5481: /* textdomain (PACKAGE); */
5482: /* setlocale (LC_CTYPE, ""); */
5483: /* setlocale (LC_MESSAGES, ""); */
5484:
5485: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5486: rstart_time = time(NULL);
5487: /* (void) gettimeofday(&start_time,&tzp);*/
5488: start_time = *localtime(&rstart_time);
1.126 brouard 5489: curr_time=start_time;
1.157 brouard 5490: /*tml = *localtime(&start_time.tm_sec);*/
5491: /* strcpy(strstart,asctime(&tml)); */
5492: strcpy(strstart,asctime(&start_time));
1.126 brouard 5493:
5494: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5495: /* tp.tm_sec = tp.tm_sec +86400; */
5496: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5497: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5498: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5499: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5500: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5501: /* strt=asctime(&tmg); */
5502: /* printf("Time(after) =%s",strstart); */
5503: /* (void) time (&time_value);
5504: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5505: * tm = *localtime(&time_value);
5506: * strstart=asctime(&tm);
5507: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5508: */
5509:
5510: nberr=0; /* Number of errors and warnings */
5511: nbwarn=0;
5512: getcwd(pathcd, size);
5513:
5514: printf("\n%s\n%s",version,fullversion);
5515: if(argc <=1){
5516: printf("\nEnter the parameter file name: ");
5517: fgets(pathr,FILENAMELENGTH,stdin);
5518: i=strlen(pathr);
5519: if(pathr[i-1]=='\n')
5520: pathr[i-1]='\0';
1.156 brouard 5521: i=strlen(pathr);
5522: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5523: pathr[i-1]='\0';
1.126 brouard 5524: for (tok = pathr; tok != NULL; ){
5525: printf("Pathr |%s|\n",pathr);
5526: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5527: printf("val= |%s| pathr=%s\n",val,pathr);
5528: strcpy (pathtot, val);
5529: if(pathr[0] == '\0') break; /* Dirty */
5530: }
5531: }
5532: else{
5533: strcpy(pathtot,argv[1]);
5534: }
5535: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5536: /*cygwin_split_path(pathtot,path,optionfile);
5537: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5538: /* cutv(path,optionfile,pathtot,'\\');*/
5539:
5540: /* Split argv[0], imach program to get pathimach */
5541: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5542: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5543: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5544: /* strcpy(pathimach,argv[0]); */
5545: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5546: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5547: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5548: chdir(path); /* Can be a relative path */
5549: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5550: printf("Current directory %s!\n",pathcd);
5551: strcpy(command,"mkdir ");
5552: strcat(command,optionfilefiname);
5553: if((outcmd=system(command)) != 0){
5554: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5555: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5556: /* fclose(ficlog); */
5557: /* exit(1); */
5558: }
5559: /* if((imk=mkdir(optionfilefiname))<0){ */
5560: /* perror("mkdir"); */
5561: /* } */
5562:
5563: /*-------- arguments in the command line --------*/
5564:
5565: /* Log file */
5566: strcat(filelog, optionfilefiname);
5567: strcat(filelog,".log"); /* */
5568: if((ficlog=fopen(filelog,"w"))==NULL) {
5569: printf("Problem with logfile %s\n",filelog);
5570: goto end;
5571: }
5572: fprintf(ficlog,"Log filename:%s\n",filelog);
5573: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5574: fprintf(ficlog,"\nEnter the parameter file name: \n");
5575: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5576: path=%s \n\
5577: optionfile=%s\n\
5578: optionfilext=%s\n\
1.156 brouard 5579: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5580:
5581: printf("Local time (at start):%s",strstart);
5582: fprintf(ficlog,"Local time (at start): %s",strstart);
5583: fflush(ficlog);
5584: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5585: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5586:
5587: /* */
5588: strcpy(fileres,"r");
5589: strcat(fileres, optionfilefiname);
5590: strcat(fileres,".txt"); /* Other files have txt extension */
5591:
5592: /*---------arguments file --------*/
5593:
5594: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5595: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5596: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5597: fflush(ficlog);
1.149 brouard 5598: /* goto end; */
5599: exit(70);
1.126 brouard 5600: }
5601:
5602:
5603:
5604: strcpy(filereso,"o");
5605: strcat(filereso,fileres);
5606: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5607: printf("Problem with Output resultfile: %s\n", filereso);
5608: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5609: fflush(ficlog);
5610: goto end;
5611: }
5612:
5613: /* Reads comments: lines beginning with '#' */
5614: numlinepar=0;
5615: while((c=getc(ficpar))=='#' && c!= EOF){
5616: ungetc(c,ficpar);
5617: fgets(line, MAXLINE, ficpar);
5618: numlinepar++;
1.141 brouard 5619: fputs(line,stdout);
1.126 brouard 5620: fputs(line,ficparo);
5621: fputs(line,ficlog);
5622: }
5623: ungetc(c,ficpar);
5624:
5625: 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);
5626: numlinepar++;
5627: 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);
5628: 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);
5629: 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);
5630: fflush(ficlog);
5631: while((c=getc(ficpar))=='#' && c!= EOF){
5632: ungetc(c,ficpar);
5633: fgets(line, MAXLINE, ficpar);
5634: numlinepar++;
1.141 brouard 5635: fputs(line, stdout);
5636: //puts(line);
1.126 brouard 5637: fputs(line,ficparo);
5638: fputs(line,ficlog);
5639: }
5640: ungetc(c,ficpar);
5641:
5642:
1.145 brouard 5643: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5644: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5645: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5646: v1+v2*age+v2*v3 makes cptcovn = 3
5647: */
5648: if (strlen(model)>1)
1.145 brouard 5649: 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*/
5650: else
5651: ncovmodel=2;
1.126 brouard 5652: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5653: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5654: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5655: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5656: 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);
5657: 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);
5658: fflush(stdout);
5659: fclose (ficlog);
5660: goto end;
5661: }
1.126 brouard 5662: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5663: delti=delti3[1][1];
5664: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5665: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5666: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5667: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5668: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5669: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5670: fclose (ficparo);
5671: fclose (ficlog);
5672: goto end;
5673: exit(0);
5674: }
5675: else if(mle==-3) {
5676: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5677: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5678: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5679: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5680: matcov=matrix(1,npar,1,npar);
5681: }
5682: else{
1.145 brouard 5683: /* Read guessed parameters */
1.126 brouard 5684: /* Reads comments: lines beginning with '#' */
5685: while((c=getc(ficpar))=='#' && c!= EOF){
5686: ungetc(c,ficpar);
5687: fgets(line, MAXLINE, ficpar);
5688: numlinepar++;
1.141 brouard 5689: fputs(line,stdout);
1.126 brouard 5690: fputs(line,ficparo);
5691: fputs(line,ficlog);
5692: }
5693: ungetc(c,ficpar);
5694:
5695: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5696: for(i=1; i <=nlstate; i++){
5697: j=0;
5698: for(jj=1; jj <=nlstate+ndeath; jj++){
5699: if(jj==i) continue;
5700: j++;
5701: fscanf(ficpar,"%1d%1d",&i1,&j1);
5702: if ((i1 != i) && (j1 != j)){
5703: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5704: It might be a problem of design; if ncovcol and the model are correct\n \
5705: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5706: exit(1);
5707: }
5708: fprintf(ficparo,"%1d%1d",i1,j1);
5709: if(mle==1)
5710: printf("%1d%1d",i,j);
5711: fprintf(ficlog,"%1d%1d",i,j);
5712: for(k=1; k<=ncovmodel;k++){
5713: fscanf(ficpar," %lf",¶m[i][j][k]);
5714: if(mle==1){
5715: printf(" %lf",param[i][j][k]);
5716: fprintf(ficlog," %lf",param[i][j][k]);
5717: }
5718: else
5719: fprintf(ficlog," %lf",param[i][j][k]);
5720: fprintf(ficparo," %lf",param[i][j][k]);
5721: }
5722: fscanf(ficpar,"\n");
5723: numlinepar++;
5724: if(mle==1)
5725: printf("\n");
5726: fprintf(ficlog,"\n");
5727: fprintf(ficparo,"\n");
5728: }
5729: }
5730: fflush(ficlog);
5731:
1.145 brouard 5732: /* Reads scales values */
1.126 brouard 5733: p=param[1][1];
5734:
5735: /* Reads comments: lines beginning with '#' */
5736: while((c=getc(ficpar))=='#' && c!= EOF){
5737: ungetc(c,ficpar);
5738: fgets(line, MAXLINE, ficpar);
5739: numlinepar++;
1.141 brouard 5740: fputs(line,stdout);
1.126 brouard 5741: fputs(line,ficparo);
5742: fputs(line,ficlog);
5743: }
5744: ungetc(c,ficpar);
5745:
5746: for(i=1; i <=nlstate; i++){
5747: for(j=1; j <=nlstate+ndeath-1; j++){
5748: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 ! brouard 5749: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5750: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5751: exit(1);
5752: }
5753: printf("%1d%1d",i,j);
5754: fprintf(ficparo,"%1d%1d",i1,j1);
5755: fprintf(ficlog,"%1d%1d",i1,j1);
5756: for(k=1; k<=ncovmodel;k++){
5757: fscanf(ficpar,"%le",&delti3[i][j][k]);
5758: printf(" %le",delti3[i][j][k]);
5759: fprintf(ficparo," %le",delti3[i][j][k]);
5760: fprintf(ficlog," %le",delti3[i][j][k]);
5761: }
5762: fscanf(ficpar,"\n");
5763: numlinepar++;
5764: printf("\n");
5765: fprintf(ficparo,"\n");
5766: fprintf(ficlog,"\n");
5767: }
5768: }
5769: fflush(ficlog);
5770:
1.145 brouard 5771: /* Reads covariance matrix */
1.126 brouard 5772: delti=delti3[1][1];
5773:
5774:
5775: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5776:
5777: /* Reads comments: lines beginning with '#' */
5778: while((c=getc(ficpar))=='#' && c!= EOF){
5779: ungetc(c,ficpar);
5780: fgets(line, MAXLINE, ficpar);
5781: numlinepar++;
1.141 brouard 5782: fputs(line,stdout);
1.126 brouard 5783: fputs(line,ficparo);
5784: fputs(line,ficlog);
5785: }
5786: ungetc(c,ficpar);
5787:
5788: matcov=matrix(1,npar,1,npar);
1.131 brouard 5789: for(i=1; i <=npar; i++)
5790: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5791:
1.126 brouard 5792: for(i=1; i <=npar; i++){
1.145 brouard 5793: fscanf(ficpar,"%s",str);
1.126 brouard 5794: if(mle==1)
5795: printf("%s",str);
5796: fprintf(ficlog,"%s",str);
5797: fprintf(ficparo,"%s",str);
5798: for(j=1; j <=i; j++){
5799: fscanf(ficpar," %le",&matcov[i][j]);
5800: if(mle==1){
5801: printf(" %.5le",matcov[i][j]);
5802: }
5803: fprintf(ficlog," %.5le",matcov[i][j]);
5804: fprintf(ficparo," %.5le",matcov[i][j]);
5805: }
5806: fscanf(ficpar,"\n");
5807: numlinepar++;
5808: if(mle==1)
5809: printf("\n");
5810: fprintf(ficlog,"\n");
5811: fprintf(ficparo,"\n");
5812: }
5813: for(i=1; i <=npar; i++)
5814: for(j=i+1;j<=npar;j++)
5815: matcov[i][j]=matcov[j][i];
5816:
5817: if(mle==1)
5818: printf("\n");
5819: fprintf(ficlog,"\n");
5820:
5821: fflush(ficlog);
5822:
5823: /*-------- Rewriting parameter file ----------*/
5824: strcpy(rfileres,"r"); /* "Rparameterfile */
5825: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5826: strcat(rfileres,"."); /* */
5827: strcat(rfileres,optionfilext); /* Other files have txt extension */
5828: if((ficres =fopen(rfileres,"w"))==NULL) {
5829: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5830: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5831: }
5832: fprintf(ficres,"#%s\n",version);
5833: } /* End of mle != -3 */
5834:
5835:
5836: n= lastobs;
5837: num=lvector(1,n);
5838: moisnais=vector(1,n);
5839: annais=vector(1,n);
5840: moisdc=vector(1,n);
5841: andc=vector(1,n);
5842: agedc=vector(1,n);
5843: cod=ivector(1,n);
5844: weight=vector(1,n);
5845: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5846: mint=matrix(1,maxwav,1,n);
5847: anint=matrix(1,maxwav,1,n);
1.131 brouard 5848: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5849: tab=ivector(1,NCOVMAX);
1.144 brouard 5850: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5851:
1.136 brouard 5852: /* Reads data from file datafile */
5853: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5854: goto end;
5855:
5856: /* Calculation of the number of parameters from char model */
1.137 brouard 5857: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5858: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5859: k=3 V4 Tvar[k=3]= 4 (from V4)
5860: k=2 V1 Tvar[k=2]= 1 (from V1)
5861: k=1 Tvar[1]=2 (from V2)
5862: */
5863: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5864: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5865: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5866: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5867: */
5868: /* For model-covariate k tells which data-covariate to use but
5869: because this model-covariate is a construction we invent a new column
5870: ncovcol + k1
5871: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5872: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5873: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5874: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5875: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5876: */
1.145 brouard 5877: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5878: 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 5879: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5880: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5881: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5882: 4 covariates (3 plus signs)
5883: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5884: */
1.136 brouard 5885:
5886: if(decodemodel(model, lastobs) == 1)
5887: goto end;
5888:
1.137 brouard 5889: if((double)(lastobs-imx)/(double)imx > 1.10){
5890: nbwarn++;
5891: 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);
5892: 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);
5893: }
1.136 brouard 5894: /* if(mle==1){*/
1.137 brouard 5895: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5896: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5897: }
5898:
5899: /*-calculation of age at interview from date of interview and age at death -*/
5900: agev=matrix(1,maxwav,1,imx);
5901:
5902: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5903: goto end;
5904:
1.126 brouard 5905:
1.136 brouard 5906: agegomp=(int)agemin;
5907: free_vector(moisnais,1,n);
5908: free_vector(annais,1,n);
1.126 brouard 5909: /* free_matrix(mint,1,maxwav,1,n);
5910: free_matrix(anint,1,maxwav,1,n);*/
5911: free_vector(moisdc,1,n);
5912: free_vector(andc,1,n);
1.145 brouard 5913: /* */
5914:
1.126 brouard 5915: wav=ivector(1,imx);
5916: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5917: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5918: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5919:
5920: /* Concatenates waves */
5921: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5922: /* */
5923:
1.126 brouard 5924: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5925:
5926: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5927: ncodemax[1]=1;
1.145 brouard 5928: Ndum =ivector(-1,NCOVMAX);
5929: if (ncovmodel > 2)
5930: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5931:
5932: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5933: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5934: h=0;
5935:
5936:
5937: /*if (cptcovn > 0) */
1.126 brouard 5938:
1.145 brouard 5939:
1.126 brouard 5940: m=pow(2,cptcoveff);
5941:
1.131 brouard 5942: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5943: 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 */
5944: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5945: 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 5946: h++;
1.141 brouard 5947: if (h>m)
1.136 brouard 5948: h=1;
1.144 brouard 5949: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5950: * h 1 2 3 4
5951: *______________________________
5952: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5953: * 2 2 1 1 1
5954: * 3 i=2 1 2 1 1
5955: * 4 2 2 1 1
5956: * 5 i=3 1 i=2 1 2 1
5957: * 6 2 1 2 1
5958: * 7 i=4 1 2 2 1
5959: * 8 2 2 2 1
5960: * 9 i=5 1 i=3 1 i=2 1 1
5961: * 10 2 1 1 1
5962: * 11 i=6 1 2 1 1
5963: * 12 2 2 1 1
5964: * 13 i=7 1 i=4 1 2 1
5965: * 14 2 1 2 1
5966: * 15 i=8 1 2 2 1
5967: * 16 2 2 2 1
5968: */
1.141 brouard 5969: codtab[h][k]=j;
1.145 brouard 5970: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5971: 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 5972: }
5973: }
5974: }
5975: }
5976: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5977: codtab[1][2]=1;codtab[2][2]=2; */
5978: /* for(i=1; i <=m ;i++){
5979: for(k=1; k <=cptcovn; k++){
1.131 brouard 5980: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5981: }
5982: printf("\n");
5983: }
5984: scanf("%d",i);*/
1.145 brouard 5985:
5986: free_ivector(Ndum,-1,NCOVMAX);
5987:
5988:
1.126 brouard 5989:
5990: /*------------ gnuplot -------------*/
5991: strcpy(optionfilegnuplot,optionfilefiname);
5992: if(mle==-3)
5993: strcat(optionfilegnuplot,"-mort");
5994: strcat(optionfilegnuplot,".gp");
5995:
5996: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5997: printf("Problem with file %s",optionfilegnuplot);
5998: }
5999: else{
6000: fprintf(ficgp,"\n# %s\n", version);
6001: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6002: //fprintf(ficgp,"set missing 'NaNq'\n");
6003: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6004: }
6005: /* fclose(ficgp);*/
6006: /*--------- index.htm --------*/
6007:
6008: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6009: if(mle==-3)
6010: strcat(optionfilehtm,"-mort");
6011: strcat(optionfilehtm,".htm");
6012: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6013: printf("Problem with %s \n",optionfilehtm);
6014: exit(0);
1.126 brouard 6015: }
6016:
6017: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6018: strcat(optionfilehtmcov,"-cov.htm");
6019: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6020: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6021: }
6022: else{
6023: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6024: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6025: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6026: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6027: }
6028:
6029: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6030: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6031: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6032: \n\
6033: <hr size=\"2\" color=\"#EC5E5E\">\
6034: <ul><li><h4>Parameter files</h4>\n\
6035: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6036: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6037: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6038: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6039: - Date and time at start: %s</ul>\n",\
6040: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6041: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6042: fileres,fileres,\
6043: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6044: fflush(fichtm);
6045:
6046: strcpy(pathr,path);
6047: strcat(pathr,optionfilefiname);
6048: chdir(optionfilefiname); /* Move to directory named optionfile */
6049:
6050: /* Calculates basic frequencies. Computes observed prevalence at single age
6051: and prints on file fileres'p'. */
6052: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6053:
6054: fprintf(fichtm,"\n");
6055: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6056: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6057: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6058: imx,agemin,agemax,jmin,jmax,jmean);
6059: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6060: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6061: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6062: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6063: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6064:
6065:
6066: /* For Powell, parameters are in a vector p[] starting at p[1]
6067: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6068: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6069:
6070: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6071:
6072: if (mle==-3){
1.136 brouard 6073: ximort=matrix(1,NDIM,1,NDIM);
6074: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6075: cens=ivector(1,n);
6076: ageexmed=vector(1,n);
6077: agecens=vector(1,n);
6078: dcwave=ivector(1,n);
6079:
6080: for (i=1; i<=imx; i++){
6081: dcwave[i]=-1;
6082: for (m=firstpass; m<=lastpass; m++)
6083: if (s[m][i]>nlstate) {
6084: dcwave[i]=m;
6085: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6086: break;
6087: }
6088: }
6089:
6090: for (i=1; i<=imx; i++) {
6091: if (wav[i]>0){
6092: ageexmed[i]=agev[mw[1][i]][i];
6093: j=wav[i];
6094: agecens[i]=1.;
6095:
6096: if (ageexmed[i]> 1 && wav[i] > 0){
6097: agecens[i]=agev[mw[j][i]][i];
6098: cens[i]= 1;
6099: }else if (ageexmed[i]< 1)
6100: cens[i]= -1;
6101: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6102: cens[i]=0 ;
6103: }
6104: else cens[i]=-1;
6105: }
6106:
6107: for (i=1;i<=NDIM;i++) {
6108: for (j=1;j<=NDIM;j++)
6109: ximort[i][j]=(i == j ? 1.0 : 0.0);
6110: }
6111:
1.145 brouard 6112: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6113: /*printf("%lf %lf", p[1], p[2]);*/
6114:
6115:
1.136 brouard 6116: #ifdef GSL
6117: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6118: #else
1.126 brouard 6119: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6120: #endif
1.126 brouard 6121: strcpy(filerespow,"pow-mort");
6122: strcat(filerespow,fileres);
6123: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6124: printf("Problem with resultfile: %s\n", filerespow);
6125: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6126: }
1.136 brouard 6127: #ifdef GSL
6128: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6129: #else
1.126 brouard 6130: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6131: #endif
1.126 brouard 6132: /* for (i=1;i<=nlstate;i++)
6133: for(j=1;j<=nlstate+ndeath;j++)
6134: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6135: */
6136: fprintf(ficrespow,"\n");
1.136 brouard 6137: #ifdef GSL
6138: /* gsl starts here */
6139: T = gsl_multimin_fminimizer_nmsimplex;
6140: gsl_multimin_fminimizer *sfm = NULL;
6141: gsl_vector *ss, *x;
6142: gsl_multimin_function minex_func;
6143:
6144: /* Initial vertex size vector */
6145: ss = gsl_vector_alloc (NDIM);
6146:
6147: if (ss == NULL){
6148: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6149: }
6150: /* Set all step sizes to 1 */
6151: gsl_vector_set_all (ss, 0.001);
6152:
6153: /* Starting point */
1.126 brouard 6154:
1.136 brouard 6155: x = gsl_vector_alloc (NDIM);
6156:
6157: if (x == NULL){
6158: gsl_vector_free(ss);
6159: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6160: }
6161:
6162: /* Initialize method and iterate */
6163: /* p[1]=0.0268; p[NDIM]=0.083; */
6164: /* gsl_vector_set(x, 0, 0.0268); */
6165: /* gsl_vector_set(x, 1, 0.083); */
6166: gsl_vector_set(x, 0, p[1]);
6167: gsl_vector_set(x, 1, p[2]);
6168:
6169: minex_func.f = &gompertz_f;
6170: minex_func.n = NDIM;
6171: minex_func.params = (void *)&p; /* ??? */
6172:
6173: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6174: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6175:
6176: printf("Iterations beginning .....\n\n");
6177: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6178:
6179: iteri=0;
6180: while (rval == GSL_CONTINUE){
6181: iteri++;
6182: status = gsl_multimin_fminimizer_iterate(sfm);
6183:
6184: if (status) printf("error: %s\n", gsl_strerror (status));
6185: fflush(0);
6186:
6187: if (status)
6188: break;
6189:
6190: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6191: ssval = gsl_multimin_fminimizer_size (sfm);
6192:
6193: if (rval == GSL_SUCCESS)
6194: printf ("converged to a local maximum at\n");
6195:
6196: printf("%5d ", iteri);
6197: for (it = 0; it < NDIM; it++){
6198: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6199: }
6200: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6201: }
6202:
6203: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6204:
6205: gsl_vector_free(x); /* initial values */
6206: gsl_vector_free(ss); /* inital step size */
6207: for (it=0; it<NDIM; it++){
6208: p[it+1]=gsl_vector_get(sfm->x,it);
6209: fprintf(ficrespow," %.12lf", p[it]);
6210: }
6211: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6212: #endif
6213: #ifdef POWELL
6214: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6215: #endif
1.126 brouard 6216: fclose(ficrespow);
6217:
6218: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6219:
6220: for(i=1; i <=NDIM; i++)
6221: for(j=i+1;j<=NDIM;j++)
6222: matcov[i][j]=matcov[j][i];
6223:
6224: printf("\nCovariance matrix\n ");
6225: for(i=1; i <=NDIM; i++) {
6226: for(j=1;j<=NDIM;j++){
6227: printf("%f ",matcov[i][j]);
6228: }
6229: printf("\n ");
6230: }
6231:
6232: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6233: for (i=1;i<=NDIM;i++)
6234: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6235:
6236: lsurv=vector(1,AGESUP);
6237: lpop=vector(1,AGESUP);
6238: tpop=vector(1,AGESUP);
6239: lsurv[agegomp]=100000;
6240:
6241: for (k=agegomp;k<=AGESUP;k++) {
6242: agemortsup=k;
6243: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6244: }
6245:
6246: for (k=agegomp;k<agemortsup;k++)
6247: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6248:
6249: for (k=agegomp;k<agemortsup;k++){
6250: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6251: sumlpop=sumlpop+lpop[k];
6252: }
6253:
6254: tpop[agegomp]=sumlpop;
6255: for (k=agegomp;k<(agemortsup-3);k++){
6256: /* tpop[k+1]=2;*/
6257: tpop[k+1]=tpop[k]-lpop[k];
6258: }
6259:
6260:
6261: printf("\nAge lx qx dx Lx Tx e(x)\n");
6262: for (k=agegomp;k<(agemortsup-2);k++)
6263: 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]);
6264:
6265:
6266: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6267: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6268:
6269: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6270: stepm, weightopt,\
6271: model,imx,p,matcov,agemortsup);
6272:
6273: free_vector(lsurv,1,AGESUP);
6274: free_vector(lpop,1,AGESUP);
6275: free_vector(tpop,1,AGESUP);
1.136 brouard 6276: #ifdef GSL
6277: free_ivector(cens,1,n);
6278: free_vector(agecens,1,n);
6279: free_ivector(dcwave,1,n);
6280: free_matrix(ximort,1,NDIM,1,NDIM);
6281: #endif
1.126 brouard 6282: } /* Endof if mle==-3 */
6283:
6284: else{ /* For mle >=1 */
1.132 brouard 6285: globpr=0;/* debug */
6286: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6287: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6288: for (k=1; k<=npar;k++)
6289: printf(" %d %8.5f",k,p[k]);
6290: printf("\n");
6291: globpr=1; /* to print the contributions */
6292: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6293: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6294: for (k=1; k<=npar;k++)
6295: printf(" %d %8.5f",k,p[k]);
6296: printf("\n");
6297: if(mle>=1){ /* Could be 1 or 2 */
6298: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6299: }
6300:
6301: /*--------- results files --------------*/
6302: 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);
6303:
6304:
6305: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6306: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6307: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6308: for(i=1,jk=1; i <=nlstate; i++){
6309: for(k=1; k <=(nlstate+ndeath); k++){
6310: if (k != i) {
6311: printf("%d%d ",i,k);
6312: fprintf(ficlog,"%d%d ",i,k);
6313: fprintf(ficres,"%1d%1d ",i,k);
6314: for(j=1; j <=ncovmodel; j++){
6315: printf("%lf ",p[jk]);
6316: fprintf(ficlog,"%lf ",p[jk]);
6317: fprintf(ficres,"%lf ",p[jk]);
6318: jk++;
6319: }
6320: printf("\n");
6321: fprintf(ficlog,"\n");
6322: fprintf(ficres,"\n");
6323: }
6324: }
6325: }
6326: if(mle!=0){
6327: /* Computing hessian and covariance matrix */
6328: ftolhess=ftol; /* Usually correct */
6329: hesscov(matcov, p, npar, delti, ftolhess, func);
6330: }
6331: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6332: printf("# Scales (for hessian or gradient estimation)\n");
6333: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6334: for(i=1,jk=1; i <=nlstate; i++){
6335: for(j=1; j <=nlstate+ndeath; j++){
6336: if (j!=i) {
6337: fprintf(ficres,"%1d%1d",i,j);
6338: printf("%1d%1d",i,j);
6339: fprintf(ficlog,"%1d%1d",i,j);
6340: for(k=1; k<=ncovmodel;k++){
6341: printf(" %.5e",delti[jk]);
6342: fprintf(ficlog," %.5e",delti[jk]);
6343: fprintf(ficres," %.5e",delti[jk]);
6344: jk++;
6345: }
6346: printf("\n");
6347: fprintf(ficlog,"\n");
6348: fprintf(ficres,"\n");
6349: }
6350: }
6351: }
6352:
6353: 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");
6354: if(mle>=1)
6355: 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");
6356: 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");
6357: /* # 121 Var(a12)\n\ */
6358: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6359: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6360: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6361: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6362: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6363: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6364: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6365:
6366:
6367: /* Just to have a covariance matrix which will be more understandable
6368: even is we still don't want to manage dictionary of variables
6369: */
6370: for(itimes=1;itimes<=2;itimes++){
6371: jj=0;
6372: for(i=1; i <=nlstate; i++){
6373: for(j=1; j <=nlstate+ndeath; j++){
6374: if(j==i) continue;
6375: for(k=1; k<=ncovmodel;k++){
6376: jj++;
6377: ca[0]= k+'a'-1;ca[1]='\0';
6378: if(itimes==1){
6379: if(mle>=1)
6380: printf("#%1d%1d%d",i,j,k);
6381: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6382: fprintf(ficres,"#%1d%1d%d",i,j,k);
6383: }else{
6384: if(mle>=1)
6385: printf("%1d%1d%d",i,j,k);
6386: fprintf(ficlog,"%1d%1d%d",i,j,k);
6387: fprintf(ficres,"%1d%1d%d",i,j,k);
6388: }
6389: ll=0;
6390: for(li=1;li <=nlstate; li++){
6391: for(lj=1;lj <=nlstate+ndeath; lj++){
6392: if(lj==li) continue;
6393: for(lk=1;lk<=ncovmodel;lk++){
6394: ll++;
6395: if(ll<=jj){
6396: cb[0]= lk +'a'-1;cb[1]='\0';
6397: if(ll<jj){
6398: if(itimes==1){
6399: if(mle>=1)
6400: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6401: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6402: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6403: }else{
6404: if(mle>=1)
6405: printf(" %.5e",matcov[jj][ll]);
6406: fprintf(ficlog," %.5e",matcov[jj][ll]);
6407: fprintf(ficres," %.5e",matcov[jj][ll]);
6408: }
6409: }else{
6410: if(itimes==1){
6411: if(mle>=1)
6412: printf(" Var(%s%1d%1d)",ca,i,j);
6413: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6414: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6415: }else{
6416: if(mle>=1)
6417: printf(" %.5e",matcov[jj][ll]);
6418: fprintf(ficlog," %.5e",matcov[jj][ll]);
6419: fprintf(ficres," %.5e",matcov[jj][ll]);
6420: }
6421: }
6422: }
6423: } /* end lk */
6424: } /* end lj */
6425: } /* end li */
6426: if(mle>=1)
6427: printf("\n");
6428: fprintf(ficlog,"\n");
6429: fprintf(ficres,"\n");
6430: numlinepar++;
6431: } /* end k*/
6432: } /*end j */
6433: } /* end i */
6434: } /* end itimes */
6435:
6436: fflush(ficlog);
6437: fflush(ficres);
6438:
6439: while((c=getc(ficpar))=='#' && c!= EOF){
6440: ungetc(c,ficpar);
6441: fgets(line, MAXLINE, ficpar);
1.141 brouard 6442: fputs(line,stdout);
1.126 brouard 6443: fputs(line,ficparo);
6444: }
6445: ungetc(c,ficpar);
6446:
6447: estepm=0;
6448: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6449: if (estepm==0 || estepm < stepm) estepm=stepm;
6450: if (fage <= 2) {
6451: bage = ageminpar;
6452: fage = agemaxpar;
6453: }
6454:
6455: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6456: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6457: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6458:
6459: while((c=getc(ficpar))=='#' && c!= EOF){
6460: ungetc(c,ficpar);
6461: fgets(line, MAXLINE, ficpar);
1.141 brouard 6462: fputs(line,stdout);
1.126 brouard 6463: fputs(line,ficparo);
6464: }
6465: ungetc(c,ficpar);
6466:
6467: 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);
6468: 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);
6469: 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);
6470: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6471: 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);
6472:
6473: while((c=getc(ficpar))=='#' && c!= EOF){
6474: ungetc(c,ficpar);
6475: fgets(line, MAXLINE, ficpar);
1.141 brouard 6476: fputs(line,stdout);
1.126 brouard 6477: fputs(line,ficparo);
6478: }
6479: ungetc(c,ficpar);
6480:
6481:
6482: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6483: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6484:
6485: fscanf(ficpar,"pop_based=%d\n",&popbased);
6486: fprintf(ficparo,"pop_based=%d\n",popbased);
6487: fprintf(ficres,"pop_based=%d\n",popbased);
6488:
6489: while((c=getc(ficpar))=='#' && c!= EOF){
6490: ungetc(c,ficpar);
6491: fgets(line, MAXLINE, ficpar);
1.141 brouard 6492: fputs(line,stdout);
1.126 brouard 6493: fputs(line,ficparo);
6494: }
6495: ungetc(c,ficpar);
6496:
6497: 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);
6498: 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);
6499: 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);
6500: 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);
6501: 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);
6502: /* day and month of proj2 are not used but only year anproj2.*/
6503:
6504:
6505:
1.145 brouard 6506: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6507: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6508:
6509: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6510: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6511:
6512: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6513: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6514: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6515:
6516: /*------------ free_vector -------------*/
6517: /* chdir(path); */
6518:
6519: free_ivector(wav,1,imx);
6520: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6521: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6522: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6523: free_lvector(num,1,n);
6524: free_vector(agedc,1,n);
6525: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6526: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6527: fclose(ficparo);
6528: fclose(ficres);
6529:
6530:
6531: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6532: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6533: fclose(ficrespl);
6534:
1.145 brouard 6535: #ifdef FREEEXIT2
6536: #include "freeexit2.h"
6537: #endif
6538:
1.126 brouard 6539: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6540: #include "hpijx.h"
6541: fclose(ficrespij);
1.126 brouard 6542:
1.145 brouard 6543: /*-------------- Variance of one-step probabilities---*/
6544: k=1;
1.126 brouard 6545: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6546:
6547:
6548: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6549: for(i=1;i<=AGESUP;i++)
6550: for(j=1;j<=NCOVMAX;j++)
6551: for(k=1;k<=NCOVMAX;k++)
6552: probs[i][j][k]=0.;
6553:
6554: /*---------- Forecasting ------------------*/
6555: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6556: if(prevfcast==1){
6557: /* if(stepm ==1){*/
6558: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6559: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6560: /* } */
6561: /* else{ */
6562: /* erreur=108; */
6563: /* 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); */
6564: /* 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); */
6565: /* } */
6566: }
6567:
6568:
1.127 brouard 6569: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6570:
6571: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6572: /* 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",\
6573: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6574: */
1.126 brouard 6575:
1.127 brouard 6576: if (mobilav!=0) {
6577: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6578: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6579: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6580: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6581: }
1.126 brouard 6582: }
6583:
6584:
1.127 brouard 6585: /*---------- Health expectancies, no variances ------------*/
6586:
1.126 brouard 6587: strcpy(filerese,"e");
6588: strcat(filerese,fileres);
6589: if((ficreseij=fopen(filerese,"w"))==NULL) {
6590: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6591: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6592: }
6593: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6594: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6595: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6596: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6597:
6598: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6599: fprintf(ficreseij,"\n#****** ");
6600: for(j=1;j<=cptcoveff;j++) {
6601: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6602: }
6603: fprintf(ficreseij,"******\n");
6604:
6605: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6606: oldm=oldms;savm=savms;
6607: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6608:
6609: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6610: /*}*/
1.127 brouard 6611: }
6612: fclose(ficreseij);
6613:
6614:
6615: /*---------- Health expectancies and variances ------------*/
6616:
6617:
6618: strcpy(filerest,"t");
6619: strcat(filerest,fileres);
6620: if((ficrest=fopen(filerest,"w"))==NULL) {
6621: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6622: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6623: }
6624: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6625: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6626:
1.126 brouard 6627:
6628: strcpy(fileresstde,"stde");
6629: strcat(fileresstde,fileres);
6630: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6631: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6632: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6633: }
6634: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6635: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6636:
6637: strcpy(filerescve,"cve");
6638: strcat(filerescve,fileres);
6639: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6640: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6641: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6642: }
6643: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6644: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6645:
6646: strcpy(fileresv,"v");
6647: strcat(fileresv,fileres);
6648: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6649: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6650: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6651: }
6652: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6653: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6654:
1.145 brouard 6655: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6656: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6657:
6658: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6659: fprintf(ficrest,"\n#****** ");
1.126 brouard 6660: for(j=1;j<=cptcoveff;j++)
6661: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6662: fprintf(ficrest,"******\n");
6663:
6664: fprintf(ficresstdeij,"\n#****** ");
6665: fprintf(ficrescveij,"\n#****** ");
6666: for(j=1;j<=cptcoveff;j++) {
6667: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6668: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6669: }
6670: fprintf(ficresstdeij,"******\n");
6671: fprintf(ficrescveij,"******\n");
6672:
6673: fprintf(ficresvij,"\n#****** ");
6674: for(j=1;j<=cptcoveff;j++)
6675: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6676: fprintf(ficresvij,"******\n");
6677:
6678: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6679: oldm=oldms;savm=savms;
1.127 brouard 6680: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6681: /*
6682: */
6683: /* goto endfree; */
1.126 brouard 6684:
6685: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6686: pstamp(ficrest);
1.145 brouard 6687:
6688:
1.128 brouard 6689: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6690: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6691: cptcod= 0; /* To be deleted */
6692: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145 brouard 6693: 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 6694: if(vpopbased==1)
6695: 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);
6696: else
6697: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6698: fprintf(ficrest,"# Age e.. (std) ");
6699: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6700: fprintf(ficrest,"\n");
1.126 brouard 6701:
1.128 brouard 6702: epj=vector(1,nlstate+1);
6703: for(age=bage; age <=fage ;age++){
6704: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6705: if (vpopbased==1) {
6706: if(mobilav ==0){
6707: for(i=1; i<=nlstate;i++)
6708: prlim[i][i]=probs[(int)age][i][k];
6709: }else{ /* mobilav */
6710: for(i=1; i<=nlstate;i++)
6711: prlim[i][i]=mobaverage[(int)age][i][k];
6712: }
1.126 brouard 6713: }
6714:
1.128 brouard 6715: fprintf(ficrest," %4.0f",age);
6716: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6717: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6718: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6719: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6720: }
6721: epj[nlstate+1] +=epj[j];
1.126 brouard 6722: }
6723:
1.128 brouard 6724: for(i=1, vepp=0.;i <=nlstate;i++)
6725: for(j=1;j <=nlstate;j++)
6726: vepp += vareij[i][j][(int)age];
6727: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6728: for(j=1;j <=nlstate;j++){
6729: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6730: }
6731: fprintf(ficrest,"\n");
1.126 brouard 6732: }
6733: }
6734: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6735: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6736: free_vector(epj,1,nlstate+1);
1.145 brouard 6737: /*}*/
1.126 brouard 6738: }
6739: free_vector(weight,1,n);
1.145 brouard 6740: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6741: free_imatrix(s,1,maxwav+1,1,n);
6742: free_matrix(anint,1,maxwav,1,n);
6743: free_matrix(mint,1,maxwav,1,n);
6744: free_ivector(cod,1,n);
6745: free_ivector(tab,1,NCOVMAX);
6746: fclose(ficresstdeij);
6747: fclose(ficrescveij);
6748: fclose(ficresvij);
6749: fclose(ficrest);
6750: fclose(ficpar);
6751:
6752: /*------- Variance of period (stable) prevalence------*/
6753:
6754: strcpy(fileresvpl,"vpl");
6755: strcat(fileresvpl,fileres);
6756: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6757: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6758: exit(0);
6759: }
6760: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6761:
1.145 brouard 6762: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6763: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6764:
6765: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6766: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6767: for(j=1;j<=cptcoveff;j++)
6768: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6769: fprintf(ficresvpl,"******\n");
6770:
6771: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6772: oldm=oldms;savm=savms;
6773: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6774: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6775: /*}*/
1.126 brouard 6776: }
6777:
6778: fclose(ficresvpl);
6779:
6780: /*---------- End : free ----------------*/
6781: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6782: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6783: } /* mle==-3 arrives here for freeing */
1.164 ! brouard 6784: /* endfree:*/
1.141 brouard 6785: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6786: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6787: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6788: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6789: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6790: free_matrix(covar,0,NCOVMAX,1,n);
6791: free_matrix(matcov,1,npar,1,npar);
6792: /*free_vector(delti,1,npar);*/
6793: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6794: free_matrix(agev,1,maxwav,1,imx);
6795: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6796:
1.145 brouard 6797: free_ivector(ncodemax,1,NCOVMAX);
6798: free_ivector(Tvar,1,NCOVMAX);
6799: free_ivector(Tprod,1,NCOVMAX);
6800: free_ivector(Tvaraff,1,NCOVMAX);
6801: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6802:
6803: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6804: free_imatrix(codtab,1,100,1,10);
6805: fflush(fichtm);
6806: fflush(ficgp);
6807:
6808:
6809: if((nberr >0) || (nbwarn>0)){
6810: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6811: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6812: }else{
6813: printf("End of Imach\n");
6814: fprintf(ficlog,"End of Imach\n");
6815: }
6816: printf("See log file on %s\n",filelog);
6817: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6818: /*(void) gettimeofday(&end_time,&tzp);*/
6819: rend_time = time(NULL);
6820: end_time = *localtime(&rend_time);
6821: /* tml = *localtime(&end_time.tm_sec); */
6822: strcpy(strtend,asctime(&end_time));
1.126 brouard 6823: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6824: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6825: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6826:
1.157 brouard 6827: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6828: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6829: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6830: /* printf("Total time was %d uSec.\n", total_usecs);*/
6831: /* if(fileappend(fichtm,optionfilehtm)){ */
6832: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6833: fclose(fichtm);
6834: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6835: fclose(fichtmcov);
6836: fclose(ficgp);
6837: fclose(ficlog);
6838: /*------ End -----------*/
6839:
6840:
6841: printf("Before Current directory %s!\n",pathcd);
6842: if(chdir(pathcd) != 0)
6843: printf("Can't move to directory %s!\n",path);
6844: if(getcwd(pathcd,MAXLINE) > 0)
6845: printf("Current directory %s!\n",pathcd);
6846: /*strcat(plotcmd,CHARSEPARATOR);*/
6847: sprintf(plotcmd,"gnuplot");
1.157 brouard 6848: #ifdef _WIN32
1.126 brouard 6849: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6850: #endif
6851: if(!stat(plotcmd,&info)){
1.158 brouard 6852: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6853: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6854: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6855: }else
6856: strcpy(pplotcmd,plotcmd);
1.157 brouard 6857: #ifdef __unix
1.126 brouard 6858: strcpy(plotcmd,GNUPLOTPROGRAM);
6859: if(!stat(plotcmd,&info)){
1.158 brouard 6860: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6861: }else
6862: strcpy(pplotcmd,plotcmd);
6863: #endif
6864: }else
6865: strcpy(pplotcmd,plotcmd);
6866:
6867: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6868: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6869:
6870: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6871: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6872: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6873: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6874: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6875: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6876: }
1.158 brouard 6877: printf(" Successful, please wait...");
1.126 brouard 6878: while (z[0] != 'q') {
6879: /* chdir(path); */
1.154 brouard 6880: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6881: scanf("%s",z);
6882: /* if (z[0] == 'c') system("./imach"); */
6883: if (z[0] == 'e') {
1.158 brouard 6884: #ifdef __APPLE__
1.152 brouard 6885: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6886: #elif __linux
6887: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6888: #else
1.152 brouard 6889: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6890: #endif
6891: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6892: system(pplotcmd);
1.126 brouard 6893: }
6894: else if (z[0] == 'g') system(plotcmd);
6895: else if (z[0] == 'q') exit(0);
6896: }
6897: end:
6898: while (z[0] != 'q') {
6899: printf("\nType q for exiting: ");
6900: scanf("%s",z);
6901: }
6902: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>