Annotation of imach/src/imach.c, revision 1.182
1.182 ! brouard 1: /* $Id: imach.c,v 1.181 2015/02/11 23:22:24 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.182 ! brouard 4: Revision 1.181 2015/02/11 23:22:24 brouard
! 5: Summary: Comments on Powell added
! 6:
! 7: Author:
! 8:
1.181 brouard 9: Revision 1.180 2015/02/11 17:33:45 brouard
10: Summary: Finishing move from main to function (hpijx and prevalence_limit)
11:
1.180 brouard 12: Revision 1.179 2015/01/04 09:57:06 brouard
13: Summary: back to OS/X
14:
1.179 brouard 15: Revision 1.178 2015/01/04 09:35:48 brouard
16: *** empty log message ***
17:
1.178 brouard 18: Revision 1.177 2015/01/03 18:40:56 brouard
19: Summary: Still testing ilc32 on OSX
20:
1.177 brouard 21: Revision 1.176 2015/01/03 16:45:04 brouard
22: *** empty log message ***
23:
1.176 brouard 24: Revision 1.175 2015/01/03 16:33:42 brouard
25: *** empty log message ***
26:
1.175 brouard 27: Revision 1.174 2015/01/03 16:15:49 brouard
28: Summary: Still in cross-compilation
29:
1.174 brouard 30: Revision 1.173 2015/01/03 12:06:26 brouard
31: Summary: trying to detect cross-compilation
32:
1.173 brouard 33: Revision 1.172 2014/12/27 12:07:47 brouard
34: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
35:
1.172 brouard 36: Revision 1.171 2014/12/23 13:26:59 brouard
37: Summary: Back from Visual C
38:
39: Still problem with utsname.h on Windows
40:
1.171 brouard 41: Revision 1.170 2014/12/23 11:17:12 brouard
42: Summary: Cleaning some \%% back to %%
43:
44: The escape was mandatory for a specific compiler (which one?), but too many warnings.
45:
1.170 brouard 46: Revision 1.169 2014/12/22 23:08:31 brouard
47: Summary: 0.98p
48:
49: Outputs some informations on compiler used, OS etc. Testing on different platforms.
50:
1.169 brouard 51: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 52: Summary: update
1.169 brouard 53:
1.168 brouard 54: Revision 1.167 2014/12/22 13:50:56 brouard
55: Summary: Testing uname and compiler version and if compiled 32 or 64
56:
57: Testing on Linux 64
58:
1.167 brouard 59: Revision 1.166 2014/12/22 11:40:47 brouard
60: *** empty log message ***
61:
1.166 brouard 62: Revision 1.165 2014/12/16 11:20:36 brouard
63: Summary: After compiling on Visual C
64:
65: * imach.c (Module): Merging 1.61 to 1.162
66:
1.165 brouard 67: Revision 1.164 2014/12/16 10:52:11 brouard
68: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
69:
70: * imach.c (Module): Merging 1.61 to 1.162
71:
1.164 brouard 72: Revision 1.163 2014/12/16 10:30:11 brouard
73: * imach.c (Module): Merging 1.61 to 1.162
74:
1.163 brouard 75: Revision 1.162 2014/09/25 11:43:39 brouard
76: Summary: temporary backup 0.99!
77:
1.162 brouard 78: Revision 1.1 2014/09/16 11:06:58 brouard
79: Summary: With some code (wrong) for nlopt
80:
81: Author:
82:
83: Revision 1.161 2014/09/15 20:41:41 brouard
84: Summary: Problem with macro SQR on Intel compiler
85:
1.161 brouard 86: Revision 1.160 2014/09/02 09:24:05 brouard
87: *** empty log message ***
88:
1.160 brouard 89: Revision 1.159 2014/09/01 10:34:10 brouard
90: Summary: WIN32
91: Author: Brouard
92:
1.159 brouard 93: Revision 1.158 2014/08/27 17:11:51 brouard
94: *** empty log message ***
95:
1.158 brouard 96: Revision 1.157 2014/08/27 16:26:55 brouard
97: Summary: Preparing windows Visual studio version
98: Author: Brouard
99:
100: In order to compile on Visual studio, time.h is now correct and time_t
101: and tm struct should be used. difftime should be used but sometimes I
102: just make the differences in raw time format (time(&now).
103: Trying to suppress #ifdef LINUX
104: Add xdg-open for __linux in order to open default browser.
105:
1.157 brouard 106: Revision 1.156 2014/08/25 20:10:10 brouard
107: *** empty log message ***
108:
1.156 brouard 109: Revision 1.155 2014/08/25 18:32:34 brouard
110: Summary: New compile, minor changes
111: Author: Brouard
112:
1.155 brouard 113: Revision 1.154 2014/06/20 17:32:08 brouard
114: Summary: Outputs now all graphs of convergence to period prevalence
115:
1.154 brouard 116: Revision 1.153 2014/06/20 16:45:46 brouard
117: Summary: If 3 live state, convergence to period prevalence on same graph
118: Author: Brouard
119:
1.153 brouard 120: Revision 1.152 2014/06/18 17:54:09 brouard
121: Summary: open browser, use gnuplot on same dir than imach if not found in the path
122:
1.152 brouard 123: Revision 1.151 2014/06/18 16:43:30 brouard
124: *** empty log message ***
125:
1.151 brouard 126: Revision 1.150 2014/06/18 16:42:35 brouard
127: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
128: Author: brouard
129:
1.150 brouard 130: Revision 1.149 2014/06/18 15:51:14 brouard
131: Summary: Some fixes in parameter files errors
132: Author: Nicolas Brouard
133:
1.149 brouard 134: Revision 1.148 2014/06/17 17:38:48 brouard
135: Summary: Nothing new
136: Author: Brouard
137:
138: Just a new packaging for OS/X version 0.98nS
139:
1.148 brouard 140: Revision 1.147 2014/06/16 10:33:11 brouard
141: *** empty log message ***
142:
1.147 brouard 143: Revision 1.146 2014/06/16 10:20:28 brouard
144: Summary: Merge
145: Author: Brouard
146:
147: Merge, before building revised version.
148:
1.146 brouard 149: Revision 1.145 2014/06/10 21:23:15 brouard
150: Summary: Debugging with valgrind
151: Author: Nicolas Brouard
152:
153: Lot of changes in order to output the results with some covariates
154: After the Edimburgh REVES conference 2014, it seems mandatory to
155: improve the code.
156: No more memory valgrind error but a lot has to be done in order to
157: continue the work of splitting the code into subroutines.
158: Also, decodemodel has been improved. Tricode is still not
159: optimal. nbcode should be improved. Documentation has been added in
160: the source code.
161:
1.144 brouard 162: Revision 1.143 2014/01/26 09:45:38 brouard
163: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
164:
165: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
166: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
167:
1.143 brouard 168: Revision 1.142 2014/01/26 03:57:36 brouard
169: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
170:
171: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
172:
1.142 brouard 173: Revision 1.141 2014/01/26 02:42:01 brouard
174: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
175:
1.141 brouard 176: Revision 1.140 2011/09/02 10:37:54 brouard
177: Summary: times.h is ok with mingw32 now.
178:
1.140 brouard 179: Revision 1.139 2010/06/14 07:50:17 brouard
180: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
181: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
182:
1.139 brouard 183: Revision 1.138 2010/04/30 18:19:40 brouard
184: *** empty log message ***
185:
1.138 brouard 186: Revision 1.137 2010/04/29 18:11:38 brouard
187: (Module): Checking covariates for more complex models
188: than V1+V2. A lot of change to be done. Unstable.
189:
1.137 brouard 190: Revision 1.136 2010/04/26 20:30:53 brouard
191: (Module): merging some libgsl code. Fixing computation
192: of likelione (using inter/intrapolation if mle = 0) in order to
193: get same likelihood as if mle=1.
194: Some cleaning of code and comments added.
195:
1.136 brouard 196: Revision 1.135 2009/10/29 15:33:14 brouard
197: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
198:
1.135 brouard 199: Revision 1.134 2009/10/29 13:18:53 brouard
200: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
201:
1.134 brouard 202: Revision 1.133 2009/07/06 10:21:25 brouard
203: just nforces
204:
1.133 brouard 205: Revision 1.132 2009/07/06 08:22:05 brouard
206: Many tings
207:
1.132 brouard 208: Revision 1.131 2009/06/20 16:22:47 brouard
209: Some dimensions resccaled
210:
1.131 brouard 211: Revision 1.130 2009/05/26 06:44:34 brouard
212: (Module): Max Covariate is now set to 20 instead of 8. A
213: lot of cleaning with variables initialized to 0. Trying to make
214: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
215:
1.130 brouard 216: Revision 1.129 2007/08/31 13:49:27 lievre
217: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
218:
1.129 lievre 219: Revision 1.128 2006/06/30 13:02:05 brouard
220: (Module): Clarifications on computing e.j
221:
1.128 brouard 222: Revision 1.127 2006/04/28 18:11:50 brouard
223: (Module): Yes the sum of survivors was wrong since
224: imach-114 because nhstepm was no more computed in the age
225: loop. Now we define nhstepma in the age loop.
226: (Module): In order to speed up (in case of numerous covariates) we
227: compute health expectancies (without variances) in a first step
228: and then all the health expectancies with variances or standard
229: deviation (needs data from the Hessian matrices) which slows the
230: computation.
231: In the future we should be able to stop the program is only health
232: expectancies and graph are needed without standard deviations.
233:
1.127 brouard 234: Revision 1.126 2006/04/28 17:23:28 brouard
235: (Module): Yes the sum of survivors was wrong since
236: imach-114 because nhstepm was no more computed in the age
237: loop. Now we define nhstepma in the age loop.
238: Version 0.98h
239:
1.126 brouard 240: Revision 1.125 2006/04/04 15:20:31 lievre
241: Errors in calculation of health expectancies. Age was not initialized.
242: Forecasting file added.
243:
244: Revision 1.124 2006/03/22 17:13:53 lievre
245: Parameters are printed with %lf instead of %f (more numbers after the comma).
246: The log-likelihood is printed in the log file
247:
248: Revision 1.123 2006/03/20 10:52:43 brouard
249: * imach.c (Module): <title> changed, corresponds to .htm file
250: name. <head> headers where missing.
251:
252: * imach.c (Module): Weights can have a decimal point as for
253: English (a comma might work with a correct LC_NUMERIC environment,
254: otherwise the weight is truncated).
255: Modification of warning when the covariates values are not 0 or
256: 1.
257: Version 0.98g
258:
259: Revision 1.122 2006/03/20 09:45:41 brouard
260: (Module): Weights can have a decimal point as for
261: English (a comma might work with a correct LC_NUMERIC environment,
262: otherwise the weight is truncated).
263: Modification of warning when the covariates values are not 0 or
264: 1.
265: Version 0.98g
266:
267: Revision 1.121 2006/03/16 17:45:01 lievre
268: * imach.c (Module): Comments concerning covariates added
269:
270: * imach.c (Module): refinements in the computation of lli if
271: status=-2 in order to have more reliable computation if stepm is
272: not 1 month. Version 0.98f
273:
274: Revision 1.120 2006/03/16 15:10:38 lievre
275: (Module): refinements in the computation of lli if
276: status=-2 in order to have more reliable computation if stepm is
277: not 1 month. Version 0.98f
278:
279: Revision 1.119 2006/03/15 17:42:26 brouard
280: (Module): Bug if status = -2, the loglikelihood was
281: computed as likelihood omitting the logarithm. Version O.98e
282:
283: Revision 1.118 2006/03/14 18:20:07 brouard
284: (Module): varevsij Comments added explaining the second
285: table of variances if popbased=1 .
286: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
287: (Module): Function pstamp added
288: (Module): Version 0.98d
289:
290: Revision 1.117 2006/03/14 17:16:22 brouard
291: (Module): varevsij Comments added explaining the second
292: table of variances if popbased=1 .
293: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
294: (Module): Function pstamp added
295: (Module): Version 0.98d
296:
297: Revision 1.116 2006/03/06 10:29:27 brouard
298: (Module): Variance-covariance wrong links and
299: varian-covariance of ej. is needed (Saito).
300:
301: Revision 1.115 2006/02/27 12:17:45 brouard
302: (Module): One freematrix added in mlikeli! 0.98c
303:
304: Revision 1.114 2006/02/26 12:57:58 brouard
305: (Module): Some improvements in processing parameter
306: filename with strsep.
307:
308: Revision 1.113 2006/02/24 14:20:24 brouard
309: (Module): Memory leaks checks with valgrind and:
310: datafile was not closed, some imatrix were not freed and on matrix
311: allocation too.
312:
313: Revision 1.112 2006/01/30 09:55:26 brouard
314: (Module): Back to gnuplot.exe instead of wgnuplot.exe
315:
316: Revision 1.111 2006/01/25 20:38:18 brouard
317: (Module): Lots of cleaning and bugs added (Gompertz)
318: (Module): Comments can be added in data file. Missing date values
319: can be a simple dot '.'.
320:
321: Revision 1.110 2006/01/25 00:51:50 brouard
322: (Module): Lots of cleaning and bugs added (Gompertz)
323:
324: Revision 1.109 2006/01/24 19:37:15 brouard
325: (Module): Comments (lines starting with a #) are allowed in data.
326:
327: Revision 1.108 2006/01/19 18:05:42 lievre
328: Gnuplot problem appeared...
329: To be fixed
330:
331: Revision 1.107 2006/01/19 16:20:37 brouard
332: Test existence of gnuplot in imach path
333:
334: Revision 1.106 2006/01/19 13:24:36 brouard
335: Some cleaning and links added in html output
336:
337: Revision 1.105 2006/01/05 20:23:19 lievre
338: *** empty log message ***
339:
340: Revision 1.104 2005/09/30 16:11:43 lievre
341: (Module): sump fixed, loop imx fixed, and simplifications.
342: (Module): If the status is missing at the last wave but we know
343: that the person is alive, then we can code his/her status as -2
344: (instead of missing=-1 in earlier versions) and his/her
345: contributions to the likelihood is 1 - Prob of dying from last
346: health status (= 1-p13= p11+p12 in the easiest case of somebody in
347: the healthy state at last known wave). Version is 0.98
348:
349: Revision 1.103 2005/09/30 15:54:49 lievre
350: (Module): sump fixed, loop imx fixed, and simplifications.
351:
352: Revision 1.102 2004/09/15 17:31:30 brouard
353: Add the possibility to read data file including tab characters.
354:
355: Revision 1.101 2004/09/15 10:38:38 brouard
356: Fix on curr_time
357:
358: Revision 1.100 2004/07/12 18:29:06 brouard
359: Add version for Mac OS X. Just define UNIX in Makefile
360:
361: Revision 1.99 2004/06/05 08:57:40 brouard
362: *** empty log message ***
363:
364: Revision 1.98 2004/05/16 15:05:56 brouard
365: New version 0.97 . First attempt to estimate force of mortality
366: directly from the data i.e. without the need of knowing the health
367: state at each age, but using a Gompertz model: log u =a + b*age .
368: This is the basic analysis of mortality and should be done before any
369: other analysis, in order to test if the mortality estimated from the
370: cross-longitudinal survey is different from the mortality estimated
371: from other sources like vital statistic data.
372:
373: The same imach parameter file can be used but the option for mle should be -3.
374:
1.133 brouard 375: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 376: former routines in order to include the new code within the former code.
377:
378: The output is very simple: only an estimate of the intercept and of
379: the slope with 95% confident intervals.
380:
381: Current limitations:
382: A) Even if you enter covariates, i.e. with the
383: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
384: B) There is no computation of Life Expectancy nor Life Table.
385:
386: Revision 1.97 2004/02/20 13:25:42 lievre
387: Version 0.96d. Population forecasting command line is (temporarily)
388: suppressed.
389:
390: Revision 1.96 2003/07/15 15:38:55 brouard
391: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
392: rewritten within the same printf. Workaround: many printfs.
393:
394: Revision 1.95 2003/07/08 07:54:34 brouard
395: * imach.c (Repository):
396: (Repository): Using imachwizard code to output a more meaningful covariance
397: matrix (cov(a12,c31) instead of numbers.
398:
399: Revision 1.94 2003/06/27 13:00:02 brouard
400: Just cleaning
401:
402: Revision 1.93 2003/06/25 16:33:55 brouard
403: (Module): On windows (cygwin) function asctime_r doesn't
404: exist so I changed back to asctime which exists.
405: (Module): Version 0.96b
406:
407: Revision 1.92 2003/06/25 16:30:45 brouard
408: (Module): On windows (cygwin) function asctime_r doesn't
409: exist so I changed back to asctime which exists.
410:
411: Revision 1.91 2003/06/25 15:30:29 brouard
412: * imach.c (Repository): Duplicated warning errors corrected.
413: (Repository): Elapsed time after each iteration is now output. It
414: helps to forecast when convergence will be reached. Elapsed time
415: is stamped in powell. We created a new html file for the graphs
416: concerning matrix of covariance. It has extension -cov.htm.
417:
418: Revision 1.90 2003/06/24 12:34:15 brouard
419: (Module): Some bugs corrected for windows. Also, when
420: mle=-1 a template is output in file "or"mypar.txt with the design
421: of the covariance matrix to be input.
422:
423: Revision 1.89 2003/06/24 12:30:52 brouard
424: (Module): Some bugs corrected for windows. Also, when
425: mle=-1 a template is output in file "or"mypar.txt with the design
426: of the covariance matrix to be input.
427:
428: Revision 1.88 2003/06/23 17:54:56 brouard
429: * 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.
430:
431: Revision 1.87 2003/06/18 12:26:01 brouard
432: Version 0.96
433:
434: Revision 1.86 2003/06/17 20:04:08 brouard
435: (Module): Change position of html and gnuplot routines and added
436: routine fileappend.
437:
438: Revision 1.85 2003/06/17 13:12:43 brouard
439: * imach.c (Repository): Check when date of death was earlier that
440: current date of interview. It may happen when the death was just
441: prior to the death. In this case, dh was negative and likelihood
442: was wrong (infinity). We still send an "Error" but patch by
443: assuming that the date of death was just one stepm after the
444: interview.
445: (Repository): Because some people have very long ID (first column)
446: we changed int to long in num[] and we added a new lvector for
447: memory allocation. But we also truncated to 8 characters (left
448: truncation)
449: (Repository): No more line truncation errors.
450:
451: Revision 1.84 2003/06/13 21:44:43 brouard
452: * imach.c (Repository): Replace "freqsummary" at a correct
453: place. It differs from routine "prevalence" which may be called
454: many times. Probs is memory consuming and must be used with
455: parcimony.
456: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
457:
458: Revision 1.83 2003/06/10 13:39:11 lievre
459: *** empty log message ***
460:
461: Revision 1.82 2003/06/05 15:57:20 brouard
462: Add log in imach.c and fullversion number is now printed.
463:
464: */
465: /*
466: Interpolated Markov Chain
467:
468: Short summary of the programme:
469:
470: This program computes Healthy Life Expectancies from
471: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
472: first survey ("cross") where individuals from different ages are
473: interviewed on their health status or degree of disability (in the
474: case of a health survey which is our main interest) -2- at least a
475: second wave of interviews ("longitudinal") which measure each change
476: (if any) in individual health status. Health expectancies are
477: computed from the time spent in each health state according to a
478: model. More health states you consider, more time is necessary to reach the
479: Maximum Likelihood of the parameters involved in the model. The
480: simplest model is the multinomial logistic model where pij is the
481: probability to be observed in state j at the second wave
482: conditional to be observed in state i at the first wave. Therefore
483: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
484: 'age' is age and 'sex' is a covariate. If you want to have a more
485: complex model than "constant and age", you should modify the program
486: where the markup *Covariates have to be included here again* invites
487: you to do it. More covariates you add, slower the
488: convergence.
489:
490: The advantage of this computer programme, compared to a simple
491: multinomial logistic model, is clear when the delay between waves is not
492: identical for each individual. Also, if a individual missed an
493: intermediate interview, the information is lost, but taken into
494: account using an interpolation or extrapolation.
495:
496: hPijx is the probability to be observed in state i at age x+h
497: conditional to the observed state i at age x. The delay 'h' can be
498: split into an exact number (nh*stepm) of unobserved intermediate
499: states. This elementary transition (by month, quarter,
500: semester or year) is modelled as a multinomial logistic. The hPx
501: matrix is simply the matrix product of nh*stepm elementary matrices
502: and the contribution of each individual to the likelihood is simply
503: hPijx.
504:
505: Also this programme outputs the covariance matrix of the parameters but also
506: of the life expectancies. It also computes the period (stable) prevalence.
507:
1.133 brouard 508: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
509: Institut national d'études démographiques, Paris.
1.126 brouard 510: This software have been partly granted by Euro-REVES, a concerted action
511: from the European Union.
512: It is copyrighted identically to a GNU software product, ie programme and
513: software can be distributed freely for non commercial use. Latest version
514: can be accessed at http://euroreves.ined.fr/imach .
515:
516: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
517: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
518:
519: **********************************************************************/
520: /*
521: main
522: read parameterfile
523: read datafile
524: concatwav
525: freqsummary
526: if (mle >= 1)
527: mlikeli
528: print results files
529: if mle==1
530: computes hessian
531: read end of parameter file: agemin, agemax, bage, fage, estepm
532: begin-prev-date,...
533: open gnuplot file
534: open html file
1.145 brouard 535: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
536: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
537: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
538: freexexit2 possible for memory heap.
539:
540: h Pij x | pij_nom ficrestpij
541: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
542: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
543: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
544:
545: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
546: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
547: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
548: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
549: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
550:
1.126 brouard 551: forecasting if prevfcast==1 prevforecast call prevalence()
552: health expectancies
553: Variance-covariance of DFLE
554: prevalence()
555: movingaverage()
556: varevsij()
557: if popbased==1 varevsij(,popbased)
558: total life expectancies
559: Variance of period (stable) prevalence
560: end
561: */
562:
1.165 brouard 563: #define POWELL /* Instead of NLOPT */
1.181 brouard 564: #define POWELLDIRECT /* Directest to decide new direction instead of Powell test */
1.126 brouard 565:
566: #include <math.h>
567: #include <stdio.h>
568: #include <stdlib.h>
569: #include <string.h>
1.159 brouard 570:
571: #ifdef _WIN32
572: #include <io.h>
1.172 brouard 573: #include <windows.h>
574: #include <tchar.h>
1.159 brouard 575: #else
1.126 brouard 576: #include <unistd.h>
1.159 brouard 577: #endif
1.126 brouard 578:
579: #include <limits.h>
580: #include <sys/types.h>
1.171 brouard 581:
582: #if defined(__GNUC__)
583: #include <sys/utsname.h> /* Doesn't work on Windows */
584: #endif
585:
1.126 brouard 586: #include <sys/stat.h>
587: #include <errno.h>
1.159 brouard 588: /* extern int errno; */
1.126 brouard 589:
1.157 brouard 590: /* #ifdef LINUX */
591: /* #include <time.h> */
592: /* #include "timeval.h" */
593: /* #else */
594: /* #include <sys/time.h> */
595: /* #endif */
596:
1.126 brouard 597: #include <time.h>
598:
1.136 brouard 599: #ifdef GSL
600: #include <gsl/gsl_errno.h>
601: #include <gsl/gsl_multimin.h>
602: #endif
603:
1.167 brouard 604:
1.162 brouard 605: #ifdef NLOPT
606: #include <nlopt.h>
607: typedef struct {
608: double (* function)(double [] );
609: } myfunc_data ;
610: #endif
611:
1.126 brouard 612: /* #include <libintl.h> */
613: /* #define _(String) gettext (String) */
614:
1.141 brouard 615: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 616:
617: #define GNUPLOTPROGRAM "gnuplot"
618: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
619: #define FILENAMELENGTH 132
620:
621: #define GLOCK_ERROR_NOPATH -1 /* empty path */
622: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
623:
1.144 brouard 624: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
625: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 626:
627: #define NINTERVMAX 8
1.144 brouard 628: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
629: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
630: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 631: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 632: #define MAXN 20000
1.144 brouard 633: #define YEARM 12. /**< Number of months per year */
1.126 brouard 634: #define AGESUP 130
635: #define AGEBASE 40
1.164 brouard 636: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 637: #ifdef _WIN32
638: #define DIRSEPARATOR '\\'
639: #define CHARSEPARATOR "\\"
640: #define ODIRSEPARATOR '/'
641: #else
1.126 brouard 642: #define DIRSEPARATOR '/'
643: #define CHARSEPARATOR "/"
644: #define ODIRSEPARATOR '\\'
645: #endif
646:
1.182 ! brouard 647: /* $Id: imach.c,v 1.181 2015/02/11 23:22:24 brouard Exp $ */
1.126 brouard 648: /* $State: Exp $ */
649:
1.180 brouard 650: char version[]="Imach version 0.98p, Février 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.182 ! brouard 651: char fullversion[]="$Revision: 1.181 $ $Date: 2015/02/11 23:22:24 $";
1.126 brouard 652: char strstart[80];
653: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 654: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 655: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 656: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
657: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
658: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
659: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
660: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
661: int cptcovprodnoage=0; /**< Number of covariate products without age */
662: int cptcoveff=0; /* Total number of covariates to vary for printing results */
663: int cptcov=0; /* Working variable */
1.126 brouard 664: int npar=NPARMAX;
665: int nlstate=2; /* Number of live states */
666: int ndeath=1; /* Number of dead states */
1.130 brouard 667: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 668: int popbased=0;
669:
670: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 671: int maxwav=0; /* Maxim number of waves */
672: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
673: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
674: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 675: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 676: int mle=1, weightopt=0;
1.126 brouard 677: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
678: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
679: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
680: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 681: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 682: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 683: double **matprod2(); /* test */
1.126 brouard 684: double **oldm, **newm, **savm; /* Working pointers to matrices */
685: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 686: /*FILE *fic ; */ /* Used in readdata only */
687: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 688: FILE *ficlog, *ficrespow;
1.130 brouard 689: int globpr=0; /* Global variable for printing or not */
1.126 brouard 690: double fretone; /* Only one call to likelihood */
1.130 brouard 691: long ipmx=0; /* Number of contributions */
1.126 brouard 692: double sw; /* Sum of weights */
693: char filerespow[FILENAMELENGTH];
694: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
695: FILE *ficresilk;
696: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
697: FILE *ficresprobmorprev;
698: FILE *fichtm, *fichtmcov; /* Html File */
699: FILE *ficreseij;
700: char filerese[FILENAMELENGTH];
701: FILE *ficresstdeij;
702: char fileresstde[FILENAMELENGTH];
703: FILE *ficrescveij;
704: char filerescve[FILENAMELENGTH];
705: FILE *ficresvij;
706: char fileresv[FILENAMELENGTH];
707: FILE *ficresvpl;
708: char fileresvpl[FILENAMELENGTH];
709: char title[MAXLINE];
710: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
711: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
712: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
713: char command[FILENAMELENGTH];
714: int outcmd=0;
715:
716: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
717:
718: char filelog[FILENAMELENGTH]; /* Log file */
719: char filerest[FILENAMELENGTH];
720: char fileregp[FILENAMELENGTH];
721: char popfile[FILENAMELENGTH];
722:
723: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
724:
1.157 brouard 725: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
726: /* struct timezone tzp; */
727: /* extern int gettimeofday(); */
728: struct tm tml, *gmtime(), *localtime();
729:
730: extern time_t time();
731:
732: struct tm start_time, end_time, curr_time, last_time, forecast_time;
733: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
734: struct tm tm;
735:
1.126 brouard 736: char strcurr[80], strfor[80];
737:
738: char *endptr;
739: long lval;
740: double dval;
741:
742: #define NR_END 1
743: #define FREE_ARG char*
744: #define FTOL 1.0e-10
745:
746: #define NRANSI
747: #define ITMAX 200
748:
749: #define TOL 2.0e-4
750:
751: #define CGOLD 0.3819660
752: #define ZEPS 1.0e-10
753: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
754:
755: #define GOLD 1.618034
756: #define GLIMIT 100.0
757: #define TINY 1.0e-20
758:
759: static double maxarg1,maxarg2;
760: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
761: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
762:
763: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
764: #define rint(a) floor(a+0.5)
1.166 brouard 765: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
766: /* #define mytinydouble 1.0e-16 */
767: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
768: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
769: /* static double dsqrarg; */
770: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 771: static double sqrarg;
772: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
773: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
774: int agegomp= AGEGOMP;
775:
776: int imx;
777: int stepm=1;
778: /* Stepm, step in month: minimum step interpolation*/
779:
780: int estepm;
781: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
782:
783: int m,nb;
784: long *num;
785: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
786: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
787: double **pmmij, ***probs;
788: double *ageexmed,*agecens;
789: double dateintmean=0;
790:
791: double *weight;
792: int **s; /* Status */
1.141 brouard 793: double *agedc;
1.145 brouard 794: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 795: * covar=matrix(0,NCOVMAX,1,n);
796: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
797: double idx;
798: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 799: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 800: int **codtab; /**< codtab=imatrix(1,100,1,10); */
801: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 802: double *lsurv, *lpop, *tpop;
803:
1.143 brouard 804: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
805: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 806:
807: /**************** split *************************/
808: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
809: {
810: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
811: the name of the file (name), its extension only (ext) and its first part of the name (finame)
812: */
813: char *ss; /* pointer */
814: int l1, l2; /* length counters */
815:
816: l1 = strlen(path ); /* length of path */
817: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
818: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
819: if ( ss == NULL ) { /* no directory, so determine current directory */
820: strcpy( name, path ); /* we got the fullname name because no directory */
821: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
822: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
823: /* get current working directory */
824: /* extern char* getcwd ( char *buf , int len);*/
825: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
826: return( GLOCK_ERROR_GETCWD );
827: }
828: /* got dirc from getcwd*/
829: printf(" DIRC = %s \n",dirc);
830: } else { /* strip direcotry from path */
831: ss++; /* after this, the filename */
832: l2 = strlen( ss ); /* length of filename */
833: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
834: strcpy( name, ss ); /* save file name */
835: strncpy( dirc, path, l1 - l2 ); /* now the directory */
836: dirc[l1-l2] = 0; /* add zero */
837: printf(" DIRC2 = %s \n",dirc);
838: }
839: /* We add a separator at the end of dirc if not exists */
840: l1 = strlen( dirc ); /* length of directory */
841: if( dirc[l1-1] != DIRSEPARATOR ){
842: dirc[l1] = DIRSEPARATOR;
843: dirc[l1+1] = 0;
844: printf(" DIRC3 = %s \n",dirc);
845: }
846: ss = strrchr( name, '.' ); /* find last / */
847: if (ss >0){
848: ss++;
849: strcpy(ext,ss); /* save extension */
850: l1= strlen( name);
851: l2= strlen(ss)+1;
852: strncpy( finame, name, l1-l2);
853: finame[l1-l2]= 0;
854: }
855:
856: return( 0 ); /* we're done */
857: }
858:
859:
860: /******************************************/
861:
862: void replace_back_to_slash(char *s, char*t)
863: {
864: int i;
865: int lg=0;
866: i=0;
867: lg=strlen(t);
868: for(i=0; i<= lg; i++) {
869: (s[i] = t[i]);
870: if (t[i]== '\\') s[i]='/';
871: }
872: }
873:
1.132 brouard 874: char *trimbb(char *out, char *in)
1.137 brouard 875: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 876: char *s;
877: s=out;
878: while (*in != '\0'){
1.137 brouard 879: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 880: in++;
881: }
882: *out++ = *in++;
883: }
884: *out='\0';
885: return s;
886: }
887:
1.145 brouard 888: char *cutl(char *blocc, char *alocc, char *in, char occ)
889: {
890: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
891: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
892: gives blocc="abcdef2ghi" and alocc="j".
893: If occ is not found blocc is null and alocc is equal to in. Returns blocc
894: */
1.160 brouard 895: char *s, *t;
1.145 brouard 896: t=in;s=in;
897: while ((*in != occ) && (*in != '\0')){
898: *alocc++ = *in++;
899: }
900: if( *in == occ){
901: *(alocc)='\0';
902: s=++in;
903: }
904:
905: if (s == t) {/* occ not found */
906: *(alocc-(in-s))='\0';
907: in=s;
908: }
909: while ( *in != '\0'){
910: *blocc++ = *in++;
911: }
912:
913: *blocc='\0';
914: return t;
915: }
1.137 brouard 916: char *cutv(char *blocc, char *alocc, char *in, char occ)
917: {
918: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
919: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
920: gives blocc="abcdef2ghi" and alocc="j".
921: If occ is not found blocc is null and alocc is equal to in. Returns alocc
922: */
923: char *s, *t;
924: t=in;s=in;
925: while (*in != '\0'){
926: while( *in == occ){
927: *blocc++ = *in++;
928: s=in;
929: }
930: *blocc++ = *in++;
931: }
932: if (s == t) /* occ not found */
933: *(blocc-(in-s))='\0';
934: else
935: *(blocc-(in-s)-1)='\0';
936: in=s;
937: while ( *in != '\0'){
938: *alocc++ = *in++;
939: }
940:
941: *alocc='\0';
942: return s;
943: }
944:
1.126 brouard 945: int nbocc(char *s, char occ)
946: {
947: int i,j=0;
948: int lg=20;
949: i=0;
950: lg=strlen(s);
951: for(i=0; i<= lg; i++) {
952: if (s[i] == occ ) j++;
953: }
954: return j;
955: }
956:
1.137 brouard 957: /* void cutv(char *u,char *v, char*t, char occ) */
958: /* { */
959: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
960: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
961: /* gives u="abcdef2ghi" and v="j" *\/ */
962: /* int i,lg,j,p=0; */
963: /* i=0; */
964: /* lg=strlen(t); */
965: /* for(j=0; j<=lg-1; j++) { */
966: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
967: /* } */
1.126 brouard 968:
1.137 brouard 969: /* for(j=0; j<p; j++) { */
970: /* (u[j] = t[j]); */
971: /* } */
972: /* u[p]='\0'; */
1.126 brouard 973:
1.137 brouard 974: /* for(j=0; j<= lg; j++) { */
975: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
976: /* } */
977: /* } */
1.126 brouard 978:
1.160 brouard 979: #ifdef _WIN32
980: char * strsep(char **pp, const char *delim)
981: {
982: char *p, *q;
983:
984: if ((p = *pp) == NULL)
985: return 0;
986: if ((q = strpbrk (p, delim)) != NULL)
987: {
988: *pp = q + 1;
989: *q = '\0';
990: }
991: else
992: *pp = 0;
993: return p;
994: }
995: #endif
996:
1.126 brouard 997: /********************** nrerror ********************/
998:
999: void nrerror(char error_text[])
1000: {
1001: fprintf(stderr,"ERREUR ...\n");
1002: fprintf(stderr,"%s\n",error_text);
1003: exit(EXIT_FAILURE);
1004: }
1005: /*********************** vector *******************/
1006: double *vector(int nl, int nh)
1007: {
1008: double *v;
1009: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1010: if (!v) nrerror("allocation failure in vector");
1011: return v-nl+NR_END;
1012: }
1013:
1014: /************************ free vector ******************/
1015: void free_vector(double*v, int nl, int nh)
1016: {
1017: free((FREE_ARG)(v+nl-NR_END));
1018: }
1019:
1020: /************************ivector *******************************/
1021: int *ivector(long nl,long nh)
1022: {
1023: int *v;
1024: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1025: if (!v) nrerror("allocation failure in ivector");
1026: return v-nl+NR_END;
1027: }
1028:
1029: /******************free ivector **************************/
1030: void free_ivector(int *v, long nl, long nh)
1031: {
1032: free((FREE_ARG)(v+nl-NR_END));
1033: }
1034:
1035: /************************lvector *******************************/
1036: long *lvector(long nl,long nh)
1037: {
1038: long *v;
1039: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1040: if (!v) nrerror("allocation failure in ivector");
1041: return v-nl+NR_END;
1042: }
1043:
1044: /******************free lvector **************************/
1045: void free_lvector(long *v, long nl, long nh)
1046: {
1047: free((FREE_ARG)(v+nl-NR_END));
1048: }
1049:
1050: /******************* imatrix *******************************/
1051: int **imatrix(long nrl, long nrh, long ncl, long nch)
1052: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1053: {
1054: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1055: int **m;
1056:
1057: /* allocate pointers to rows */
1058: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1059: if (!m) nrerror("allocation failure 1 in matrix()");
1060: m += NR_END;
1061: m -= nrl;
1062:
1063:
1064: /* allocate rows and set pointers to them */
1065: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1066: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1067: m[nrl] += NR_END;
1068: m[nrl] -= ncl;
1069:
1070: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1071:
1072: /* return pointer to array of pointers to rows */
1073: return m;
1074: }
1075:
1076: /****************** free_imatrix *************************/
1077: void free_imatrix(m,nrl,nrh,ncl,nch)
1078: int **m;
1079: long nch,ncl,nrh,nrl;
1080: /* free an int matrix allocated by imatrix() */
1081: {
1082: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1083: free((FREE_ARG) (m+nrl-NR_END));
1084: }
1085:
1086: /******************* matrix *******************************/
1087: double **matrix(long nrl, long nrh, long ncl, long nch)
1088: {
1089: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1090: double **m;
1091:
1092: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1093: if (!m) nrerror("allocation failure 1 in matrix()");
1094: m += NR_END;
1095: m -= nrl;
1096:
1097: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1098: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1099: m[nrl] += NR_END;
1100: m[nrl] -= ncl;
1101:
1102: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1103: return m;
1.145 brouard 1104: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1105: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1106: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1107: */
1108: }
1109:
1110: /*************************free matrix ************************/
1111: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1112: {
1113: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1114: free((FREE_ARG)(m+nrl-NR_END));
1115: }
1116:
1117: /******************* ma3x *******************************/
1118: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1119: {
1120: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1121: double ***m;
1122:
1123: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1124: if (!m) nrerror("allocation failure 1 in matrix()");
1125: m += NR_END;
1126: m -= nrl;
1127:
1128: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1129: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1130: m[nrl] += NR_END;
1131: m[nrl] -= ncl;
1132:
1133: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1134:
1135: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1136: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1137: m[nrl][ncl] += NR_END;
1138: m[nrl][ncl] -= nll;
1139: for (j=ncl+1; j<=nch; j++)
1140: m[nrl][j]=m[nrl][j-1]+nlay;
1141:
1142: for (i=nrl+1; i<=nrh; i++) {
1143: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1144: for (j=ncl+1; j<=nch; j++)
1145: m[i][j]=m[i][j-1]+nlay;
1146: }
1147: return m;
1148: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1149: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1150: */
1151: }
1152:
1153: /*************************free ma3x ************************/
1154: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1155: {
1156: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1157: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1158: free((FREE_ARG)(m+nrl-NR_END));
1159: }
1160:
1161: /*************** function subdirf ***********/
1162: char *subdirf(char fileres[])
1163: {
1164: /* Caution optionfilefiname is hidden */
1165: strcpy(tmpout,optionfilefiname);
1166: strcat(tmpout,"/"); /* Add to the right */
1167: strcat(tmpout,fileres);
1168: return tmpout;
1169: }
1170:
1171: /*************** function subdirf2 ***********/
1172: char *subdirf2(char fileres[], char *preop)
1173: {
1174:
1175: /* Caution optionfilefiname is hidden */
1176: strcpy(tmpout,optionfilefiname);
1177: strcat(tmpout,"/");
1178: strcat(tmpout,preop);
1179: strcat(tmpout,fileres);
1180: return tmpout;
1181: }
1182:
1183: /*************** function subdirf3 ***********/
1184: char *subdirf3(char fileres[], char *preop, char *preop2)
1185: {
1186:
1187: /* Caution optionfilefiname is hidden */
1188: strcpy(tmpout,optionfilefiname);
1189: strcat(tmpout,"/");
1190: strcat(tmpout,preop);
1191: strcat(tmpout,preop2);
1192: strcat(tmpout,fileres);
1193: return tmpout;
1194: }
1195:
1.162 brouard 1196: char *asc_diff_time(long time_sec, char ascdiff[])
1197: {
1198: long sec_left, days, hours, minutes;
1199: days = (time_sec) / (60*60*24);
1200: sec_left = (time_sec) % (60*60*24);
1201: hours = (sec_left) / (60*60) ;
1202: sec_left = (sec_left) %(60*60);
1203: minutes = (sec_left) /60;
1204: sec_left = (sec_left) % (60);
1205: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1206: return ascdiff;
1207: }
1208:
1.126 brouard 1209: /***************** f1dim *************************/
1210: extern int ncom;
1211: extern double *pcom,*xicom;
1212: extern double (*nrfunc)(double []);
1213:
1214: double f1dim(double x)
1215: {
1216: int j;
1217: double f;
1218: double *xt;
1219:
1220: xt=vector(1,ncom);
1221: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1222: f=(*nrfunc)(xt);
1223: free_vector(xt,1,ncom);
1224: return f;
1225: }
1226:
1227: /*****************brent *************************/
1228: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1229: {
1230: int iter;
1231: double a,b,d,etemp;
1.159 brouard 1232: double fu=0,fv,fw,fx;
1.164 brouard 1233: double ftemp=0.;
1.126 brouard 1234: double p,q,r,tol1,tol2,u,v,w,x,xm;
1235: double e=0.0;
1236:
1237: a=(ax < cx ? ax : cx);
1238: b=(ax > cx ? ax : cx);
1239: x=w=v=bx;
1240: fw=fv=fx=(*f)(x);
1241: for (iter=1;iter<=ITMAX;iter++) {
1242: xm=0.5*(a+b);
1243: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1244: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1245: printf(".");fflush(stdout);
1246: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1247: #ifdef DEBUGBRENT
1.126 brouard 1248: 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);
1249: 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);
1250: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1251: #endif
1252: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1253: *xmin=x;
1254: return fx;
1255: }
1256: ftemp=fu;
1257: if (fabs(e) > tol1) {
1258: r=(x-w)*(fx-fv);
1259: q=(x-v)*(fx-fw);
1260: p=(x-v)*q-(x-w)*r;
1261: q=2.0*(q-r);
1262: if (q > 0.0) p = -p;
1263: q=fabs(q);
1264: etemp=e;
1265: e=d;
1266: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1267: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1268: else {
1269: d=p/q;
1270: u=x+d;
1271: if (u-a < tol2 || b-u < tol2)
1272: d=SIGN(tol1,xm-x);
1273: }
1274: } else {
1275: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1276: }
1277: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1278: fu=(*f)(u);
1279: if (fu <= fx) {
1280: if (u >= x) a=x; else b=x;
1281: SHFT(v,w,x,u)
1282: SHFT(fv,fw,fx,fu)
1283: } else {
1284: if (u < x) a=u; else b=u;
1285: if (fu <= fw || w == x) {
1286: v=w;
1287: w=u;
1288: fv=fw;
1289: fw=fu;
1290: } else if (fu <= fv || v == x || v == w) {
1291: v=u;
1292: fv=fu;
1293: }
1294: }
1295: }
1296: nrerror("Too many iterations in brent");
1297: *xmin=x;
1298: return fx;
1299: }
1300:
1301: /****************** mnbrak ***********************/
1302:
1303: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1304: double (*func)(double))
1305: {
1306: double ulim,u,r,q, dum;
1307: double fu;
1308:
1309: *fa=(*func)(*ax);
1310: *fb=(*func)(*bx);
1311: if (*fb > *fa) {
1312: SHFT(dum,*ax,*bx,dum)
1313: SHFT(dum,*fb,*fa,dum)
1314: }
1315: *cx=(*bx)+GOLD*(*bx-*ax);
1316: *fc=(*func)(*cx);
1.162 brouard 1317: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1318: r=(*bx-*ax)*(*fb-*fc);
1319: q=(*bx-*cx)*(*fb-*fa);
1320: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1321: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1322: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1323: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1324: fu=(*func)(u);
1.163 brouard 1325: #ifdef DEBUG
1326: /* f(x)=A(x-u)**2+f(u) */
1327: double A, fparabu;
1328: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1329: fparabu= *fa - A*(*ax-u)*(*ax-u);
1330: 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);
1331: 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);
1332: #endif
1.162 brouard 1333: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1334: fu=(*func)(u);
1335: if (fu < *fc) {
1336: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1337: SHFT(*fb,*fc,fu,(*func)(u))
1338: }
1.162 brouard 1339: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1340: u=ulim;
1341: fu=(*func)(u);
1342: } else {
1343: u=(*cx)+GOLD*(*cx-*bx);
1344: fu=(*func)(u);
1345: }
1346: SHFT(*ax,*bx,*cx,u)
1347: SHFT(*fa,*fb,*fc,fu)
1348: }
1349: }
1350:
1351: /*************** linmin ************************/
1.162 brouard 1352: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1353: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1354: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1355: the value of func at the returned location p . This is actually all accomplished by calling the
1356: routines mnbrak and brent .*/
1.126 brouard 1357: int ncom;
1358: double *pcom,*xicom;
1359: double (*nrfunc)(double []);
1360:
1361: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1362: {
1363: double brent(double ax, double bx, double cx,
1364: double (*f)(double), double tol, double *xmin);
1365: double f1dim(double x);
1366: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1367: double *fc, double (*func)(double));
1368: int j;
1369: double xx,xmin,bx,ax;
1370: double fx,fb,fa;
1371:
1372: ncom=n;
1373: pcom=vector(1,n);
1374: xicom=vector(1,n);
1375: nrfunc=func;
1376: for (j=1;j<=n;j++) {
1377: pcom[j]=p[j];
1378: xicom[j]=xi[j];
1379: }
1380: ax=0.0;
1381: xx=1.0;
1.162 brouard 1382: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1383: *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 1384: #ifdef DEBUG
1385: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1386: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1387: #endif
1388: for (j=1;j<=n;j++) {
1389: xi[j] *= xmin;
1390: p[j] += xi[j];
1391: }
1392: free_vector(xicom,1,n);
1393: free_vector(pcom,1,n);
1394: }
1395:
1396:
1397: /*************** powell ************************/
1.162 brouard 1398: /*
1399: Minimization of a function func of n variables. Input consists of an initial starting point
1400: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1401: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1402: such that failure to decrease by more than this amount on one iteration signals doneness. On
1403: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1404: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1405: */
1.126 brouard 1406: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1407: double (*func)(double []))
1408: {
1409: void linmin(double p[], double xi[], int n, double *fret,
1410: double (*func)(double []));
1411: int i,ibig,j;
1412: double del,t,*pt,*ptt,*xit;
1.181 brouard 1413: double directest;
1.126 brouard 1414: double fp,fptt;
1415: double *xits;
1416: int niterf, itmp;
1417:
1418: pt=vector(1,n);
1419: ptt=vector(1,n);
1420: xit=vector(1,n);
1421: xits=vector(1,n);
1422: *fret=(*func)(p);
1423: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1424: rcurr_time = time(NULL);
1.126 brouard 1425: for (*iter=1;;++(*iter)) {
1426: fp=(*fret);
1427: ibig=0;
1428: del=0.0;
1.157 brouard 1429: rlast_time=rcurr_time;
1430: /* (void) gettimeofday(&curr_time,&tzp); */
1431: rcurr_time = time(NULL);
1432: curr_time = *localtime(&rcurr_time);
1433: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1434: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1435: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1436: for (i=1;i<=n;i++) {
1437: printf(" %d %.12f",i, p[i]);
1438: fprintf(ficlog," %d %.12lf",i, p[i]);
1439: fprintf(ficrespow," %.12lf", p[i]);
1440: }
1441: printf("\n");
1442: fprintf(ficlog,"\n");
1443: fprintf(ficrespow,"\n");fflush(ficrespow);
1444: if(*iter <=3){
1.157 brouard 1445: tml = *localtime(&rcurr_time);
1446: strcpy(strcurr,asctime(&tml));
1447: rforecast_time=rcurr_time;
1.126 brouard 1448: itmp = strlen(strcurr);
1449: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1450: strcurr[itmp-1]='\0';
1.162 brouard 1451: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1452: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1453: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1454: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1455: forecast_time = *localtime(&rforecast_time);
1456: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1457: itmp = strlen(strfor);
1458: if(strfor[itmp-1]=='\n')
1459: strfor[itmp-1]='\0';
1.157 brouard 1460: 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);
1461: 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 1462: }
1463: }
1464: for (i=1;i<=n;i++) {
1465: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1466: fptt=(*fret);
1467: #ifdef DEBUG
1.164 brouard 1468: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1469: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1470: #endif
1471: printf("%d",i);fflush(stdout);
1472: fprintf(ficlog,"%d",i);fflush(ficlog);
1473: linmin(p,xit,n,fret,func);
1.181 brouard 1474: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1475: because that direction will be replaced unless the gain del is small
1476: in comparison with the 'probable' gain, mu^2, with the last average direction.
1477: Unless the n directions are conjugate some gain in the determinant may be obtained
1478: with the new direction.
1479: */
1.126 brouard 1480: del=fabs(fptt-(*fret));
1481: ibig=i;
1482: }
1483: #ifdef DEBUG
1484: printf("%d %.12e",i,(*fret));
1485: fprintf(ficlog,"%d %.12e",i,(*fret));
1486: for (j=1;j<=n;j++) {
1487: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1488: printf(" x(%d)=%.12e",j,xit[j]);
1489: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1490: }
1491: for(j=1;j<=n;j++) {
1.162 brouard 1492: printf(" p(%d)=%.12e",j,p[j]);
1493: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1494: }
1495: printf("\n");
1496: fprintf(ficlog,"\n");
1497: #endif
1.162 brouard 1498: } /* end i */
1.182 ! brouard 1499: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.126 brouard 1500: #ifdef DEBUG
1501: int k[2],l;
1502: k[0]=1;
1503: k[1]=-1;
1504: printf("Max: %.12e",(*func)(p));
1505: fprintf(ficlog,"Max: %.12e",(*func)(p));
1506: for (j=1;j<=n;j++) {
1507: printf(" %.12e",p[j]);
1508: fprintf(ficlog," %.12e",p[j]);
1509: }
1510: printf("\n");
1511: fprintf(ficlog,"\n");
1512: for(l=0;l<=1;l++) {
1513: for (j=1;j<=n;j++) {
1514: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1515: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1516: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1517: }
1518: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1519: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1520: }
1521: #endif
1522:
1523:
1524: free_vector(xit,1,n);
1525: free_vector(xits,1,n);
1526: free_vector(ptt,1,n);
1527: free_vector(pt,1,n);
1528: return;
1529: }
1530: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1531: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1532: ptt[j]=2.0*p[j]-pt[j];
1533: xit[j]=p[j]-pt[j];
1534: pt[j]=p[j];
1535: }
1.181 brouard 1536: fptt=(*func)(ptt); /* f_3 */
1.161 brouard 1537: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1538: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1539: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1540: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1541: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1542: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1543: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1544: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1545:
1.182 ! brouard 1546: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line */
1.161 brouard 1547: t= t- del*SQR(fp-fptt);
1.182 ! brouard 1548: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1549: #ifdef DEBUG
1.181 brouard 1550: printf("t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1551: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1.161 brouard 1552: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1553: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1554: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1555: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1556: 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);
1557: 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);
1558: #endif
1.181 brouard 1559: #ifdef POWELLDIRECT
1.182 ! brouard 1560: if (directest*t < 0.0) { /* Contradiction between both tests */
! 1561: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
! 1562: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
! 1563: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
! 1564: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
! 1565: }
1.181 brouard 1566: if (directest < 0.0) { /* Then we use it for new direction */
1567: #else
1568: if (t < 0.0) { /* Then we use it for new direction */
1569: #endif
1570: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1.126 brouard 1571: for (j=1;j<=n;j++) {
1.181 brouard 1572: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1573: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1574: }
1.181 brouard 1575: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1576: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1577:
1.126 brouard 1578: #ifdef DEBUG
1.164 brouard 1579: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1580: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1581: for(j=1;j<=n;j++){
1582: printf(" %.12e",xit[j]);
1583: fprintf(ficlog," %.12e",xit[j]);
1584: }
1585: printf("\n");
1586: fprintf(ficlog,"\n");
1587: #endif
1.162 brouard 1588: } /* end of t negative */
1589: } /* end if (fptt < fp) */
1.126 brouard 1590: }
1591: }
1592:
1593: /**** Prevalence limit (stable or period prevalence) ****************/
1594:
1595: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1596: {
1597: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1598: matrix by transitions matrix until convergence is reached */
1.169 brouard 1599:
1.126 brouard 1600: int i, ii,j,k;
1601: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1602: /* double **matprod2(); */ /* test */
1.131 brouard 1603: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1604: double **newm;
1605: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1606:
1.126 brouard 1607: for (ii=1;ii<=nlstate+ndeath;ii++)
1608: for (j=1;j<=nlstate+ndeath;j++){
1609: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1610: }
1.169 brouard 1611:
1612: cov[1]=1.;
1613:
1614: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1615: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1616: newm=savm;
1617: /* Covariates have to be included here again */
1.138 brouard 1618: cov[2]=agefin;
1619:
1620: for (k=1; k<=cptcovn;k++) {
1621: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1622: /*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 1623: }
1.145 brouard 1624: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1625: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1626: /* 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 1627:
1628: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1629: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1630: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1631: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1632: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1633: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1634:
1.126 brouard 1635: savm=oldm;
1636: oldm=newm;
1637: maxmax=0.;
1638: for(j=1;j<=nlstate;j++){
1639: min=1.;
1640: max=0.;
1641: for(i=1; i<=nlstate; i++) {
1642: sumnew=0;
1643: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1644: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1645: /*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 1646: max=FMAX(max,prlim[i][j]);
1647: min=FMIN(min,prlim[i][j]);
1648: }
1649: maxmin=max-min;
1650: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1651: } /* j loop */
1.126 brouard 1652: if(maxmax < ftolpl){
1653: return prlim;
1654: }
1.169 brouard 1655: } /* age loop */
1656: return prlim; /* should not reach here */
1.126 brouard 1657: }
1658:
1659: /*************** transition probabilities ***************/
1660:
1661: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1662: {
1.138 brouard 1663: /* According to parameters values stored in x and the covariate's values stored in cov,
1664: computes the probability to be observed in state j being in state i by appying the
1665: model to the ncovmodel covariates (including constant and age).
1666: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1667: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1668: ncth covariate in the global vector x is given by the formula:
1669: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1670: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1671: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1672: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1673: Outputs ps[i][j] the probability to be observed in j being in j according to
1674: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1675: */
1676: double s1, lnpijopii;
1.126 brouard 1677: /*double t34;*/
1.164 brouard 1678: int i,j, nc, ii, jj;
1.126 brouard 1679:
1680: for(i=1; i<= nlstate; i++){
1681: for(j=1; j<i;j++){
1.138 brouard 1682: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1683: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1684: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1685: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1686: }
1.138 brouard 1687: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1688: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1689: }
1690: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1691: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1692: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1693: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1694: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1695: }
1.138 brouard 1696: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1697: }
1698: }
1699:
1700: for(i=1; i<= nlstate; i++){
1701: s1=0;
1.131 brouard 1702: for(j=1; j<i; j++){
1.138 brouard 1703: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1704: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1705: }
1706: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1707: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1708: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1709: }
1.138 brouard 1710: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1711: ps[i][i]=1./(s1+1.);
1.138 brouard 1712: /* Computing other pijs */
1.126 brouard 1713: for(j=1; j<i; j++)
1714: ps[i][j]= exp(ps[i][j])*ps[i][i];
1715: for(j=i+1; j<=nlstate+ndeath; j++)
1716: ps[i][j]= exp(ps[i][j])*ps[i][i];
1717: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1718: } /* end i */
1719:
1720: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1721: for(jj=1; jj<= nlstate+ndeath; jj++){
1722: ps[ii][jj]=0;
1723: ps[ii][ii]=1;
1724: }
1725: }
1726:
1.145 brouard 1727:
1728: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1729: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1730: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1731: /* } */
1732: /* printf("\n "); */
1733: /* } */
1734: /* printf("\n ");printf("%lf ",cov[2]);*/
1735: /*
1.126 brouard 1736: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1737: goto end;*/
1738: return ps;
1739: }
1740:
1741: /**************** Product of 2 matrices ******************/
1742:
1.145 brouard 1743: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1744: {
1745: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1746: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1747: /* in, b, out are matrice of pointers which should have been initialized
1748: before: only the contents of out is modified. The function returns
1749: a pointer to pointers identical to out */
1.145 brouard 1750: int i, j, k;
1.126 brouard 1751: for(i=nrl; i<= nrh; i++)
1.145 brouard 1752: for(k=ncolol; k<=ncoloh; k++){
1753: out[i][k]=0.;
1754: for(j=ncl; j<=nch; j++)
1755: out[i][k] +=in[i][j]*b[j][k];
1756: }
1.126 brouard 1757: return out;
1758: }
1759:
1760:
1761: /************* Higher Matrix Product ***************/
1762:
1763: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1764: {
1765: /* Computes the transition matrix starting at age 'age' over
1766: 'nhstepm*hstepm*stepm' months (i.e. until
1767: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1768: nhstepm*hstepm matrices.
1769: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1770: (typically every 2 years instead of every month which is too big
1771: for the memory).
1772: Model is determined by parameters x and covariates have to be
1773: included manually here.
1774:
1775: */
1776:
1777: int i, j, d, h, k;
1.131 brouard 1778: double **out, cov[NCOVMAX+1];
1.126 brouard 1779: double **newm;
1780:
1781: /* Hstepm could be zero and should return the unit matrix */
1782: for (i=1;i<=nlstate+ndeath;i++)
1783: for (j=1;j<=nlstate+ndeath;j++){
1784: oldm[i][j]=(i==j ? 1.0 : 0.0);
1785: po[i][j][0]=(i==j ? 1.0 : 0.0);
1786: }
1787: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1788: for(h=1; h <=nhstepm; h++){
1789: for(d=1; d <=hstepm; d++){
1790: newm=savm;
1791: /* Covariates have to be included here again */
1792: cov[1]=1.;
1793: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1794: for (k=1; k<=cptcovn;k++)
1795: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1796: for (k=1; k<=cptcovage;k++)
1797: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1798: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1799: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1800:
1801:
1802: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1803: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1804: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1805: pmij(pmmij,cov,ncovmodel,x,nlstate));
1806: savm=oldm;
1807: oldm=newm;
1808: }
1809: for(i=1; i<=nlstate+ndeath; i++)
1810: for(j=1;j<=nlstate+ndeath;j++) {
1811: po[i][j][h]=newm[i][j];
1.128 brouard 1812: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1813: }
1.128 brouard 1814: /*printf("h=%d ",h);*/
1.126 brouard 1815: } /* end h */
1.128 brouard 1816: /* printf("\n H=%d \n",h); */
1.126 brouard 1817: return po;
1818: }
1819:
1.162 brouard 1820: #ifdef NLOPT
1821: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1822: double fret;
1823: double *xt;
1824: int j;
1825: myfunc_data *d2 = (myfunc_data *) pd;
1826: /* xt = (p1-1); */
1827: xt=vector(1,n);
1828: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1829:
1830: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1831: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1832: printf("Function = %.12lf ",fret);
1833: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1834: printf("\n");
1835: free_vector(xt,1,n);
1836: return fret;
1837: }
1838: #endif
1.126 brouard 1839:
1840: /*************** log-likelihood *************/
1841: double func( double *x)
1842: {
1843: int i, ii, j, k, mi, d, kk;
1.131 brouard 1844: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1845: double **out;
1846: double sw; /* Sum of weights */
1847: double lli; /* Individual log likelihood */
1848: int s1, s2;
1849: double bbh, survp;
1850: long ipmx;
1851: /*extern weight */
1852: /* We are differentiating ll according to initial status */
1853: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1854: /*for(i=1;i<imx;i++)
1855: printf(" %d\n",s[4][i]);
1856: */
1.162 brouard 1857:
1858: ++countcallfunc;
1859:
1.126 brouard 1860: cov[1]=1.;
1861:
1862: for(k=1; k<=nlstate; k++) ll[k]=0.;
1863:
1864: if(mle==1){
1865: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1866: /* Computes the values of the ncovmodel covariates of the model
1867: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1868: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1869: to be observed in j being in i according to the model.
1870: */
1.145 brouard 1871: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1872: cov[2+k]=covar[Tvar[k]][i];
1873: }
1.137 brouard 1874: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1875: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1876: has been calculated etc */
1.126 brouard 1877: for(mi=1; mi<= wav[i]-1; mi++){
1878: for (ii=1;ii<=nlstate+ndeath;ii++)
1879: for (j=1;j<=nlstate+ndeath;j++){
1880: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1881: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1882: }
1883: for(d=0; d<dh[mi][i]; d++){
1884: newm=savm;
1885: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1886: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1887: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1888: }
1889: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1890: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1891: savm=oldm;
1892: oldm=newm;
1893: } /* end mult */
1894:
1895: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1896: /* But now since version 0.9 we anticipate for bias at large stepm.
1897: * If stepm is larger than one month (smallest stepm) and if the exact delay
1898: * (in months) between two waves is not a multiple of stepm, we rounded to
1899: * the nearest (and in case of equal distance, to the lowest) interval but now
1900: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1901: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1902: * probability in order to take into account the bias as a fraction of the way
1903: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1904: * -stepm/2 to stepm/2 .
1905: * For stepm=1 the results are the same as for previous versions of Imach.
1906: * For stepm > 1 the results are less biased than in previous versions.
1907: */
1908: s1=s[mw[mi][i]][i];
1909: s2=s[mw[mi+1][i]][i];
1910: bbh=(double)bh[mi][i]/(double)stepm;
1911: /* bias bh is positive if real duration
1912: * is higher than the multiple of stepm and negative otherwise.
1913: */
1914: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1915: if( s2 > nlstate){
1916: /* i.e. if s2 is a death state and if the date of death is known
1917: then the contribution to the likelihood is the probability to
1918: die between last step unit time and current step unit time,
1919: which is also equal to probability to die before dh
1920: minus probability to die before dh-stepm .
1921: In version up to 0.92 likelihood was computed
1922: as if date of death was unknown. Death was treated as any other
1923: health state: the date of the interview describes the actual state
1924: and not the date of a change in health state. The former idea was
1925: to consider that at each interview the state was recorded
1926: (healthy, disable or death) and IMaCh was corrected; but when we
1927: introduced the exact date of death then we should have modified
1928: the contribution of an exact death to the likelihood. This new
1929: contribution is smaller and very dependent of the step unit
1930: stepm. It is no more the probability to die between last interview
1931: and month of death but the probability to survive from last
1932: interview up to one month before death multiplied by the
1933: probability to die within a month. Thanks to Chris
1934: Jackson for correcting this bug. Former versions increased
1935: mortality artificially. The bad side is that we add another loop
1936: which slows down the processing. The difference can be up to 10%
1937: lower mortality.
1938: */
1939: lli=log(out[s1][s2] - savm[s1][s2]);
1940:
1941:
1942: } else if (s2==-2) {
1943: for (j=1,survp=0. ; j<=nlstate; j++)
1944: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1945: /*survp += out[s1][j]; */
1946: lli= log(survp);
1947: }
1948:
1949: else if (s2==-4) {
1950: for (j=3,survp=0. ; j<=nlstate; j++)
1951: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1952: lli= log(survp);
1953: }
1954:
1955: else if (s2==-5) {
1956: for (j=1,survp=0. ; j<=2; j++)
1957: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1958: lli= log(survp);
1959: }
1960:
1961: else{
1962: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1963: /* 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 */
1964: }
1965: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1966: /*if(lli ==000.0)*/
1967: /*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); */
1968: ipmx +=1;
1969: sw += weight[i];
1970: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1971: } /* end of wave */
1972: } /* end of individual */
1973: } else if(mle==2){
1974: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1975: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1976: for(mi=1; mi<= wav[i]-1; mi++){
1977: for (ii=1;ii<=nlstate+ndeath;ii++)
1978: for (j=1;j<=nlstate+ndeath;j++){
1979: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1980: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1981: }
1982: for(d=0; d<=dh[mi][i]; d++){
1983: newm=savm;
1984: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1985: for (kk=1; kk<=cptcovage;kk++) {
1986: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
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: bbh=(double)bh[mi][i]/(double)stepm;
1997: 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 */
1998: ipmx +=1;
1999: sw += weight[i];
2000: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2001: } /* end of wave */
2002: } /* end of individual */
2003: } else if(mle==3){ /* exponential inter-extrapolation */
2004: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2005: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2006: for(mi=1; mi<= wav[i]-1; mi++){
2007: for (ii=1;ii<=nlstate+ndeath;ii++)
2008: for (j=1;j<=nlstate+ndeath;j++){
2009: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2010: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2011: }
2012: for(d=0; d<dh[mi][i]; d++){
2013: newm=savm;
2014: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2015: for (kk=1; kk<=cptcovage;kk++) {
2016: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2017: }
2018: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2019: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2020: savm=oldm;
2021: oldm=newm;
2022: } /* end mult */
2023:
2024: s1=s[mw[mi][i]][i];
2025: s2=s[mw[mi+1][i]][i];
2026: bbh=(double)bh[mi][i]/(double)stepm;
2027: 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 */
2028: ipmx +=1;
2029: sw += weight[i];
2030: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2031: } /* end of wave */
2032: } /* end of individual */
2033: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2034: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2035: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2036: for(mi=1; mi<= wav[i]-1; mi++){
2037: for (ii=1;ii<=nlstate+ndeath;ii++)
2038: for (j=1;j<=nlstate+ndeath;j++){
2039: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2040: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2041: }
2042: for(d=0; d<dh[mi][i]; d++){
2043: newm=savm;
2044: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2045: for (kk=1; kk<=cptcovage;kk++) {
2046: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2047: }
2048:
2049: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2050: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2051: savm=oldm;
2052: oldm=newm;
2053: } /* end mult */
2054:
2055: s1=s[mw[mi][i]][i];
2056: s2=s[mw[mi+1][i]][i];
2057: if( s2 > nlstate){
2058: lli=log(out[s1][s2] - savm[s1][s2]);
2059: }else{
2060: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2061: }
2062: ipmx +=1;
2063: sw += weight[i];
2064: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2065: /* 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]); */
2066: } /* end of wave */
2067: } /* end of individual */
2068: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2069: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2070: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2071: for(mi=1; mi<= wav[i]-1; mi++){
2072: for (ii=1;ii<=nlstate+ndeath;ii++)
2073: for (j=1;j<=nlstate+ndeath;j++){
2074: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2075: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2076: }
2077: for(d=0; d<dh[mi][i]; d++){
2078: newm=savm;
2079: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2080: for (kk=1; kk<=cptcovage;kk++) {
2081: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2082: }
2083:
2084: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2085: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2086: savm=oldm;
2087: oldm=newm;
2088: } /* end mult */
2089:
2090: s1=s[mw[mi][i]][i];
2091: s2=s[mw[mi+1][i]][i];
2092: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2093: ipmx +=1;
2094: sw += weight[i];
2095: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2096: /*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]);*/
2097: } /* end of wave */
2098: } /* end of individual */
2099: } /* End of if */
2100: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2101: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2102: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2103: return -l;
2104: }
2105:
2106: /*************** log-likelihood *************/
2107: double funcone( double *x)
2108: {
2109: /* Same as likeli but slower because of a lot of printf and if */
2110: int i, ii, j, k, mi, d, kk;
1.131 brouard 2111: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2112: double **out;
2113: double lli; /* Individual log likelihood */
2114: double llt;
2115: int s1, s2;
2116: double bbh, survp;
2117: /*extern weight */
2118: /* We are differentiating ll according to initial status */
2119: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2120: /*for(i=1;i<imx;i++)
2121: printf(" %d\n",s[4][i]);
2122: */
2123: cov[1]=1.;
2124:
2125: for(k=1; k<=nlstate; k++) ll[k]=0.;
2126:
2127: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2128: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2129: for(mi=1; mi<= wav[i]-1; mi++){
2130: for (ii=1;ii<=nlstate+ndeath;ii++)
2131: for (j=1;j<=nlstate+ndeath;j++){
2132: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2133: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2134: }
2135: for(d=0; d<dh[mi][i]; d++){
2136: newm=savm;
2137: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2138: for (kk=1; kk<=cptcovage;kk++) {
2139: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2140: }
1.145 brouard 2141: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2142: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2143: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2144: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2145: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2146: savm=oldm;
2147: oldm=newm;
2148: } /* end mult */
2149:
2150: s1=s[mw[mi][i]][i];
2151: s2=s[mw[mi+1][i]][i];
2152: bbh=(double)bh[mi][i]/(double)stepm;
2153: /* bias is positive if real duration
2154: * is higher than the multiple of stepm and negative otherwise.
2155: */
2156: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2157: lli=log(out[s1][s2] - savm[s1][s2]);
2158: } else if (s2==-2) {
2159: for (j=1,survp=0. ; j<=nlstate; j++)
2160: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2161: lli= log(survp);
2162: }else if (mle==1){
2163: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2164: } else if(mle==2){
2165: 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 */
2166: } else if(mle==3){ /* exponential inter-extrapolation */
2167: 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 */
2168: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2169: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2170: } else{ /* mle=0 back to 1 */
2171: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2172: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2173: } /* End of if */
2174: ipmx +=1;
2175: sw += weight[i];
2176: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2177: /*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 2178: if(globpr){
1.141 brouard 2179: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2180: %11.6f %11.6f %11.6f ", \
2181: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2182: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2183: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2184: llt +=ll[k]*gipmx/gsw;
2185: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2186: }
2187: fprintf(ficresilk," %10.6f\n", -llt);
2188: }
2189: } /* end of wave */
2190: } /* end of individual */
2191: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2192: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2193: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2194: if(globpr==0){ /* First time we count the contributions and weights */
2195: gipmx=ipmx;
2196: gsw=sw;
2197: }
2198: return -l;
2199: }
2200:
2201:
2202: /*************** function likelione ***********/
2203: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2204: {
2205: /* This routine should help understanding what is done with
2206: the selection of individuals/waves and
2207: to check the exact contribution to the likelihood.
2208: Plotting could be done.
2209: */
2210: int k;
2211:
2212: if(*globpri !=0){ /* Just counts and sums, no printings */
2213: strcpy(fileresilk,"ilk");
2214: strcat(fileresilk,fileres);
2215: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2216: printf("Problem with resultfile: %s\n", fileresilk);
2217: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2218: }
2219: 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");
2220: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2221: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2222: for(k=1; k<=nlstate; k++)
2223: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2224: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2225: }
2226:
2227: *fretone=(*funcone)(p);
2228: if(*globpri !=0){
2229: fclose(ficresilk);
2230: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2231: fflush(fichtm);
2232: }
2233: return;
2234: }
2235:
2236:
2237: /*********** Maximum Likelihood Estimation ***************/
2238:
2239: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2240: {
1.165 brouard 2241: int i,j, iter=0;
1.126 brouard 2242: double **xi;
2243: double fret;
2244: double fretone; /* Only one call to likelihood */
2245: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2246:
2247: #ifdef NLOPT
2248: int creturn;
2249: nlopt_opt opt;
2250: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2251: double *lb;
2252: double minf; /* the minimum objective value, upon return */
2253: double * p1; /* Shifted parameters from 0 instead of 1 */
2254: myfunc_data dinst, *d = &dinst;
2255: #endif
2256:
2257:
1.126 brouard 2258: xi=matrix(1,npar,1,npar);
2259: for (i=1;i<=npar;i++)
2260: for (j=1;j<=npar;j++)
2261: xi[i][j]=(i==j ? 1.0 : 0.0);
2262: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2263: strcpy(filerespow,"pow");
2264: strcat(filerespow,fileres);
2265: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2266: printf("Problem with resultfile: %s\n", filerespow);
2267: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2268: }
2269: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2270: for (i=1;i<=nlstate;i++)
2271: for(j=1;j<=nlstate+ndeath;j++)
2272: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2273: fprintf(ficrespow,"\n");
1.162 brouard 2274: #ifdef POWELL
1.126 brouard 2275: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2276: #endif
1.126 brouard 2277:
1.162 brouard 2278: #ifdef NLOPT
2279: #ifdef NEWUOA
2280: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2281: #else
2282: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2283: #endif
2284: lb=vector(0,npar-1);
2285: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2286: nlopt_set_lower_bounds(opt, lb);
2287: nlopt_set_initial_step1(opt, 0.1);
2288:
2289: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2290: d->function = func;
2291: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2292: nlopt_set_min_objective(opt, myfunc, d);
2293: nlopt_set_xtol_rel(opt, ftol);
2294: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2295: printf("nlopt failed! %d\n",creturn);
2296: }
2297: else {
2298: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2299: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2300: iter=1; /* not equal */
2301: }
2302: nlopt_destroy(opt);
2303: #endif
1.126 brouard 2304: free_matrix(xi,1,npar,1,npar);
2305: fclose(ficrespow);
1.180 brouard 2306: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2307: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2308: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2309:
2310: }
2311:
2312: /**** Computes Hessian and covariance matrix ***/
2313: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2314: {
2315: double **a,**y,*x,pd;
2316: double **hess;
1.164 brouard 2317: int i, j;
1.126 brouard 2318: int *indx;
2319:
2320: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2321: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2322: void lubksb(double **a, int npar, int *indx, double b[]) ;
2323: void ludcmp(double **a, int npar, int *indx, double *d) ;
2324: double gompertz(double p[]);
2325: hess=matrix(1,npar,1,npar);
2326:
2327: printf("\nCalculation of the hessian matrix. Wait...\n");
2328: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2329: for (i=1;i<=npar;i++){
2330: printf("%d",i);fflush(stdout);
2331: fprintf(ficlog,"%d",i);fflush(ficlog);
2332:
2333: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2334:
2335: /* printf(" %f ",p[i]);
2336: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2337: }
2338:
2339: for (i=1;i<=npar;i++) {
2340: for (j=1;j<=npar;j++) {
2341: if (j>i) {
2342: printf(".%d%d",i,j);fflush(stdout);
2343: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2344: hess[i][j]=hessij(p,delti,i,j,func,npar);
2345:
2346: hess[j][i]=hess[i][j];
2347: /*printf(" %lf ",hess[i][j]);*/
2348: }
2349: }
2350: }
2351: printf("\n");
2352: fprintf(ficlog,"\n");
2353:
2354: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2355: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2356:
2357: a=matrix(1,npar,1,npar);
2358: y=matrix(1,npar,1,npar);
2359: x=vector(1,npar);
2360: indx=ivector(1,npar);
2361: for (i=1;i<=npar;i++)
2362: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2363: ludcmp(a,npar,indx,&pd);
2364:
2365: for (j=1;j<=npar;j++) {
2366: for (i=1;i<=npar;i++) x[i]=0;
2367: x[j]=1;
2368: lubksb(a,npar,indx,x);
2369: for (i=1;i<=npar;i++){
2370: matcov[i][j]=x[i];
2371: }
2372: }
2373:
2374: printf("\n#Hessian matrix#\n");
2375: fprintf(ficlog,"\n#Hessian matrix#\n");
2376: for (i=1;i<=npar;i++) {
2377: for (j=1;j<=npar;j++) {
2378: printf("%.3e ",hess[i][j]);
2379: fprintf(ficlog,"%.3e ",hess[i][j]);
2380: }
2381: printf("\n");
2382: fprintf(ficlog,"\n");
2383: }
2384:
2385: /* Recompute Inverse */
2386: for (i=1;i<=npar;i++)
2387: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2388: ludcmp(a,npar,indx,&pd);
2389:
2390: /* printf("\n#Hessian matrix recomputed#\n");
2391:
2392: for (j=1;j<=npar;j++) {
2393: for (i=1;i<=npar;i++) x[i]=0;
2394: x[j]=1;
2395: lubksb(a,npar,indx,x);
2396: for (i=1;i<=npar;i++){
2397: y[i][j]=x[i];
2398: printf("%.3e ",y[i][j]);
2399: fprintf(ficlog,"%.3e ",y[i][j]);
2400: }
2401: printf("\n");
2402: fprintf(ficlog,"\n");
2403: }
2404: */
2405:
2406: free_matrix(a,1,npar,1,npar);
2407: free_matrix(y,1,npar,1,npar);
2408: free_vector(x,1,npar);
2409: free_ivector(indx,1,npar);
2410: free_matrix(hess,1,npar,1,npar);
2411:
2412:
2413: }
2414:
2415: /*************** hessian matrix ****************/
2416: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2417: {
2418: int i;
2419: int l=1, lmax=20;
2420: double k1,k2;
1.132 brouard 2421: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2422: double res;
2423: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2424: double fx;
2425: int k=0,kmax=10;
2426: double l1;
2427:
2428: fx=func(x);
2429: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2430: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2431: l1=pow(10,l);
2432: delts=delt;
2433: for(k=1 ; k <kmax; k=k+1){
2434: delt = delta*(l1*k);
2435: p2[theta]=x[theta] +delt;
1.145 brouard 2436: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2437: p2[theta]=x[theta]-delt;
2438: k2=func(p2)-fx;
2439: /*res= (k1-2.0*fx+k2)/delt/delt; */
2440: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2441:
1.132 brouard 2442: #ifdef DEBUGHESS
1.126 brouard 2443: 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);
2444: 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);
2445: #endif
2446: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2447: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2448: k=kmax;
2449: }
2450: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2451: k=kmax; l=lmax*10;
1.126 brouard 2452: }
2453: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2454: delts=delt;
2455: }
2456: }
2457: }
2458: delti[theta]=delts;
2459: return res;
2460:
2461: }
2462:
2463: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2464: {
2465: int i;
1.164 brouard 2466: int l=1, lmax=20;
1.126 brouard 2467: double k1,k2,k3,k4,res,fx;
1.132 brouard 2468: double p2[MAXPARM+1];
1.126 brouard 2469: int k;
2470:
2471: fx=func(x);
2472: for (k=1; k<=2; k++) {
2473: for (i=1;i<=npar;i++) p2[i]=x[i];
2474: p2[thetai]=x[thetai]+delti[thetai]/k;
2475: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2476: k1=func(p2)-fx;
2477:
2478: p2[thetai]=x[thetai]+delti[thetai]/k;
2479: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2480: k2=func(p2)-fx;
2481:
2482: p2[thetai]=x[thetai]-delti[thetai]/k;
2483: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2484: k3=func(p2)-fx;
2485:
2486: p2[thetai]=x[thetai]-delti[thetai]/k;
2487: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2488: k4=func(p2)-fx;
2489: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2490: #ifdef DEBUG
2491: 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);
2492: 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);
2493: #endif
2494: }
2495: return res;
2496: }
2497:
2498: /************** Inverse of matrix **************/
2499: void ludcmp(double **a, int n, int *indx, double *d)
2500: {
2501: int i,imax,j,k;
2502: double big,dum,sum,temp;
2503: double *vv;
2504:
2505: vv=vector(1,n);
2506: *d=1.0;
2507: for (i=1;i<=n;i++) {
2508: big=0.0;
2509: for (j=1;j<=n;j++)
2510: if ((temp=fabs(a[i][j])) > big) big=temp;
2511: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2512: vv[i]=1.0/big;
2513: }
2514: for (j=1;j<=n;j++) {
2515: for (i=1;i<j;i++) {
2516: sum=a[i][j];
2517: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2518: a[i][j]=sum;
2519: }
2520: big=0.0;
2521: for (i=j;i<=n;i++) {
2522: sum=a[i][j];
2523: for (k=1;k<j;k++)
2524: sum -= a[i][k]*a[k][j];
2525: a[i][j]=sum;
2526: if ( (dum=vv[i]*fabs(sum)) >= big) {
2527: big=dum;
2528: imax=i;
2529: }
2530: }
2531: if (j != imax) {
2532: for (k=1;k<=n;k++) {
2533: dum=a[imax][k];
2534: a[imax][k]=a[j][k];
2535: a[j][k]=dum;
2536: }
2537: *d = -(*d);
2538: vv[imax]=vv[j];
2539: }
2540: indx[j]=imax;
2541: if (a[j][j] == 0.0) a[j][j]=TINY;
2542: if (j != n) {
2543: dum=1.0/(a[j][j]);
2544: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2545: }
2546: }
2547: free_vector(vv,1,n); /* Doesn't work */
2548: ;
2549: }
2550:
2551: void lubksb(double **a, int n, int *indx, double b[])
2552: {
2553: int i,ii=0,ip,j;
2554: double sum;
2555:
2556: for (i=1;i<=n;i++) {
2557: ip=indx[i];
2558: sum=b[ip];
2559: b[ip]=b[i];
2560: if (ii)
2561: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2562: else if (sum) ii=i;
2563: b[i]=sum;
2564: }
2565: for (i=n;i>=1;i--) {
2566: sum=b[i];
2567: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2568: b[i]=sum/a[i][i];
2569: }
2570: }
2571:
2572: void pstamp(FILE *fichier)
2573: {
2574: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2575: }
2576:
2577: /************ Frequencies ********************/
2578: 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[])
2579: { /* Some frequencies */
2580:
1.164 brouard 2581: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2582: int first;
2583: double ***freq; /* Frequencies */
2584: double *pp, **prop;
2585: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2586: char fileresp[FILENAMELENGTH];
2587:
2588: pp=vector(1,nlstate);
2589: prop=matrix(1,nlstate,iagemin,iagemax+3);
2590: strcpy(fileresp,"p");
2591: strcat(fileresp,fileres);
2592: if((ficresp=fopen(fileresp,"w"))==NULL) {
2593: printf("Problem with prevalence resultfile: %s\n", fileresp);
2594: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2595: exit(0);
2596: }
2597: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2598: j1=0;
2599:
2600: j=cptcoveff;
2601: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2602:
2603: first=1;
2604:
1.169 brouard 2605: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2606: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2607: /* j1++; */
1.145 brouard 2608: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2609: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2610: scanf("%d", i);*/
2611: for (i=-5; i<=nlstate+ndeath; i++)
2612: for (jk=-5; jk<=nlstate+ndeath; jk++)
2613: for(m=iagemin; m <= iagemax+3; m++)
2614: freq[i][jk][m]=0;
1.143 brouard 2615:
2616: for (i=1; i<=nlstate; i++)
2617: for(m=iagemin; m <= iagemax+3; m++)
2618: prop[i][m]=0;
1.126 brouard 2619:
2620: dateintsum=0;
2621: k2cpt=0;
2622: for (i=1; i<=imx; i++) {
2623: bool=1;
1.144 brouard 2624: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2625: for (z1=1; z1<=cptcoveff; z1++)
2626: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2627: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2628: bool=0;
1.145 brouard 2629: /* 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",
2630: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2631: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2632: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2633: }
1.126 brouard 2634: }
1.144 brouard 2635:
1.126 brouard 2636: if (bool==1){
2637: for(m=firstpass; m<=lastpass; m++){
2638: k2=anint[m][i]+(mint[m][i]/12.);
2639: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2640: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2641: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2642: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2643: if (m<lastpass) {
2644: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2645: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2646: }
2647:
2648: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2649: dateintsum=dateintsum+k2;
2650: k2cpt++;
2651: }
2652: /*}*/
2653: }
2654: }
1.145 brouard 2655: } /* end i */
1.126 brouard 2656:
2657: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2658: pstamp(ficresp);
2659: if (cptcovn>0) {
2660: fprintf(ficresp, "\n#********** Variable ");
2661: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2662: fprintf(ficresp, "**********\n#");
1.143 brouard 2663: fprintf(ficlog, "\n#********** Variable ");
2664: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2665: fprintf(ficlog, "**********\n#");
1.126 brouard 2666: }
2667: for(i=1; i<=nlstate;i++)
2668: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2669: fprintf(ficresp, "\n");
2670:
2671: for(i=iagemin; i <= iagemax+3; i++){
2672: if(i==iagemax+3){
2673: fprintf(ficlog,"Total");
2674: }else{
2675: if(first==1){
2676: first=0;
2677: printf("See log file for details...\n");
2678: }
2679: fprintf(ficlog,"Age %d", i);
2680: }
2681: for(jk=1; jk <=nlstate ; jk++){
2682: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2683: pp[jk] += freq[jk][m][i];
2684: }
2685: for(jk=1; jk <=nlstate ; jk++){
2686: for(m=-1, pos=0; m <=0 ; m++)
2687: pos += freq[jk][m][i];
2688: if(pp[jk]>=1.e-10){
2689: if(first==1){
1.132 brouard 2690: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2691: }
2692: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2693: }else{
2694: if(first==1)
2695: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2696: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2697: }
2698: }
2699:
2700: for(jk=1; jk <=nlstate ; jk++){
2701: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2702: pp[jk] += freq[jk][m][i];
2703: }
2704: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2705: pos += pp[jk];
2706: posprop += prop[jk][i];
2707: }
2708: for(jk=1; jk <=nlstate ; jk++){
2709: if(pos>=1.e-5){
2710: if(first==1)
2711: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2712: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2713: }else{
2714: if(first==1)
2715: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2716: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2717: }
2718: if( i <= iagemax){
2719: if(pos>=1.e-5){
2720: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2721: /*probs[i][jk][j1]= pp[jk]/pos;*/
2722: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2723: }
2724: else
2725: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2726: }
2727: }
2728:
2729: for(jk=-1; jk <=nlstate+ndeath; jk++)
2730: for(m=-1; m <=nlstate+ndeath; m++)
2731: if(freq[jk][m][i] !=0 ) {
2732: if(first==1)
2733: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2734: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2735: }
2736: if(i <= iagemax)
2737: fprintf(ficresp,"\n");
2738: if(first==1)
2739: printf("Others in log...\n");
2740: fprintf(ficlog,"\n");
2741: }
1.145 brouard 2742: /*}*/
1.126 brouard 2743: }
2744: dateintmean=dateintsum/k2cpt;
2745:
2746: fclose(ficresp);
2747: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2748: free_vector(pp,1,nlstate);
2749: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2750: /* End of Freq */
2751: }
2752:
2753: /************ Prevalence ********************/
2754: 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)
2755: {
2756: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2757: in each health status at the date of interview (if between dateprev1 and dateprev2).
2758: We still use firstpass and lastpass as another selection.
2759: */
2760:
1.164 brouard 2761: int i, m, jk, j1, bool, z1,j;
2762:
2763: double **prop;
2764: double posprop;
1.126 brouard 2765: double y2; /* in fractional years */
2766: int iagemin, iagemax;
1.145 brouard 2767: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2768:
2769: iagemin= (int) agemin;
2770: iagemax= (int) agemax;
2771: /*pp=vector(1,nlstate);*/
2772: prop=matrix(1,nlstate,iagemin,iagemax+3);
2773: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2774: j1=0;
2775:
1.145 brouard 2776: /*j=cptcoveff;*/
1.126 brouard 2777: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2778:
1.145 brouard 2779: first=1;
2780: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2781: /*for(i1=1; i1<=ncodemax[k1];i1++){
2782: j1++;*/
1.126 brouard 2783:
2784: for (i=1; i<=nlstate; i++)
2785: for(m=iagemin; m <= iagemax+3; m++)
2786: prop[i][m]=0.0;
2787:
2788: for (i=1; i<=imx; i++) { /* Each individual */
2789: bool=1;
2790: if (cptcovn>0) {
2791: for (z1=1; z1<=cptcoveff; z1++)
2792: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2793: bool=0;
2794: }
2795: if (bool==1) {
2796: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2797: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2798: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2799: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2800: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2801: 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);
2802: if (s[m][i]>0 && s[m][i]<=nlstate) {
2803: /*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]]);*/
2804: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2805: prop[s[m][i]][iagemax+3] += weight[i];
2806: }
2807: }
2808: } /* end selection of waves */
2809: }
2810: }
2811: for(i=iagemin; i <= iagemax+3; i++){
2812: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2813: posprop += prop[jk][i];
2814: }
1.145 brouard 2815:
1.126 brouard 2816: for(jk=1; jk <=nlstate ; jk++){
2817: if( i <= iagemax){
2818: if(posprop>=1.e-5){
2819: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2820: } else{
2821: if(first==1){
2822: first=0;
2823: 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]);
2824: }
2825: }
1.126 brouard 2826: }
2827: }/* end jk */
2828: }/* end i */
1.145 brouard 2829: /*} *//* end i1 */
2830: } /* end j1 */
1.126 brouard 2831:
2832: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2833: /*free_vector(pp,1,nlstate);*/
2834: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2835: } /* End of prevalence */
2836:
2837: /************* Waves Concatenation ***************/
2838:
2839: 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)
2840: {
2841: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2842: Death is a valid wave (if date is known).
2843: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2844: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2845: and mw[mi+1][i]. dh depends on stepm.
2846: */
2847:
2848: int i, mi, m;
2849: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2850: double sum=0., jmean=0.;*/
2851: int first;
2852: int j, k=0,jk, ju, jl;
2853: double sum=0.;
2854: first=0;
1.164 brouard 2855: jmin=100000;
1.126 brouard 2856: jmax=-1;
2857: jmean=0.;
2858: for(i=1; i<=imx; i++){
2859: mi=0;
2860: m=firstpass;
2861: while(s[m][i] <= nlstate){
2862: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2863: mw[++mi][i]=m;
2864: if(m >=lastpass)
2865: break;
2866: else
2867: m++;
2868: }/* end while */
2869: if (s[m][i] > nlstate){
2870: mi++; /* Death is another wave */
2871: /* if(mi==0) never been interviewed correctly before death */
2872: /* Only death is a correct wave */
2873: mw[mi][i]=m;
2874: }
2875:
2876: wav[i]=mi;
2877: if(mi==0){
2878: nbwarn++;
2879: if(first==0){
2880: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2881: first=1;
2882: }
2883: if(first==1){
2884: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2885: }
2886: } /* end mi==0 */
2887: } /* End individuals */
2888:
2889: for(i=1; i<=imx; i++){
2890: for(mi=1; mi<wav[i];mi++){
2891: if (stepm <=0)
2892: dh[mi][i]=1;
2893: else{
2894: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2895: if (agedc[i] < 2*AGESUP) {
2896: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2897: if(j==0) j=1; /* Survives at least one month after exam */
2898: else if(j<0){
2899: nberr++;
2900: 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]);
2901: j=1; /* Temporary Dangerous patch */
2902: 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);
2903: 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]);
2904: 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);
2905: }
2906: k=k+1;
2907: if (j >= jmax){
2908: jmax=j;
2909: ijmax=i;
2910: }
2911: if (j <= jmin){
2912: jmin=j;
2913: ijmin=i;
2914: }
2915: sum=sum+j;
2916: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2917: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2918: }
2919: }
2920: else{
2921: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2922: /* 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]); */
2923:
2924: k=k+1;
2925: if (j >= jmax) {
2926: jmax=j;
2927: ijmax=i;
2928: }
2929: else if (j <= jmin){
2930: jmin=j;
2931: ijmin=i;
2932: }
2933: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2934: /*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]);*/
2935: if(j<0){
2936: nberr++;
2937: 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]);
2938: 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]);
2939: }
2940: sum=sum+j;
2941: }
2942: jk= j/stepm;
2943: jl= j -jk*stepm;
2944: ju= j -(jk+1)*stepm;
2945: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2946: if(jl==0){
2947: dh[mi][i]=jk;
2948: bh[mi][i]=0;
2949: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2950: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2951: dh[mi][i]=jk+1;
2952: bh[mi][i]=ju;
2953: }
2954: }else{
2955: if(jl <= -ju){
2956: dh[mi][i]=jk;
2957: bh[mi][i]=jl; /* bias is positive if real duration
2958: * is higher than the multiple of stepm and negative otherwise.
2959: */
2960: }
2961: else{
2962: dh[mi][i]=jk+1;
2963: bh[mi][i]=ju;
2964: }
2965: if(dh[mi][i]==0){
2966: dh[mi][i]=1; /* At least one step */
2967: bh[mi][i]=ju; /* At least one step */
2968: /* 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);*/
2969: }
2970: } /* end if mle */
2971: }
2972: } /* end wave */
2973: }
2974: jmean=sum/k;
2975: 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 2976: 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 2977: }
2978:
2979: /*********** Tricode ****************************/
1.145 brouard 2980: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2981: {
1.144 brouard 2982: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2983: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
1.169 brouard 2984: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2985: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 2986: * nbcode[Tvar[j]][1]=
1.144 brouard 2987: */
1.130 brouard 2988:
1.145 brouard 2989: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2990: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2991: int cptcode=0; /* Modality max of covariates j */
2992: int modmincovj=0; /* Modality min of covariates j */
2993:
2994:
1.126 brouard 2995: cptcoveff=0;
2996:
1.145 brouard 2997: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2998: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2999:
1.145 brouard 3000: /* Loop on covariates without age and products */
3001: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
3002: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 3003: modality of this covariate Vj*/
1.145 brouard 3004: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3005: * If product of Vn*Vm, still boolean *:
3006: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3007: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3008: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3009: modality of the nth covariate of individual i. */
1.145 brouard 3010: if (ij > modmaxcovj)
3011: modmaxcovj=ij;
3012: else if (ij < modmincovj)
3013: modmincovj=ij;
3014: if ((ij < -1) && (ij > NCOVMAX)){
3015: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3016: exit(1);
3017: }else
1.136 brouard 3018: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3019: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3020: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3021: /* getting the maximum value of the modality of the covariate
3022: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3023: female is 1, then modmaxcovj=1.*/
1.126 brouard 3024: }
1.145 brouard 3025: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3026: cptcode=modmaxcovj;
1.137 brouard 3027: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3028: /*for (i=0; i<=cptcode; i++) {*/
3029: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3030: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3031: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3032: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3033: }
3034: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3035: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3036: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3037:
1.136 brouard 3038: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 3039: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3040: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3041: modmincovj=3; modmaxcovj = 7;
3042: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3043: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3044: variables V1_1 and V1_2.
3045: nbcode[Tvar[j]][ij]=k;
3046: nbcode[Tvar[j]][1]=0;
3047: nbcode[Tvar[j]][2]=1;
3048: nbcode[Tvar[j]][3]=2;
3049: */
3050: ij=1; /* ij is similar to i but can jumps over null modalities */
3051: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3052: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3053: /*recode from 0 */
1.131 brouard 3054: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3055: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3056: k is a modality. If we have model=V1+V1*sex
3057: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3058: ij++;
3059: }
3060: if (ij > ncodemax[j]) break;
1.137 brouard 3061: } /* end of loop on */
3062: } /* end of loop on modality */
3063: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3064:
1.145 brouard 3065: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3066:
1.145 brouard 3067: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3068: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3069: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3070: Ndum[ij]++;
3071: }
1.126 brouard 3072:
3073: ij=1;
1.145 brouard 3074: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3075: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3076: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3077: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3078: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3079: ij++;
1.145 brouard 3080: }else
3081: Tvaraff[ij]=0;
1.126 brouard 3082: }
1.131 brouard 3083: ij--;
1.144 brouard 3084: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3085:
1.126 brouard 3086: }
3087:
1.145 brouard 3088:
1.126 brouard 3089: /*********** Health Expectancies ****************/
3090:
1.127 brouard 3091: 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 3092:
3093: {
3094: /* Health expectancies, no variances */
1.164 brouard 3095: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3096: int nhstepma, nstepma; /* Decreasing with age */
3097: double age, agelim, hf;
3098: double ***p3mat;
3099: double eip;
3100:
3101: pstamp(ficreseij);
3102: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3103: fprintf(ficreseij,"# Age");
3104: for(i=1; i<=nlstate;i++){
3105: for(j=1; j<=nlstate;j++){
3106: fprintf(ficreseij," e%1d%1d ",i,j);
3107: }
3108: fprintf(ficreseij," e%1d. ",i);
3109: }
3110: fprintf(ficreseij,"\n");
3111:
3112:
3113: if(estepm < stepm){
3114: printf ("Problem %d lower than %d\n",estepm, stepm);
3115: }
3116: else hstepm=estepm;
3117: /* We compute the life expectancy from trapezoids spaced every estepm months
3118: * This is mainly to measure the difference between two models: for example
3119: * if stepm=24 months pijx are given only every 2 years and by summing them
3120: * we are calculating an estimate of the Life Expectancy assuming a linear
3121: * progression in between and thus overestimating or underestimating according
3122: * to the curvature of the survival function. If, for the same date, we
3123: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3124: * to compare the new estimate of Life expectancy with the same linear
3125: * hypothesis. A more precise result, taking into account a more precise
3126: * curvature will be obtained if estepm is as small as stepm. */
3127:
3128: /* For example we decided to compute the life expectancy with the smallest unit */
3129: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3130: nhstepm is the number of hstepm from age to agelim
3131: nstepm is the number of stepm from age to agelin.
3132: Look at hpijx to understand the reason of that which relies in memory size
3133: and note for a fixed period like estepm months */
3134: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3135: survival function given by stepm (the optimization length). Unfortunately it
3136: means that if the survival funtion is printed only each two years of age and if
3137: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3138: results. So we changed our mind and took the option of the best precision.
3139: */
3140: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3141:
3142: agelim=AGESUP;
3143: /* If stepm=6 months */
3144: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3145: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3146:
3147: /* nhstepm age range expressed in number of stepm */
3148: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3149: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3150: /* if (stepm >= YEARM) hstepm=1;*/
3151: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3152: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3153:
3154: for (age=bage; age<=fage; age ++){
3155: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3156: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3157: /* if (stepm >= YEARM) hstepm=1;*/
3158: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3159:
3160: /* If stepm=6 months */
3161: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3162: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3163:
3164: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3165:
3166: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3167:
3168: printf("%d|",(int)age);fflush(stdout);
3169: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3170:
3171: /* Computing expectancies */
3172: for(i=1; i<=nlstate;i++)
3173: for(j=1; j<=nlstate;j++)
3174: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3175: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3176:
3177: /* 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]);*/
3178:
3179: }
3180:
3181: fprintf(ficreseij,"%3.0f",age );
3182: for(i=1; i<=nlstate;i++){
3183: eip=0;
3184: for(j=1; j<=nlstate;j++){
3185: eip +=eij[i][j][(int)age];
3186: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3187: }
3188: fprintf(ficreseij,"%9.4f", eip );
3189: }
3190: fprintf(ficreseij,"\n");
3191:
3192: }
3193: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3194: printf("\n");
3195: fprintf(ficlog,"\n");
3196:
3197: }
3198:
1.127 brouard 3199: 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 3200:
3201: {
3202: /* Covariances of health expectancies eij and of total life expectancies according
3203: to initial status i, ei. .
3204: */
3205: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3206: int nhstepma, nstepma; /* Decreasing with age */
3207: double age, agelim, hf;
3208: double ***p3matp, ***p3matm, ***varhe;
3209: double **dnewm,**doldm;
3210: double *xp, *xm;
3211: double **gp, **gm;
3212: double ***gradg, ***trgradg;
3213: int theta;
3214:
3215: double eip, vip;
3216:
3217: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3218: xp=vector(1,npar);
3219: xm=vector(1,npar);
3220: dnewm=matrix(1,nlstate*nlstate,1,npar);
3221: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3222:
3223: pstamp(ficresstdeij);
3224: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3225: fprintf(ficresstdeij,"# Age");
3226: for(i=1; i<=nlstate;i++){
3227: for(j=1; j<=nlstate;j++)
3228: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3229: fprintf(ficresstdeij," e%1d. ",i);
3230: }
3231: fprintf(ficresstdeij,"\n");
3232:
3233: pstamp(ficrescveij);
3234: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3235: fprintf(ficrescveij,"# Age");
3236: for(i=1; i<=nlstate;i++)
3237: for(j=1; j<=nlstate;j++){
3238: cptj= (j-1)*nlstate+i;
3239: for(i2=1; i2<=nlstate;i2++)
3240: for(j2=1; j2<=nlstate;j2++){
3241: cptj2= (j2-1)*nlstate+i2;
3242: if(cptj2 <= cptj)
3243: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3244: }
3245: }
3246: fprintf(ficrescveij,"\n");
3247:
3248: if(estepm < stepm){
3249: printf ("Problem %d lower than %d\n",estepm, stepm);
3250: }
3251: else hstepm=estepm;
3252: /* We compute the life expectancy from trapezoids spaced every estepm months
3253: * This is mainly to measure the difference between two models: for example
3254: * if stepm=24 months pijx are given only every 2 years and by summing them
3255: * we are calculating an estimate of the Life Expectancy assuming a linear
3256: * progression in between and thus overestimating or underestimating according
3257: * to the curvature of the survival function. If, for the same date, we
3258: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3259: * to compare the new estimate of Life expectancy with the same linear
3260: * hypothesis. A more precise result, taking into account a more precise
3261: * curvature will be obtained if estepm is as small as stepm. */
3262:
3263: /* For example we decided to compute the life expectancy with the smallest unit */
3264: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3265: nhstepm is the number of hstepm from age to agelim
3266: nstepm is the number of stepm from age to agelin.
3267: Look at hpijx to understand the reason of that which relies in memory size
3268: and note for a fixed period like estepm months */
3269: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3270: survival function given by stepm (the optimization length). Unfortunately it
3271: means that if the survival funtion is printed only each two years of age and if
3272: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3273: results. So we changed our mind and took the option of the best precision.
3274: */
3275: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3276:
3277: /* If stepm=6 months */
3278: /* nhstepm age range expressed in number of stepm */
3279: agelim=AGESUP;
3280: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3281: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3282: /* if (stepm >= YEARM) hstepm=1;*/
3283: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3284:
3285: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3286: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3287: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3288: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3289: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3290: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3291:
3292: for (age=bage; age<=fage; age ++){
3293: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3294: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3295: /* if (stepm >= YEARM) hstepm=1;*/
3296: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3297:
3298: /* If stepm=6 months */
3299: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3300: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3301:
3302: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3303:
3304: /* Computing Variances of health expectancies */
3305: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3306: decrease memory allocation */
3307: for(theta=1; theta <=npar; theta++){
3308: for(i=1; i<=npar; i++){
3309: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3310: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3311: }
3312: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3313: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3314:
3315: for(j=1; j<= nlstate; j++){
3316: for(i=1; i<=nlstate; i++){
3317: for(h=0; h<=nhstepm-1; h++){
3318: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3319: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3320: }
3321: }
3322: }
3323:
3324: for(ij=1; ij<= nlstate*nlstate; ij++)
3325: for(h=0; h<=nhstepm-1; h++){
3326: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3327: }
3328: }/* End theta */
3329:
3330:
3331: for(h=0; h<=nhstepm-1; h++)
3332: for(j=1; j<=nlstate*nlstate;j++)
3333: for(theta=1; theta <=npar; theta++)
3334: trgradg[h][j][theta]=gradg[h][theta][j];
3335:
3336:
3337: for(ij=1;ij<=nlstate*nlstate;ij++)
3338: for(ji=1;ji<=nlstate*nlstate;ji++)
3339: varhe[ij][ji][(int)age] =0.;
3340:
3341: printf("%d|",(int)age);fflush(stdout);
3342: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3343: for(h=0;h<=nhstepm-1;h++){
3344: for(k=0;k<=nhstepm-1;k++){
3345: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3346: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3347: for(ij=1;ij<=nlstate*nlstate;ij++)
3348: for(ji=1;ji<=nlstate*nlstate;ji++)
3349: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3350: }
3351: }
3352:
3353: /* Computing expectancies */
3354: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3355: for(i=1; i<=nlstate;i++)
3356: for(j=1; j<=nlstate;j++)
3357: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3358: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3359:
3360: /* 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]);*/
3361:
3362: }
3363:
3364: fprintf(ficresstdeij,"%3.0f",age );
3365: for(i=1; i<=nlstate;i++){
3366: eip=0.;
3367: vip=0.;
3368: for(j=1; j<=nlstate;j++){
3369: eip += eij[i][j][(int)age];
3370: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3371: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3372: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3373: }
3374: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3375: }
3376: fprintf(ficresstdeij,"\n");
3377:
3378: fprintf(ficrescveij,"%3.0f",age );
3379: for(i=1; i<=nlstate;i++)
3380: for(j=1; j<=nlstate;j++){
3381: cptj= (j-1)*nlstate+i;
3382: for(i2=1; i2<=nlstate;i2++)
3383: for(j2=1; j2<=nlstate;j2++){
3384: cptj2= (j2-1)*nlstate+i2;
3385: if(cptj2 <= cptj)
3386: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3387: }
3388: }
3389: fprintf(ficrescveij,"\n");
3390:
3391: }
3392: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3393: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3394: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3395: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3396: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3397: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3398: printf("\n");
3399: fprintf(ficlog,"\n");
3400:
3401: free_vector(xm,1,npar);
3402: free_vector(xp,1,npar);
3403: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3404: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3405: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3406: }
3407:
3408: /************ Variance ******************/
3409: 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[])
3410: {
3411: /* Variance of health expectancies */
3412: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3413: /* double **newm;*/
1.169 brouard 3414: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3415:
3416: int movingaverage();
1.126 brouard 3417: double **dnewm,**doldm;
3418: double **dnewmp,**doldmp;
3419: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3420: int k;
1.126 brouard 3421: double *xp;
3422: double **gp, **gm; /* for var eij */
3423: double ***gradg, ***trgradg; /*for var eij */
3424: double **gradgp, **trgradgp; /* for var p point j */
3425: double *gpp, *gmp; /* for var p point j */
3426: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3427: double ***p3mat;
3428: double age,agelim, hf;
3429: double ***mobaverage;
3430: int theta;
3431: char digit[4];
3432: char digitp[25];
3433:
3434: char fileresprobmorprev[FILENAMELENGTH];
3435:
3436: if(popbased==1){
3437: if(mobilav!=0)
3438: strcpy(digitp,"-populbased-mobilav-");
3439: else strcpy(digitp,"-populbased-nomobil-");
3440: }
3441: else
3442: strcpy(digitp,"-stablbased-");
3443:
3444: if (mobilav!=0) {
3445: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3446: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3447: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3448: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3449: }
3450: }
3451:
3452: strcpy(fileresprobmorprev,"prmorprev");
3453: sprintf(digit,"%-d",ij);
3454: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3455: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3456: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3457: strcat(fileresprobmorprev,fileres);
3458: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3459: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3460: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3461: }
3462: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3463:
3464: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3465: pstamp(ficresprobmorprev);
3466: 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);
3467: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3468: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3469: fprintf(ficresprobmorprev," p.%-d SE",j);
3470: for(i=1; i<=nlstate;i++)
3471: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3472: }
3473: fprintf(ficresprobmorprev,"\n");
3474: fprintf(ficgp,"\n# Routine varevsij");
3475: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3476: 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");
3477: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3478: /* } */
3479: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3480: pstamp(ficresvij);
3481: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3482: if(popbased==1)
1.128 brouard 3483: 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 3484: else
3485: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3486: fprintf(ficresvij,"# Age");
3487: for(i=1; i<=nlstate;i++)
3488: for(j=1; j<=nlstate;j++)
3489: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3490: fprintf(ficresvij,"\n");
3491:
3492: xp=vector(1,npar);
3493: dnewm=matrix(1,nlstate,1,npar);
3494: doldm=matrix(1,nlstate,1,nlstate);
3495: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3496: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3497:
3498: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3499: gpp=vector(nlstate+1,nlstate+ndeath);
3500: gmp=vector(nlstate+1,nlstate+ndeath);
3501: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3502:
3503: if(estepm < stepm){
3504: printf ("Problem %d lower than %d\n",estepm, stepm);
3505: }
3506: else hstepm=estepm;
3507: /* For example we decided to compute the life expectancy with the smallest unit */
3508: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3509: nhstepm is the number of hstepm from age to agelim
3510: nstepm is the number of stepm from age to agelin.
1.128 brouard 3511: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3512: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3513: survival function given by stepm (the optimization length). Unfortunately it
3514: means that if the survival funtion is printed every two years of age and if
3515: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3516: results. So we changed our mind and took the option of the best precision.
3517: */
3518: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3519: agelim = AGESUP;
3520: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3521: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3522: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3523: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3524: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3525: gp=matrix(0,nhstepm,1,nlstate);
3526: gm=matrix(0,nhstepm,1,nlstate);
3527:
3528:
3529: for(theta=1; theta <=npar; theta++){
3530: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3531: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3532: }
3533: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3534: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3535:
3536: if (popbased==1) {
3537: if(mobilav ==0){
3538: for(i=1; i<=nlstate;i++)
3539: prlim[i][i]=probs[(int)age][i][ij];
3540: }else{ /* mobilav */
3541: for(i=1; i<=nlstate;i++)
3542: prlim[i][i]=mobaverage[(int)age][i][ij];
3543: }
3544: }
3545:
3546: for(j=1; j<= nlstate; j++){
3547: for(h=0; h<=nhstepm; h++){
3548: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3549: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3550: }
3551: }
3552: /* This for computing probability of death (h=1 means
3553: computed over hstepm matrices product = hstepm*stepm months)
3554: as a weighted average of prlim.
3555: */
3556: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3557: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3558: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3559: }
3560: /* end probability of death */
3561:
3562: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3563: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3564: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3565: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3566:
3567: if (popbased==1) {
3568: if(mobilav ==0){
3569: for(i=1; i<=nlstate;i++)
3570: prlim[i][i]=probs[(int)age][i][ij];
3571: }else{ /* mobilav */
3572: for(i=1; i<=nlstate;i++)
3573: prlim[i][i]=mobaverage[(int)age][i][ij];
3574: }
3575: }
3576:
1.128 brouard 3577: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3578: for(h=0; h<=nhstepm; h++){
3579: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3580: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3581: }
3582: }
3583: /* This for computing probability of death (h=1 means
3584: computed over hstepm matrices product = hstepm*stepm months)
3585: as a weighted average of prlim.
3586: */
3587: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3588: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3589: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3590: }
3591: /* end probability of death */
3592:
3593: for(j=1; j<= nlstate; j++) /* vareij */
3594: for(h=0; h<=nhstepm; h++){
3595: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3596: }
3597:
3598: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3599: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3600: }
3601:
3602: } /* End theta */
3603:
3604: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3605:
3606: for(h=0; h<=nhstepm; h++) /* veij */
3607: for(j=1; j<=nlstate;j++)
3608: for(theta=1; theta <=npar; theta++)
3609: trgradg[h][j][theta]=gradg[h][theta][j];
3610:
3611: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3612: for(theta=1; theta <=npar; theta++)
3613: trgradgp[j][theta]=gradgp[theta][j];
3614:
3615:
3616: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3617: for(i=1;i<=nlstate;i++)
3618: for(j=1;j<=nlstate;j++)
3619: vareij[i][j][(int)age] =0.;
3620:
3621: for(h=0;h<=nhstepm;h++){
3622: for(k=0;k<=nhstepm;k++){
3623: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3624: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3625: for(i=1;i<=nlstate;i++)
3626: for(j=1;j<=nlstate;j++)
3627: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3628: }
3629: }
3630:
3631: /* pptj */
3632: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3633: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3634: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3635: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3636: varppt[j][i]=doldmp[j][i];
3637: /* end ppptj */
3638: /* x centered again */
3639: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3640: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3641:
3642: if (popbased==1) {
3643: if(mobilav ==0){
3644: for(i=1; i<=nlstate;i++)
3645: prlim[i][i]=probs[(int)age][i][ij];
3646: }else{ /* mobilav */
3647: for(i=1; i<=nlstate;i++)
3648: prlim[i][i]=mobaverage[(int)age][i][ij];
3649: }
3650: }
3651:
3652: /* This for computing probability of death (h=1 means
3653: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3654: as a weighted average of prlim.
3655: */
3656: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3657: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3658: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3659: }
3660: /* end probability of death */
3661:
3662: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3663: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3664: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3665: for(i=1; i<=nlstate;i++){
3666: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3667: }
3668: }
3669: fprintf(ficresprobmorprev,"\n");
3670:
3671: fprintf(ficresvij,"%.0f ",age );
3672: for(i=1; i<=nlstate;i++)
3673: for(j=1; j<=nlstate;j++){
3674: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3675: }
3676: fprintf(ficresvij,"\n");
3677: free_matrix(gp,0,nhstepm,1,nlstate);
3678: free_matrix(gm,0,nhstepm,1,nlstate);
3679: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3680: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3681: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3682: } /* End age */
3683: free_vector(gpp,nlstate+1,nlstate+ndeath);
3684: free_vector(gmp,nlstate+1,nlstate+ndeath);
3685: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3686: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3687: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3688: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3689: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3690: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3691: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3692: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3693: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3694: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3695: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3696: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3697: 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);
3698: /* 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);
3699: */
3700: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3701: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3702:
3703: free_vector(xp,1,npar);
3704: free_matrix(doldm,1,nlstate,1,nlstate);
3705: free_matrix(dnewm,1,nlstate,1,npar);
3706: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3707: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3708: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3709: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3710: fclose(ficresprobmorprev);
3711: fflush(ficgp);
3712: fflush(fichtm);
3713: } /* end varevsij */
3714:
3715: /************ Variance of prevlim ******************/
3716: 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[])
3717: {
3718: /* Variance of prevalence limit */
3719: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3720:
1.126 brouard 3721: double **dnewm,**doldm;
3722: int i, j, nhstepm, hstepm;
3723: double *xp;
3724: double *gp, *gm;
3725: double **gradg, **trgradg;
3726: double age,agelim;
3727: int theta;
3728:
3729: pstamp(ficresvpl);
3730: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3731: fprintf(ficresvpl,"# Age");
3732: for(i=1; i<=nlstate;i++)
3733: fprintf(ficresvpl," %1d-%1d",i,i);
3734: fprintf(ficresvpl,"\n");
3735:
3736: xp=vector(1,npar);
3737: dnewm=matrix(1,nlstate,1,npar);
3738: doldm=matrix(1,nlstate,1,nlstate);
3739:
3740: hstepm=1*YEARM; /* Every year of age */
3741: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3742: agelim = AGESUP;
3743: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3744: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3745: if (stepm >= YEARM) hstepm=1;
3746: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3747: gradg=matrix(1,npar,1,nlstate);
3748: gp=vector(1,nlstate);
3749: gm=vector(1,nlstate);
3750:
3751: for(theta=1; theta <=npar; theta++){
3752: for(i=1; i<=npar; i++){ /* Computes gradient */
3753: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3754: }
3755: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3756: for(i=1;i<=nlstate;i++)
3757: gp[i] = prlim[i][i];
3758:
3759: for(i=1; i<=npar; i++) /* Computes gradient */
3760: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3761: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3762: for(i=1;i<=nlstate;i++)
3763: gm[i] = prlim[i][i];
3764:
3765: for(i=1;i<=nlstate;i++)
3766: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3767: } /* End theta */
3768:
3769: trgradg =matrix(1,nlstate,1,npar);
3770:
3771: for(j=1; j<=nlstate;j++)
3772: for(theta=1; theta <=npar; theta++)
3773: trgradg[j][theta]=gradg[theta][j];
3774:
3775: for(i=1;i<=nlstate;i++)
3776: varpl[i][(int)age] =0.;
3777: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3778: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3779: for(i=1;i<=nlstate;i++)
3780: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3781:
3782: fprintf(ficresvpl,"%.0f ",age );
3783: for(i=1; i<=nlstate;i++)
3784: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3785: fprintf(ficresvpl,"\n");
3786: free_vector(gp,1,nlstate);
3787: free_vector(gm,1,nlstate);
3788: free_matrix(gradg,1,npar,1,nlstate);
3789: free_matrix(trgradg,1,nlstate,1,npar);
3790: } /* End age */
3791:
3792: free_vector(xp,1,npar);
3793: free_matrix(doldm,1,nlstate,1,npar);
3794: free_matrix(dnewm,1,nlstate,1,nlstate);
3795:
3796: }
3797:
3798: /************ Variance of one-step probabilities ******************/
3799: 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[])
3800: {
1.164 brouard 3801: int i, j=0, k1, l1, tj;
1.126 brouard 3802: int k2, l2, j1, z1;
1.164 brouard 3803: int k=0, l;
1.145 brouard 3804: int first=1, first1, first2;
1.126 brouard 3805: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3806: double **dnewm,**doldm;
3807: double *xp;
3808: double *gp, *gm;
3809: double **gradg, **trgradg;
3810: double **mu;
1.164 brouard 3811: double age, cov[NCOVMAX+1];
1.126 brouard 3812: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3813: int theta;
3814: char fileresprob[FILENAMELENGTH];
3815: char fileresprobcov[FILENAMELENGTH];
3816: char fileresprobcor[FILENAMELENGTH];
3817: double ***varpij;
3818:
3819: strcpy(fileresprob,"prob");
3820: strcat(fileresprob,fileres);
3821: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3822: printf("Problem with resultfile: %s\n", fileresprob);
3823: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3824: }
3825: strcpy(fileresprobcov,"probcov");
3826: strcat(fileresprobcov,fileres);
3827: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3828: printf("Problem with resultfile: %s\n", fileresprobcov);
3829: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3830: }
3831: strcpy(fileresprobcor,"probcor");
3832: strcat(fileresprobcor,fileres);
3833: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3834: printf("Problem with resultfile: %s\n", fileresprobcor);
3835: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3836: }
3837: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3838: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3839: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3840: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3841: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3842: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3843: pstamp(ficresprob);
3844: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3845: fprintf(ficresprob,"# Age");
3846: pstamp(ficresprobcov);
3847: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3848: fprintf(ficresprobcov,"# Age");
3849: pstamp(ficresprobcor);
3850: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3851: fprintf(ficresprobcor,"# Age");
3852:
3853:
3854: for(i=1; i<=nlstate;i++)
3855: for(j=1; j<=(nlstate+ndeath);j++){
3856: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3857: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3858: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3859: }
3860: /* fprintf(ficresprob,"\n");
3861: fprintf(ficresprobcov,"\n");
3862: fprintf(ficresprobcor,"\n");
3863: */
1.131 brouard 3864: xp=vector(1,npar);
1.126 brouard 3865: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3866: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3867: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3868: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3869: first=1;
3870: fprintf(ficgp,"\n# Routine varprob");
3871: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3872: fprintf(fichtm,"\n");
3873:
3874: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3875: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3876: file %s<br>\n",optionfilehtmcov);
3877: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3878: and drawn. It helps understanding how is the covariance between two incidences.\
3879: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3880: 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. \
3881: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3882: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3883: standard deviations wide on each axis. <br>\
3884: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3885: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3886: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3887:
3888: cov[1]=1;
1.145 brouard 3889: /* tj=cptcoveff; */
3890: tj = (int) pow(2,cptcoveff);
1.126 brouard 3891: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3892: j1=0;
1.145 brouard 3893: for(j1=1; j1<=tj;j1++){
3894: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3895: /*j1++;*/
1.126 brouard 3896: if (cptcovn>0) {
3897: fprintf(ficresprob, "\n#********** Variable ");
3898: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3899: fprintf(ficresprob, "**********\n#\n");
3900: fprintf(ficresprobcov, "\n#********** Variable ");
3901: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3902: fprintf(ficresprobcov, "**********\n#\n");
3903:
3904: fprintf(ficgp, "\n#********** Variable ");
3905: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3906: fprintf(ficgp, "**********\n#\n");
3907:
3908:
3909: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3910: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3911: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3912:
3913: fprintf(ficresprobcor, "\n#********** Variable ");
3914: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3915: fprintf(ficresprobcor, "**********\n#");
3916: }
3917:
1.145 brouard 3918: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3919: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3920: gp=vector(1,(nlstate)*(nlstate+ndeath));
3921: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3922: for (age=bage; age<=fage; age ++){
3923: cov[2]=age;
3924: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3925: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3926: * 1 1 1 1 1
3927: * 2 2 1 1 1
3928: * 3 1 2 1 1
3929: */
3930: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3931: }
3932: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3933: for (k=1; k<=cptcovprod;k++)
3934: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3935:
3936:
3937: for(theta=1; theta <=npar; theta++){
3938: for(i=1; i<=npar; i++)
3939: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3940:
3941: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3942:
3943: k=0;
3944: for(i=1; i<= (nlstate); i++){
3945: for(j=1; j<=(nlstate+ndeath);j++){
3946: k=k+1;
3947: gp[k]=pmmij[i][j];
3948: }
3949: }
3950:
3951: for(i=1; i<=npar; i++)
3952: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3953:
3954: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3955: k=0;
3956: for(i=1; i<=(nlstate); i++){
3957: for(j=1; j<=(nlstate+ndeath);j++){
3958: k=k+1;
3959: gm[k]=pmmij[i][j];
3960: }
3961: }
3962:
3963: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3964: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3965: }
3966:
3967: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3968: for(theta=1; theta <=npar; theta++)
3969: trgradg[j][theta]=gradg[theta][j];
3970:
3971: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3972: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3973:
3974: pmij(pmmij,cov,ncovmodel,x,nlstate);
3975:
3976: k=0;
3977: for(i=1; i<=(nlstate); i++){
3978: for(j=1; j<=(nlstate+ndeath);j++){
3979: k=k+1;
3980: mu[k][(int) age]=pmmij[i][j];
3981: }
3982: }
3983: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3984: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3985: varpij[i][j][(int)age] = doldm[i][j];
3986:
3987: /*printf("\n%d ",(int)age);
3988: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3989: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3990: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3991: }*/
3992:
3993: fprintf(ficresprob,"\n%d ",(int)age);
3994: fprintf(ficresprobcov,"\n%d ",(int)age);
3995: fprintf(ficresprobcor,"\n%d ",(int)age);
3996:
3997: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3998: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3999: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4000: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4001: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4002: }
4003: i=0;
4004: for (k=1; k<=(nlstate);k++){
4005: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4006: i++;
1.126 brouard 4007: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4008: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4009: for (j=1; j<=i;j++){
1.145 brouard 4010: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4011: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4012: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4013: }
4014: }
4015: }/* end of loop for state */
4016: } /* end of loop for age */
1.145 brouard 4017: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4018: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4019: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4020: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4021:
1.126 brouard 4022: /* Confidence intervalle of pij */
4023: /*
1.131 brouard 4024: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4025: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4026: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4027: 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);
4028: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4029: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4030: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4031: */
4032:
4033: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4034: first1=1;first2=2;
1.126 brouard 4035: for (k2=1; k2<=(nlstate);k2++){
4036: for (l2=1; l2<=(nlstate+ndeath);l2++){
4037: if(l2==k2) continue;
4038: j=(k2-1)*(nlstate+ndeath)+l2;
4039: for (k1=1; k1<=(nlstate);k1++){
4040: for (l1=1; l1<=(nlstate+ndeath);l1++){
4041: if(l1==k1) continue;
4042: i=(k1-1)*(nlstate+ndeath)+l1;
4043: if(i<=j) continue;
4044: for (age=bage; age<=fage; age ++){
4045: if ((int)age %5==0){
4046: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4047: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4048: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4049: mu1=mu[i][(int) age]/stepm*YEARM ;
4050: mu2=mu[j][(int) age]/stepm*YEARM;
4051: c12=cv12/sqrt(v1*v2);
4052: /* Computing eigen value of matrix of covariance */
4053: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4054: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4055: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4056: if(first2==1){
4057: first1=0;
4058: 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);
4059: }
4060: 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);
4061: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4062: /* lc2=fabs(lc2); */
1.135 brouard 4063: }
4064:
1.126 brouard 4065: /* Eigen vectors */
4066: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4067: /*v21=sqrt(1.-v11*v11); *//* error */
4068: v21=(lc1-v1)/cv12*v11;
4069: v12=-v21;
4070: v22=v11;
4071: tnalp=v21/v11;
4072: if(first1==1){
4073: first1=0;
4074: 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);
4075: }
4076: 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);
4077: /*printf(fignu*/
4078: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4079: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4080: if(first==1){
4081: first=0;
4082: fprintf(ficgp,"\nset parametric;unset label");
4083: 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 4084: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4085: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4086: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4087: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4088: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4089: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4090: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4091: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4092: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4093: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4094: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4095: 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",\
4096: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4097: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4098: }else{
4099: first=0;
4100: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4101: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4102: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4103: 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",\
4104: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4105: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4106: }/* if first */
4107: } /* age mod 5 */
4108: } /* end loop age */
4109: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4110: first=1;
4111: } /*l12 */
4112: } /* k12 */
4113: } /*l1 */
4114: }/* k1 */
1.169 brouard 4115: /* } */ /* loop covariates */
1.126 brouard 4116: }
4117: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4118: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4119: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4120: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4121: free_vector(xp,1,npar);
4122: fclose(ficresprob);
4123: fclose(ficresprobcov);
4124: fclose(ficresprobcor);
4125: fflush(ficgp);
4126: fflush(fichtmcov);
4127: }
4128:
4129:
4130: /******************* Printing html file ***********/
4131: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4132: int lastpass, int stepm, int weightopt, char model[],\
4133: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4134: int popforecast, int estepm ,\
4135: double jprev1, double mprev1,double anprev1, \
4136: double jprev2, double mprev2,double anprev2){
4137: int jj1, k1, i1, cpt;
4138:
4139: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4140: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4141: </ul>");
4142: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4143: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4144: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4145: fprintf(fichtm,"\
4146: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4147: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4148: fprintf(fichtm,"\
4149: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4150: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4151: fprintf(fichtm,"\
1.128 brouard 4152: - (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 4153: <a href=\"%s\">%s</a> <br>\n",
4154: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4155: fprintf(fichtm,"\
4156: - Population projections by age and states: \
4157: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4158:
4159: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4160:
1.145 brouard 4161: m=pow(2,cptcoveff);
1.126 brouard 4162: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4163:
4164: jj1=0;
4165: for(k1=1; k1<=m;k1++){
4166: for(i1=1; i1<=ncodemax[k1];i1++){
4167: jj1++;
4168: if (cptcovn > 0) {
4169: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4170: for (cpt=1; cpt<=cptcoveff;cpt++)
4171: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4172: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4173: }
4174: /* Pij */
1.145 brouard 4175: 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> \
4176: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4177: /* Quasi-incidences */
4178: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4179: 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> \
4180: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4181: /* Period (stable) prevalence in each health state */
1.154 brouard 4182: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4183: fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
4184: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126 brouard 4185: }
4186: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4187: 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> \
4188: <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 4189: }
4190: } /* end i1 */
4191: }/* End k1 */
4192: fprintf(fichtm,"</ul>");
4193:
4194:
4195: fprintf(fichtm,"\
4196: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4197: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4198:
4199: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4200: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4201: fprintf(fichtm,"\
4202: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4203: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4204:
4205: fprintf(fichtm,"\
4206: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4207: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4208: fprintf(fichtm,"\
4209: - 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): \
4210: <a href=\"%s\">%s</a> <br>\n</li>",
4211: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4212: fprintf(fichtm,"\
4213: - (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): \
4214: <a href=\"%s\">%s</a> <br>\n</li>",
4215: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4216: fprintf(fichtm,"\
1.128 brouard 4217: - 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 4218: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4219: fprintf(fichtm,"\
1.128 brouard 4220: - 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",
4221: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4222: fprintf(fichtm,"\
4223: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4224: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4225:
4226: /* if(popforecast==1) fprintf(fichtm,"\n */
4227: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4228: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4229: /* <br>",fileres,fileres,fileres,fileres); */
4230: /* else */
4231: /* 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); */
4232: fflush(fichtm);
4233: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4234:
1.145 brouard 4235: m=pow(2,cptcoveff);
1.126 brouard 4236: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4237:
4238: jj1=0;
4239: for(k1=1; k1<=m;k1++){
4240: for(i1=1; i1<=ncodemax[k1];i1++){
4241: jj1++;
4242: if (cptcovn > 0) {
4243: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4244: for (cpt=1; cpt<=cptcoveff;cpt++)
4245: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4246: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4247: }
4248: for(cpt=1; cpt<=nlstate;cpt++) {
4249: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4250: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4251: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4252: }
4253: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4254: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4255: true period expectancies (those weighted with period prevalences are also\
4256: drawn in addition to the population based expectancies computed using\
4257: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4258: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4259: } /* end i1 */
4260: }/* End k1 */
4261: fprintf(fichtm,"</ul>");
4262: fflush(fichtm);
4263: }
4264:
4265: /******************* Gnuplot file **************/
4266: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4267:
4268: char dirfileres[132],optfileres[132];
1.164 brouard 4269: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4270: int ng=0;
1.126 brouard 4271: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4272: /* printf("Problem with file %s",optionfilegnuplot); */
4273: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4274: /* } */
4275:
4276: /*#ifdef windows */
4277: fprintf(ficgp,"cd \"%s\" \n",pathc);
4278: /*#endif */
4279: m=pow(2,cptcoveff);
4280:
4281: strcpy(dirfileres,optionfilefiname);
4282: strcpy(optfileres,"vpl");
4283: /* 1eme*/
1.153 brouard 4284: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4285: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4286: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4287: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4288: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4289: fprintf(ficgp,"set xlabel \"Age\" \n\
4290: set ylabel \"Probability\" \n\
1.145 brouard 4291: set ter png small size 320, 240\n\
1.170 brouard 4292: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4293:
4294: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4295: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4296: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4297: }
1.170 brouard 4298: 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 4299: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4300: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4301: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4302: }
1.170 brouard 4303: 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 4304: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4305: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4306: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4307: }
1.145 brouard 4308: 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 4309: }
4310: }
4311: /*2 eme*/
1.153 brouard 4312: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4313: for (k1=1; k1<= m ; k1 ++) {
4314: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4315: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4316:
4317: for (i=1; i<= nlstate+1 ; i ++) {
4318: k=2*i;
1.170 brouard 4319: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4320: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4321: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4322: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4323: }
4324: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4325: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4326: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4327: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4328: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4329: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4330: }
1.145 brouard 4331: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4332: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4333: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4334: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4335: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4336: }
1.145 brouard 4337: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4338: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4339: }
4340: }
4341:
4342: /*3eme*/
4343:
4344: for (k1=1; k1<= m ; k1 ++) {
4345: for (cpt=1; cpt<= nlstate ; cpt ++) {
4346: /* k=2+nlstate*(2*cpt-2); */
4347: k=2+(nlstate+1)*(cpt-1);
4348: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4349: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4350: 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);
4351: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4352: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4353: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4354: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4355: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4356: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4357:
4358: */
4359: for (i=1; i< nlstate ; i ++) {
4360: 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);
4361: /* 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);*/
4362:
4363: }
4364: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4365: }
4366: }
4367:
4368: /* CV preval stable (period) */
1.153 brouard 4369: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4370: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4371: k=3;
1.153 brouard 4372: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4373: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4374: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4375: set ter png small size 320, 240\n\
1.126 brouard 4376: unset log y\n\
1.153 brouard 4377: plot [%.f:%.f] ", ageminpar, agemaxpar);
4378: for (i=1; i<= nlstate ; i ++){
4379: if(i==1)
4380: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4381: else
4382: fprintf(ficgp,", '' ");
1.154 brouard 4383: l=(nlstate+ndeath)*(i-1)+1;
4384: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4385: for (j=1; j<= (nlstate-1) ; j ++)
4386: fprintf(ficgp,"+$%d",k+l+j);
4387: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4388: } /* nlstate */
4389: fprintf(ficgp,"\n");
4390: } /* end cpt state*/
4391: } /* end covariate */
1.126 brouard 4392:
4393: /* proba elementaires */
4394: for(i=1,jk=1; i <=nlstate; i++){
4395: for(k=1; k <=(nlstate+ndeath); k++){
4396: if (k != i) {
4397: for(j=1; j <=ncovmodel; j++){
4398: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4399: jk++;
4400: fprintf(ficgp,"\n");
4401: }
4402: }
4403: }
4404: }
1.145 brouard 4405: /*goto avoid;*/
1.126 brouard 4406: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4407: for(jk=1; jk <=m; jk++) {
1.145 brouard 4408: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4409: if (ng==2)
4410: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4411: else
4412: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4413: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4414: i=1;
4415: for(k2=1; k2<=nlstate; k2++) {
4416: k3=i;
4417: for(k=1; k<=(nlstate+ndeath); k++) {
4418: if (k != k2){
4419: if(ng==2)
4420: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4421: else
4422: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4423: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4424: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4425: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4426: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4427: /* ij++; */
4428: /* } */
4429: /* else */
1.126 brouard 4430: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4431: }
4432: fprintf(ficgp,")/(1");
4433:
4434: for(k1=1; k1 <=nlstate; k1++){
4435: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4436: ij=1;
4437: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4438: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4439: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4440: /* ij++; */
4441: /* } */
4442: /* else */
1.126 brouard 4443: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4444: }
4445: fprintf(ficgp,")");
4446: }
4447: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4448: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4449: i=i+ncovmodel;
4450: }
4451: } /* end k */
4452: } /* end k2 */
4453: } /* end jk */
4454: } /* end ng */
1.164 brouard 4455: /* avoid: */
1.126 brouard 4456: fflush(ficgp);
4457: } /* end gnuplot */
4458:
4459:
4460: /*************** Moving average **************/
4461: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4462:
4463: int i, cpt, cptcod;
4464: int modcovmax =1;
4465: int mobilavrange, mob;
4466: double age;
4467:
4468: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4469: a covariate has 2 modalities */
4470: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4471:
4472: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4473: if(mobilav==1) mobilavrange=5; /* default */
4474: else mobilavrange=mobilav;
4475: for (age=bage; age<=fage; age++)
4476: for (i=1; i<=nlstate;i++)
4477: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4478: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4479: /* We keep the original values on the extreme ages bage, fage and for
4480: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4481: we use a 5 terms etc. until the borders are no more concerned.
4482: */
4483: for (mob=3;mob <=mobilavrange;mob=mob+2){
4484: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4485: for (i=1; i<=nlstate;i++){
4486: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4487: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4488: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4489: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4490: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4491: }
4492: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4493: }
4494: }
4495: }/* end age */
4496: }/* end mob */
4497: }else return -1;
4498: return 0;
4499: }/* End movingaverage */
4500:
4501:
4502: /************** Forecasting ******************/
1.169 brouard 4503: void 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){
1.126 brouard 4504: /* proj1, year, month, day of starting projection
4505: agemin, agemax range of age
4506: dateprev1 dateprev2 range of dates during which prevalence is computed
4507: anproj2 year of en of projection (same day and month as proj1).
4508: */
1.164 brouard 4509: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4510: double agec; /* generic age */
4511: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4512: double *popeffectif,*popcount;
4513: double ***p3mat;
4514: double ***mobaverage;
4515: char fileresf[FILENAMELENGTH];
4516:
4517: agelim=AGESUP;
4518: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4519:
4520: strcpy(fileresf,"f");
4521: strcat(fileresf,fileres);
4522: if((ficresf=fopen(fileresf,"w"))==NULL) {
4523: printf("Problem with forecast resultfile: %s\n", fileresf);
4524: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4525: }
4526: printf("Computing forecasting: result on file '%s' \n", fileresf);
4527: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4528:
4529: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4530:
4531: if (mobilav!=0) {
4532: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4533: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4534: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4535: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4536: }
4537: }
4538:
4539: stepsize=(int) (stepm+YEARM-1)/YEARM;
4540: if (stepm<=12) stepsize=1;
4541: if(estepm < stepm){
4542: printf ("Problem %d lower than %d\n",estepm, stepm);
4543: }
4544: else hstepm=estepm;
4545:
4546: hstepm=hstepm/stepm;
4547: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4548: fractional in yp1 */
4549: anprojmean=yp;
4550: yp2=modf((yp1*12),&yp);
4551: mprojmean=yp;
4552: yp1=modf((yp2*30.5),&yp);
4553: jprojmean=yp;
4554: if(jprojmean==0) jprojmean=1;
4555: if(mprojmean==0) jprojmean=1;
4556:
4557: i1=cptcoveff;
4558: if (cptcovn < 1){i1=1;}
4559:
4560: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4561:
4562: fprintf(ficresf,"#****** Routine prevforecast **\n");
4563:
4564: /* if (h==(int)(YEARM*yearp)){ */
4565: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4566: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4567: k=k+1;
4568: fprintf(ficresf,"\n#******");
4569: for(j=1;j<=cptcoveff;j++) {
4570: 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]]);
4571: }
4572: fprintf(ficresf,"******\n");
4573: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4574: for(j=1; j<=nlstate+ndeath;j++){
4575: for(i=1; i<=nlstate;i++)
4576: fprintf(ficresf," p%d%d",i,j);
4577: fprintf(ficresf," p.%d",j);
4578: }
4579: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4580: fprintf(ficresf,"\n");
4581: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4582:
4583: for (agec=fage; agec>=(ageminpar-1); agec--){
4584: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4585: nhstepm = nhstepm/hstepm;
4586: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4587: oldm=oldms;savm=savms;
4588: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4589:
4590: for (h=0; h<=nhstepm; h++){
4591: if (h*hstepm/YEARM*stepm ==yearp) {
4592: fprintf(ficresf,"\n");
4593: for(j=1;j<=cptcoveff;j++)
4594: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4595: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4596: }
4597: for(j=1; j<=nlstate+ndeath;j++) {
4598: ppij=0.;
4599: for(i=1; i<=nlstate;i++) {
4600: if (mobilav==1)
4601: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4602: else {
4603: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4604: }
4605: if (h*hstepm/YEARM*stepm== yearp) {
4606: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4607: }
4608: } /* end i */
4609: if (h*hstepm/YEARM*stepm==yearp) {
4610: fprintf(ficresf," %.3f", ppij);
4611: }
4612: }/* end j */
4613: } /* end h */
4614: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4615: } /* end agec */
4616: } /* end yearp */
4617: } /* end cptcod */
4618: } /* end cptcov */
4619:
4620: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4621:
4622: fclose(ficresf);
4623: }
4624:
4625: /************** Forecasting *****not tested NB*************/
1.169 brouard 4626: void 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){
1.126 brouard 4627:
4628: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4629: int *popage;
4630: double calagedatem, agelim, kk1, kk2;
4631: double *popeffectif,*popcount;
4632: double ***p3mat,***tabpop,***tabpopprev;
4633: double ***mobaverage;
4634: char filerespop[FILENAMELENGTH];
4635:
4636: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4637: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4638: agelim=AGESUP;
4639: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4640:
4641: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4642:
4643:
4644: strcpy(filerespop,"pop");
4645: strcat(filerespop,fileres);
4646: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4647: printf("Problem with forecast resultfile: %s\n", filerespop);
4648: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4649: }
4650: printf("Computing forecasting: result on file '%s' \n", filerespop);
4651: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4652:
4653: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4654:
4655: if (mobilav!=0) {
4656: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4657: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4658: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4659: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4660: }
4661: }
4662:
4663: stepsize=(int) (stepm+YEARM-1)/YEARM;
4664: if (stepm<=12) stepsize=1;
4665:
4666: agelim=AGESUP;
4667:
4668: hstepm=1;
4669: hstepm=hstepm/stepm;
4670:
4671: if (popforecast==1) {
4672: if((ficpop=fopen(popfile,"r"))==NULL) {
4673: printf("Problem with population file : %s\n",popfile);exit(0);
4674: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4675: }
4676: popage=ivector(0,AGESUP);
4677: popeffectif=vector(0,AGESUP);
4678: popcount=vector(0,AGESUP);
4679:
4680: i=1;
4681: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4682:
4683: imx=i;
4684: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4685: }
4686:
4687: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4688: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4689: k=k+1;
4690: fprintf(ficrespop,"\n#******");
4691: for(j=1;j<=cptcoveff;j++) {
4692: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4693: }
4694: fprintf(ficrespop,"******\n");
4695: fprintf(ficrespop,"# Age");
4696: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4697: if (popforecast==1) fprintf(ficrespop," [Population]");
4698:
4699: for (cpt=0; cpt<=0;cpt++) {
4700: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4701:
4702: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4703: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4704: nhstepm = nhstepm/hstepm;
4705:
4706: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4707: oldm=oldms;savm=savms;
4708: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4709:
4710: for (h=0; h<=nhstepm; h++){
4711: if (h==(int) (calagedatem+YEARM*cpt)) {
4712: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4713: }
4714: for(j=1; j<=nlstate+ndeath;j++) {
4715: kk1=0.;kk2=0;
4716: for(i=1; i<=nlstate;i++) {
4717: if (mobilav==1)
4718: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4719: else {
4720: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4721: }
4722: }
4723: if (h==(int)(calagedatem+12*cpt)){
4724: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4725: /*fprintf(ficrespop," %.3f", kk1);
4726: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4727: }
4728: }
4729: for(i=1; i<=nlstate;i++){
4730: kk1=0.;
4731: for(j=1; j<=nlstate;j++){
4732: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4733: }
4734: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4735: }
4736:
4737: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4738: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4739: }
4740: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4741: }
4742: }
4743:
4744: /******/
4745:
4746: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4747: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4748: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4749: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4750: nhstepm = nhstepm/hstepm;
4751:
4752: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4753: oldm=oldms;savm=savms;
4754: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4755: for (h=0; h<=nhstepm; h++){
4756: if (h==(int) (calagedatem+YEARM*cpt)) {
4757: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4758: }
4759: for(j=1; j<=nlstate+ndeath;j++) {
4760: kk1=0.;kk2=0;
4761: for(i=1; i<=nlstate;i++) {
4762: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4763: }
4764: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4765: }
4766: }
4767: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4768: }
4769: }
4770: }
4771: }
4772:
4773: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4774:
4775: if (popforecast==1) {
4776: free_ivector(popage,0,AGESUP);
4777: free_vector(popeffectif,0,AGESUP);
4778: free_vector(popcount,0,AGESUP);
4779: }
4780: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4781: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4782: fclose(ficrespop);
4783: } /* End of popforecast */
4784:
4785: int fileappend(FILE *fichier, char *optionfich)
4786: {
4787: if((fichier=fopen(optionfich,"a"))==NULL) {
4788: printf("Problem with file: %s\n", optionfich);
4789: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4790: return (0);
4791: }
4792: fflush(fichier);
4793: return (1);
4794: }
4795:
4796:
4797: /**************** function prwizard **********************/
4798: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4799: {
4800:
4801: /* Wizard to print covariance matrix template */
4802:
1.164 brouard 4803: char ca[32], cb[32];
4804: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4805: int numlinepar;
4806:
4807: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4808: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4809: for(i=1; i <=nlstate; i++){
4810: jj=0;
4811: for(j=1; j <=nlstate+ndeath; j++){
4812: if(j==i) continue;
4813: jj++;
4814: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4815: printf("%1d%1d",i,j);
4816: fprintf(ficparo,"%1d%1d",i,j);
4817: for(k=1; k<=ncovmodel;k++){
4818: /* printf(" %lf",param[i][j][k]); */
4819: /* fprintf(ficparo," %lf",param[i][j][k]); */
4820: printf(" 0.");
4821: fprintf(ficparo," 0.");
4822: }
4823: printf("\n");
4824: fprintf(ficparo,"\n");
4825: }
4826: }
4827: printf("# Scales (for hessian or gradient estimation)\n");
4828: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4829: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4830: for(i=1; i <=nlstate; i++){
4831: jj=0;
4832: for(j=1; j <=nlstate+ndeath; j++){
4833: if(j==i) continue;
4834: jj++;
4835: fprintf(ficparo,"%1d%1d",i,j);
4836: printf("%1d%1d",i,j);
4837: fflush(stdout);
4838: for(k=1; k<=ncovmodel;k++){
4839: /* printf(" %le",delti3[i][j][k]); */
4840: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4841: printf(" 0.");
4842: fprintf(ficparo," 0.");
4843: }
4844: numlinepar++;
4845: printf("\n");
4846: fprintf(ficparo,"\n");
4847: }
4848: }
4849: printf("# Covariance matrix\n");
4850: /* # 121 Var(a12)\n\ */
4851: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4852: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4853: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4854: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4855: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4856: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4857: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4858: fflush(stdout);
4859: fprintf(ficparo,"# Covariance matrix\n");
4860: /* # 121 Var(a12)\n\ */
4861: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4862: /* # ...\n\ */
4863: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4864:
4865: for(itimes=1;itimes<=2;itimes++){
4866: jj=0;
4867: for(i=1; i <=nlstate; i++){
4868: for(j=1; j <=nlstate+ndeath; j++){
4869: if(j==i) continue;
4870: for(k=1; k<=ncovmodel;k++){
4871: jj++;
4872: ca[0]= k+'a'-1;ca[1]='\0';
4873: if(itimes==1){
4874: printf("#%1d%1d%d",i,j,k);
4875: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4876: }else{
4877: printf("%1d%1d%d",i,j,k);
4878: fprintf(ficparo,"%1d%1d%d",i,j,k);
4879: /* printf(" %.5le",matcov[i][j]); */
4880: }
4881: ll=0;
4882: for(li=1;li <=nlstate; li++){
4883: for(lj=1;lj <=nlstate+ndeath; lj++){
4884: if(lj==li) continue;
4885: for(lk=1;lk<=ncovmodel;lk++){
4886: ll++;
4887: if(ll<=jj){
4888: cb[0]= lk +'a'-1;cb[1]='\0';
4889: if(ll<jj){
4890: if(itimes==1){
4891: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4892: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4893: }else{
4894: printf(" 0.");
4895: fprintf(ficparo," 0.");
4896: }
4897: }else{
4898: if(itimes==1){
4899: printf(" Var(%s%1d%1d)",ca,i,j);
4900: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4901: }else{
4902: printf(" 0.");
4903: fprintf(ficparo," 0.");
4904: }
4905: }
4906: }
4907: } /* end lk */
4908: } /* end lj */
4909: } /* end li */
4910: printf("\n");
4911: fprintf(ficparo,"\n");
4912: numlinepar++;
4913: } /* end k*/
4914: } /*end j */
4915: } /* end i */
4916: } /* end itimes */
4917:
4918: } /* end of prwizard */
4919: /******************* Gompertz Likelihood ******************************/
4920: double gompertz(double x[])
4921: {
4922: double A,B,L=0.0,sump=0.,num=0.;
4923: int i,n=0; /* n is the size of the sample */
4924:
4925: for (i=0;i<=imx-1 ; i++) {
4926: sump=sump+weight[i];
4927: /* sump=sump+1;*/
4928: num=num+1;
4929: }
4930:
4931:
4932: /* for (i=0; i<=imx; i++)
4933: 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]);*/
4934:
4935: for (i=1;i<=imx ; i++)
4936: {
4937: if (cens[i] == 1 && wav[i]>1)
4938: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4939:
4940: if (cens[i] == 0 && wav[i]>1)
4941: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4942: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4943:
4944: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4945: if (wav[i] > 1 ) { /* ??? */
4946: L=L+A*weight[i];
4947: /* 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]);*/
4948: }
4949: }
4950:
4951: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4952:
4953: return -2*L*num/sump;
4954: }
4955:
1.136 brouard 4956: #ifdef GSL
4957: /******************* Gompertz_f Likelihood ******************************/
4958: double gompertz_f(const gsl_vector *v, void *params)
4959: {
4960: double A,B,LL=0.0,sump=0.,num=0.;
4961: double *x= (double *) v->data;
4962: int i,n=0; /* n is the size of the sample */
4963:
4964: for (i=0;i<=imx-1 ; i++) {
4965: sump=sump+weight[i];
4966: /* sump=sump+1;*/
4967: num=num+1;
4968: }
4969:
4970:
4971: /* for (i=0; i<=imx; i++)
4972: 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]);*/
4973: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4974: for (i=1;i<=imx ; i++)
4975: {
4976: if (cens[i] == 1 && wav[i]>1)
4977: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4978:
4979: if (cens[i] == 0 && wav[i]>1)
4980: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4981: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4982:
4983: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4984: if (wav[i] > 1 ) { /* ??? */
4985: LL=LL+A*weight[i];
4986: /* 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]);*/
4987: }
4988: }
4989:
4990: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4991: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4992:
4993: return -2*LL*num/sump;
4994: }
4995: #endif
4996:
1.126 brouard 4997: /******************* Printing html file ***********/
4998: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4999: int lastpass, int stepm, int weightopt, char model[],\
5000: int imx, double p[],double **matcov,double agemortsup){
5001: int i,k;
5002:
5003: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5004: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5005: for (i=1;i<=2;i++)
5006: 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]));
5007: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5008: fprintf(fichtm,"</ul>");
5009:
5010: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5011:
5012: 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>");
5013:
5014: for (k=agegomp;k<(agemortsup-2);k++)
5015: 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]);
5016:
5017:
5018: fflush(fichtm);
5019: }
5020:
5021: /******************* Gnuplot file **************/
5022: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5023:
5024: char dirfileres[132],optfileres[132];
1.164 brouard 5025:
1.126 brouard 5026: int ng;
5027:
5028:
5029: /*#ifdef windows */
5030: fprintf(ficgp,"cd \"%s\" \n",pathc);
5031: /*#endif */
5032:
5033:
5034: strcpy(dirfileres,optionfilefiname);
5035: strcpy(optfileres,"vpl");
5036: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5037: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 5038: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5039: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5040: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5041:
5042: }
5043:
1.136 brouard 5044: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5045: {
1.126 brouard 5046:
1.136 brouard 5047: /*-------- data file ----------*/
5048: FILE *fic;
5049: char dummy[]=" ";
1.164 brouard 5050: int i=0, j=0, n=0;
1.136 brouard 5051: int linei, month, year,iout;
5052: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5053: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5054: char *stratrunc;
5055: int lstra;
1.126 brouard 5056:
5057:
1.136 brouard 5058: if((fic=fopen(datafile,"r"))==NULL) {
5059: printf("Problem while opening datafile: %s\n", datafile);return 1;
5060: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5061: }
1.126 brouard 5062:
1.136 brouard 5063: i=1;
5064: linei=0;
5065: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5066: linei=linei+1;
5067: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5068: if(line[j] == '\t')
5069: line[j] = ' ';
5070: }
5071: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5072: ;
5073: };
5074: line[j+1]=0; /* Trims blanks at end of line */
5075: if(line[0]=='#'){
5076: fprintf(ficlog,"Comment line\n%s\n",line);
5077: printf("Comment line\n%s\n",line);
5078: continue;
5079: }
5080: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5081: strcpy(line, linetmp);
1.136 brouard 5082:
1.126 brouard 5083:
1.136 brouard 5084: for (j=maxwav;j>=1;j--){
1.137 brouard 5085: cutv(stra, strb, line, ' ');
1.136 brouard 5086: if(strb[0]=='.') { /* Missing status */
5087: lval=-1;
5088: }else{
5089: errno=0;
5090: lval=strtol(strb,&endptr,10);
5091: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5092: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5093: 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);
5094: 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 5095: return 1;
5096: }
5097: }
5098: s[j][i]=lval;
5099:
5100: strcpy(line,stra);
5101: cutv(stra, strb,line,' ');
1.169 brouard 5102: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5103: }
1.169 brouard 5104: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5105: month=99;
5106: year=9999;
5107: }else{
1.141 brouard 5108: 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);
5109: 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 5110: return 1;
5111: }
5112: anint[j][i]= (double) year;
5113: mint[j][i]= (double)month;
5114: strcpy(line,stra);
5115: } /* ENd Waves */
5116:
5117: cutv(stra, strb,line,' ');
1.169 brouard 5118: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5119: }
1.169 brouard 5120: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5121: month=99;
5122: year=9999;
5123: }else{
1.141 brouard 5124: 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);
5125: 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 5126: return 1;
5127: }
5128: andc[i]=(double) year;
5129: moisdc[i]=(double) month;
5130: strcpy(line,stra);
5131:
5132: cutv(stra, strb,line,' ');
1.169 brouard 5133: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5134: }
1.169 brouard 5135: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5136: month=99;
5137: year=9999;
5138: }else{
1.141 brouard 5139: 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);
5140: 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 5141: return 1;
5142: }
5143: if (year==9999) {
1.141 brouard 5144: 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);
5145: 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 5146: return 1;
1.126 brouard 5147:
1.136 brouard 5148: }
5149: annais[i]=(double)(year);
5150: moisnais[i]=(double)(month);
5151: strcpy(line,stra);
5152:
5153: cutv(stra, strb,line,' ');
5154: errno=0;
5155: dval=strtod(strb,&endptr);
5156: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5157: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5158: 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 5159: fflush(ficlog);
5160: return 1;
5161: }
5162: weight[i]=dval;
5163: strcpy(line,stra);
5164:
5165: for (j=ncovcol;j>=1;j--){
5166: cutv(stra, strb,line,' ');
5167: if(strb[0]=='.') { /* Missing status */
5168: lval=-1;
5169: }else{
5170: errno=0;
5171: lval=strtol(strb,&endptr,10);
5172: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5173: 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);
5174: 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 5175: return 1;
5176: }
5177: }
5178: if(lval <-1 || lval >1){
1.141 brouard 5179: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5180: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5181: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5182: For example, for multinomial values like 1, 2 and 3,\n \
5183: build V1=0 V2=0 for the reference value (1),\n \
5184: V1=1 V2=0 for (2) \n \
5185: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5186: output of IMaCh is often meaningless.\n \
5187: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5188: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5189: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5190: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5191: For example, for multinomial values like 1, 2 and 3,\n \
5192: build V1=0 V2=0 for the reference value (1),\n \
5193: V1=1 V2=0 for (2) \n \
5194: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5195: output of IMaCh is often meaningless.\n \
5196: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5197: return 1;
5198: }
5199: covar[j][i]=(double)(lval);
5200: strcpy(line,stra);
5201: }
5202: lstra=strlen(stra);
5203:
5204: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5205: stratrunc = &(stra[lstra-9]);
5206: num[i]=atol(stratrunc);
5207: }
5208: else
5209: num[i]=atol(stra);
5210: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5211: 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;}*/
5212:
5213: i=i+1;
5214: } /* End loop reading data */
1.126 brouard 5215:
1.136 brouard 5216: *imax=i-1; /* Number of individuals */
5217: fclose(fic);
5218:
5219: return (0);
1.164 brouard 5220: /* endread: */
1.136 brouard 5221: printf("Exiting readdata: ");
5222: fclose(fic);
5223: return (1);
1.126 brouard 5224:
5225:
5226:
1.136 brouard 5227: }
1.145 brouard 5228: void removespace(char *str) {
5229: char *p1 = str, *p2 = str;
5230: do
5231: while (*p2 == ' ')
5232: p2++;
1.169 brouard 5233: while (*p1++ == *p2++);
1.145 brouard 5234: }
5235:
5236: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5237: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5238: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5239: * - cptcovn or number of covariates k of the models excluding age*products =6
5240: * - cptcovage number of covariates with age*products =2
5241: * - cptcovs number of simple covariates
5242: * - 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
5243: * which is a new column after the 9 (ncovcol) variables.
5244: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5245: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5246: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5247: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5248: */
1.136 brouard 5249: {
1.145 brouard 5250: int i, j, k, ks;
1.164 brouard 5251: int j1, k1, k2;
1.136 brouard 5252: char modelsav[80];
1.145 brouard 5253: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5254:
1.145 brouard 5255: /*removespace(model);*/
1.136 brouard 5256: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5257: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5258: j=nbocc(model,'+'); /**< j=Number of '+' */
5259: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5260: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5261: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5262: /* including age products which are counted in cptcovage.
1.169 brouard 5263: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5264: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5265: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5266: strcpy(modelsav,model);
1.137 brouard 5267: if (strstr(model,"AGE") !=0){
5268: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5269: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5270: return 1;
5271: }
1.141 brouard 5272: if (strstr(model,"v") !=0){
5273: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5274: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5275: return 1;
5276: }
1.136 brouard 5277:
1.145 brouard 5278: /* Design
5279: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5280: * < ncovcol=8 >
5281: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5282: * k= 1 2 3 4 5 6 7 8
5283: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5284: * covar[k,i], value of kth covariate if not including age for individual i:
5285: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5286: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5287: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5288: * Tage[++cptcovage]=k
5289: * if products, new covar are created after ncovcol with k1
5290: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5291: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5292: * 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
5293: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5294: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5295: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5296: * < ncovcol=8 >
5297: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5298: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5299: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5300: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5301: * p Tprod[1]@2={ 6, 5}
5302: *p Tvard[1][1]@4= {7, 8, 5, 6}
5303: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5304: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5305: *How to reorganize?
5306: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5307: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5308: * {2, 1, 4, 8, 5, 6, 3, 7}
5309: * Struct []
5310: */
5311:
1.136 brouard 5312: /* This loop fills the array Tvar from the string 'model'.*/
5313: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5314: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5315: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5316: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5317: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5318: /* k=1 Tvar[1]=2 (from V2) */
5319: /* k=5 Tvar[5] */
5320: /* for (k=1; k<=cptcovn;k++) { */
5321: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5322: /* } */
5323: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5324: /*
5325: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5326: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5327: Tvar[k]=0;
5328: cptcovage=0;
5329: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5330: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5331: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5332: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5333: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5334: /*scanf("%d",i);*/
1.145 brouard 5335: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5336: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5337: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5338: /* covar is not filled and then is empty */
1.136 brouard 5339: cptcovprod--;
1.145 brouard 5340: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5341: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5342: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5343: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5344: /*printf("stre=%s ", stre);*/
1.137 brouard 5345: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5346: cptcovprod--;
1.145 brouard 5347: cutl(stre,strb,strc,'V');
1.136 brouard 5348: Tvar[k]=atoi(stre);
5349: cptcovage++;
5350: Tage[cptcovage]=k;
1.137 brouard 5351: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5352: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5353: cptcovn++;
5354: cptcovprodnoage++;k1++;
5355: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5356: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5357: because this model-covariate is a construction we invent a new column
5358: ncovcol + k1
5359: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5360: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5361: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5362: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5363: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5364: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5365: k2=k2+2;
5366: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5367: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5368: for (i=1; i<=lastobs;i++){
5369: /* Computes the new covariate which is a product of
1.145 brouard 5370: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5371: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5372: }
5373: } /* End age is not in the model */
5374: } /* End if model includes a product */
1.136 brouard 5375: else { /* no more sum */
5376: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5377: /* scanf("%d",i);*/
1.145 brouard 5378: cutl(strd,strc,strb,'V');
5379: ks++; /**< Number of simple covariates */
5380: cptcovn++;
5381: Tvar[k]=atoi(strd);
1.136 brouard 5382: }
1.137 brouard 5383: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5384: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5385: scanf("%d",i);*/
5386: } /* end of loop + */
5387: } /* end model */
5388:
5389: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5390: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5391:
5392: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5393: printf("cptcovprod=%d ", cptcovprod);
5394: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5395:
5396: scanf("%d ",i);*/
5397:
5398:
1.137 brouard 5399: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5400: /*endread:*/
1.136 brouard 5401: printf("Exiting decodemodel: ");
5402: return (1);
5403: }
5404:
1.169 brouard 5405: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5406: {
5407: int i, m;
5408:
5409: for (i=1; i<=imx; i++) {
5410: for(m=2; (m<= maxwav); m++) {
5411: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5412: anint[m][i]=9999;
5413: s[m][i]=-1;
5414: }
5415: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5416: *nberr = *nberr + 1;
5417: 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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
5418: 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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136 brouard 5419: s[m][i]=-1;
5420: }
5421: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5422: (*nberr)++;
1.136 brouard 5423: 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]);
5424: 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]);
5425: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5426: }
5427: }
5428: }
5429:
5430: for (i=1; i<=imx; i++) {
5431: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5432: for(m=firstpass; (m<= lastpass); m++){
5433: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5434: if (s[m][i] >= nlstate+1) {
1.169 brouard 5435: if(agedc[i]>0){
5436: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5437: agev[m][i]=agedc[i];
5438: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5439: }else {
1.136 brouard 5440: if ((int)andc[i]!=9999){
5441: nbwarn++;
5442: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5443: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5444: agev[m][i]=-1;
5445: }
5446: }
1.169 brouard 5447: } /* agedc > 0 */
1.136 brouard 5448: }
5449: else if(s[m][i] !=9){ /* Standard case, age in fractional
5450: years but with the precision of a month */
5451: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5452: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5453: agev[m][i]=1;
5454: else if(agev[m][i] < *agemin){
5455: *agemin=agev[m][i];
5456: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5457: }
5458: else if(agev[m][i] >*agemax){
5459: *agemax=agev[m][i];
1.156 brouard 5460: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5461: }
5462: /*agev[m][i]=anint[m][i]-annais[i];*/
5463: /* agev[m][i] = age[i]+2*m;*/
5464: }
5465: else { /* =9 */
5466: agev[m][i]=1;
5467: s[m][i]=-1;
5468: }
5469: }
5470: else /*= 0 Unknown */
5471: agev[m][i]=1;
5472: }
5473:
5474: }
5475: for (i=1; i<=imx; i++) {
5476: for(m=firstpass; (m<=lastpass); m++){
5477: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5478: (*nberr)++;
1.136 brouard 5479: 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);
5480: 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);
5481: return 1;
5482: }
5483: }
5484: }
5485:
5486: /*for (i=1; i<=imx; i++){
5487: for (m=firstpass; (m<lastpass); m++){
5488: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5489: }
5490:
5491: }*/
5492:
5493:
1.139 brouard 5494: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5495: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5496:
5497: return (0);
1.164 brouard 5498: /* endread:*/
1.136 brouard 5499: printf("Exiting calandcheckages: ");
5500: return (1);
5501: }
5502:
1.172 brouard 5503: #if defined(_MSC_VER)
5504: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5505: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5506: //#include "stdafx.h"
5507: //#include <stdio.h>
5508: //#include <tchar.h>
5509: //#include <windows.h>
5510: //#include <iostream>
5511: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5512:
5513: LPFN_ISWOW64PROCESS fnIsWow64Process;
5514:
5515: BOOL IsWow64()
5516: {
5517: BOOL bIsWow64 = FALSE;
5518:
5519: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5520: // (HANDLE, PBOOL);
5521:
5522: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5523:
5524: HMODULE module = GetModuleHandle(_T("kernel32"));
5525: const char funcName[] = "IsWow64Process";
5526: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5527: GetProcAddress(module, funcName);
5528:
5529: if (NULL != fnIsWow64Process)
5530: {
5531: if (!fnIsWow64Process(GetCurrentProcess(),
5532: &bIsWow64))
5533: //throw std::exception("Unknown error");
5534: printf("Unknown error\n");
5535: }
5536: return bIsWow64 != FALSE;
5537: }
5538: #endif
1.177 brouard 5539:
1.169 brouard 5540: void syscompilerinfo()
1.167 brouard 5541: {
5542: /* #include "syscompilerinfo.h"*/
1.177 brouard 5543:
5544: #if defined __INTEL_COMPILER
1.178 brouard 5545: #if defined(__GNUC__)
5546: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5547: #endif
1.177 brouard 5548: #elif defined(__GNUC__)
1.179 brouard 5549: #ifndef __APPLE__
1.174 brouard 5550: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 5551: #endif
1.177 brouard 5552: struct utsname sysInfo;
1.178 brouard 5553: int cross = CROSS;
5554: if (cross){
5555: printf("Cross-");
5556: fprintf(ficlog, "Cross-");
5557: }
1.174 brouard 5558: #endif
5559:
1.171 brouard 5560: #include <stdint.h>
1.178 brouard 5561:
1.169 brouard 5562: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5563: #if defined(__clang__)
5564: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5565: #endif
5566: #if defined(__ICC) || defined(__INTEL_COMPILER)
5567: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5568: #endif
5569: #if defined(__GNUC__) || defined(__GNUG__)
5570: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5571: #endif
5572: #if defined(__HP_cc) || defined(__HP_aCC)
5573: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5574: #endif
5575: #if defined(__IBMC__) || defined(__IBMCPP__)
5576: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5577: #endif
5578: #if defined(_MSC_VER)
5579: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5580: #endif
5581: #if defined(__PGI)
5582: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5583: #endif
5584: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5585: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5586: #endif
1.174 brouard 5587: printf(" for ");fprintf(ficlog," for ");
1.169 brouard 5588:
1.167 brouard 5589: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5590: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5591: // Windows (x64 and x86)
1.174 brouard 5592: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 5593: #elif __unix__ // all unices, not all compilers
5594: // Unix
1.174 brouard 5595: printf("Unix ");fprintf(ficlog,"Unix ");
1.167 brouard 5596: #elif __linux__
5597: // linux
1.174 brouard 5598: printf("linux ");fprintf(ficlog,"linux ");
1.167 brouard 5599: #elif __APPLE__
1.174 brouard 5600: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5601: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167 brouard 5602: #endif
5603:
5604: /* __MINGW32__ */
5605: /* __CYGWIN__ */
5606: /* __MINGW64__ */
5607: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5608: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5609: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5610: /* _WIN64 // Defined for applications for Win64. */
5611: /* _M_X64 // Defined for compilations that target x64 processors. */
5612: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5613:
1.167 brouard 5614: #if UINTPTR_MAX == 0xffffffff
1.174 brouard 5615: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 5616: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174 brouard 5617: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 5618: #else
1.174 brouard 5619: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 5620: #endif
5621:
1.169 brouard 5622: #if defined(__GNUC__)
5623: # if defined(__GNUC_PATCHLEVEL__)
5624: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5625: + __GNUC_MINOR__ * 100 \
5626: + __GNUC_PATCHLEVEL__)
5627: # else
5628: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5629: + __GNUC_MINOR__ * 100)
5630: # endif
1.174 brouard 5631: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5632: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 5633:
5634: if (uname(&sysInfo) != -1) {
5635: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5636: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5637: }
5638: else
5639: perror("uname() error");
1.179 brouard 5640: //#ifndef __INTEL_COMPILER
5641: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 5642: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.179 brouard 5643: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 5644: #endif
1.169 brouard 5645: #endif
1.172 brouard 5646:
5647: // void main()
5648: // {
1.169 brouard 5649: #if defined(_MSC_VER)
1.174 brouard 5650: if (IsWow64()){
1.176 brouard 5651: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5652: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 5653: }
5654: else{
1.176 brouard 5655: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178 brouard 5656: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 5657: }
1.172 brouard 5658: // printf("\nPress Enter to continue...");
5659: // getchar();
5660: // }
5661:
1.169 brouard 5662: #endif
5663:
1.167 brouard 5664:
5665: }
1.136 brouard 5666:
1.180 brouard 5667: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5668: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5669: int i, j, k, i1 ;
5670: double ftolpl = 1.e-10;
5671: double age, agebase, agelim;
5672:
5673: strcpy(filerespl,"pl");
5674: strcat(filerespl,fileres);
5675: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5676: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5677: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5678: }
5679: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5680: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5681: pstamp(ficrespl);
5682: fprintf(ficrespl,"# Period (stable) prevalence \n");
5683: fprintf(ficrespl,"#Age ");
5684: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5685: fprintf(ficrespl,"\n");
5686:
5687: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5688:
5689: agebase=ageminpar;
5690: agelim=agemaxpar;
5691:
5692: i1=pow(2,cptcoveff);
5693: if (cptcovn < 1){i1=1;}
5694:
5695: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5696: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5697: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5698: k=k+1;
5699: /* to clean */
5700: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5701: fprintf(ficrespl,"\n#******");
5702: printf("\n#******");
5703: fprintf(ficlog,"\n#******");
5704: for(j=1;j<=cptcoveff;j++) {
5705: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5706: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5707: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5708: }
5709: fprintf(ficrespl,"******\n");
5710: printf("******\n");
5711: fprintf(ficlog,"******\n");
5712:
5713: fprintf(ficrespl,"#Age ");
5714: for(j=1;j<=cptcoveff;j++) {
5715: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5716: }
5717: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5718: fprintf(ficrespl,"\n");
5719:
5720: for (age=agebase; age<=agelim; age++){
5721: /* for (age=agebase; age<=agebase; age++){ */
5722: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5723: fprintf(ficrespl,"%.0f ",age );
5724: for(j=1;j<=cptcoveff;j++)
5725: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5726: for(i=1; i<=nlstate;i++)
5727: fprintf(ficrespl," %.5f", prlim[i][i]);
5728: fprintf(ficrespl,"\n");
5729: } /* Age */
5730: /* was end of cptcod */
5731: } /* cptcov */
5732: }
5733:
5734: int hPijx(double *p, int bage, int fage){
5735: /*------------- h Pij x at various ages ------------*/
5736:
5737: int stepsize;
5738: int agelim;
5739: int hstepm;
5740: int nhstepm;
5741: int h, i, i1, j, k;
5742:
5743: double agedeb;
5744: double ***p3mat;
5745:
5746: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5747: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5748: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5749: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5750: }
5751: printf("Computing pij: result on file '%s' \n", filerespij);
5752: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5753:
5754: stepsize=(int) (stepm+YEARM-1)/YEARM;
5755: /*if (stepm<=24) stepsize=2;*/
5756:
5757: agelim=AGESUP;
5758: hstepm=stepsize*YEARM; /* Every year of age */
5759: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5760:
5761: /* hstepm=1; aff par mois*/
5762: pstamp(ficrespij);
5763: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5764: i1= pow(2,cptcoveff);
5765: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5766: /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
5767: k=k+1;
5768: /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
5769: fprintf(ficrespij,"\n#****** ");
5770: for(j=1;j<=cptcoveff;j++)
5771: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5772: fprintf(ficrespij,"******\n");
5773:
5774: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5775: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5776: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5777:
5778: /* nhstepm=nhstepm*YEARM; aff par mois*/
5779:
5780: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5781: oldm=oldms;savm=savms;
5782: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5783: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5784: for(i=1; i<=nlstate;i++)
5785: for(j=1; j<=nlstate+ndeath;j++)
5786: fprintf(ficrespij," %1d-%1d",i,j);
5787: fprintf(ficrespij,"\n");
5788: for (h=0; h<=nhstepm; h++){
5789: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5790: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5791: for(i=1; i<=nlstate;i++)
5792: for(j=1; j<=nlstate+ndeath;j++)
5793: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5794: fprintf(ficrespij,"\n");
5795: }
5796: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5797: fprintf(ficrespij,"\n");
5798: }
5799: /*}*/
5800: }
5801: }
5802:
5803:
1.136 brouard 5804: /***********************************************/
5805: /**************** Main Program *****************/
5806: /***********************************************/
5807:
5808: int main(int argc, char *argv[])
5809: {
5810: #ifdef GSL
5811: const gsl_multimin_fminimizer_type *T;
5812: size_t iteri = 0, it;
5813: int rval = GSL_CONTINUE;
5814: int status = GSL_SUCCESS;
5815: double ssval;
5816: #endif
5817: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5818: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5819:
5820: int jj, ll, li, lj, lk;
1.136 brouard 5821: int numlinepar=0; /* Current linenumber of parameter file */
5822: int itimes;
5823: int NDIM=2;
5824: int vpopbased=0;
5825:
1.164 brouard 5826: char ca[32], cb[32];
1.136 brouard 5827: /* FILE *fichtm; *//* Html File */
5828: /* FILE *ficgp;*/ /*Gnuplot File */
5829: struct stat info;
1.164 brouard 5830: double agedeb;
1.136 brouard 5831: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5832:
1.165 brouard 5833: double fret;
1.136 brouard 5834: double dum; /* Dummy variable */
5835: double ***p3mat;
5836: double ***mobaverage;
1.164 brouard 5837:
5838: char line[MAXLINE];
1.136 brouard 5839: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5840: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5841: char *tok, *val; /* pathtot */
1.136 brouard 5842: int firstobs=1, lastobs=10;
1.164 brouard 5843: int c, h , cpt;
5844: int jl;
5845: int i1, j1, jk, stepsize;
5846: int *tab;
1.136 brouard 5847: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5848: int mobilav=0,popforecast=0;
5849: int hstepm, nhstepm;
5850: int agemortsup;
5851: float sumlpop=0.;
5852: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5853: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5854:
1.164 brouard 5855: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5856: double ftolpl=FTOL;
5857: double **prlim;
5858: double ***param; /* Matrix of parameters */
5859: double *p;
5860: double **matcov; /* Matrix of covariance */
5861: double ***delti3; /* Scale */
5862: double *delti; /* Scale */
5863: double ***eij, ***vareij;
5864: double **varpl; /* Variances of prevalence limits by age */
5865: double *epj, vepp;
1.164 brouard 5866:
1.136 brouard 5867: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5868: double **ximort;
1.145 brouard 5869: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5870: int *dcwave;
5871:
1.164 brouard 5872: char z[1]="c";
1.136 brouard 5873:
5874: /*char *strt;*/
5875: char strtend[80];
1.126 brouard 5876:
1.164 brouard 5877:
1.126 brouard 5878: /* setlocale (LC_ALL, ""); */
5879: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5880: /* textdomain (PACKAGE); */
5881: /* setlocale (LC_CTYPE, ""); */
5882: /* setlocale (LC_MESSAGES, ""); */
5883:
5884: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5885: rstart_time = time(NULL);
5886: /* (void) gettimeofday(&start_time,&tzp);*/
5887: start_time = *localtime(&rstart_time);
1.126 brouard 5888: curr_time=start_time;
1.157 brouard 5889: /*tml = *localtime(&start_time.tm_sec);*/
5890: /* strcpy(strstart,asctime(&tml)); */
5891: strcpy(strstart,asctime(&start_time));
1.126 brouard 5892:
5893: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5894: /* tp.tm_sec = tp.tm_sec +86400; */
5895: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5896: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5897: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5898: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5899: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5900: /* strt=asctime(&tmg); */
5901: /* printf("Time(after) =%s",strstart); */
5902: /* (void) time (&time_value);
5903: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5904: * tm = *localtime(&time_value);
5905: * strstart=asctime(&tm);
5906: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5907: */
5908:
5909: nberr=0; /* Number of errors and warnings */
5910: nbwarn=0;
5911: getcwd(pathcd, size);
5912:
5913: printf("\n%s\n%s",version,fullversion);
5914: if(argc <=1){
5915: printf("\nEnter the parameter file name: ");
5916: fgets(pathr,FILENAMELENGTH,stdin);
5917: i=strlen(pathr);
5918: if(pathr[i-1]=='\n')
5919: pathr[i-1]='\0';
1.156 brouard 5920: i=strlen(pathr);
5921: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5922: pathr[i-1]='\0';
1.126 brouard 5923: for (tok = pathr; tok != NULL; ){
5924: printf("Pathr |%s|\n",pathr);
5925: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5926: printf("val= |%s| pathr=%s\n",val,pathr);
5927: strcpy (pathtot, val);
5928: if(pathr[0] == '\0') break; /* Dirty */
5929: }
5930: }
5931: else{
5932: strcpy(pathtot,argv[1]);
5933: }
5934: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5935: /*cygwin_split_path(pathtot,path,optionfile);
5936: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5937: /* cutv(path,optionfile,pathtot,'\\');*/
5938:
5939: /* Split argv[0], imach program to get pathimach */
5940: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5941: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5942: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5943: /* strcpy(pathimach,argv[0]); */
5944: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5945: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5946: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5947: chdir(path); /* Can be a relative path */
5948: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5949: printf("Current directory %s!\n",pathcd);
5950: strcpy(command,"mkdir ");
5951: strcat(command,optionfilefiname);
5952: if((outcmd=system(command)) != 0){
1.169 brouard 5953: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 5954: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5955: /* fclose(ficlog); */
5956: /* exit(1); */
5957: }
5958: /* if((imk=mkdir(optionfilefiname))<0){ */
5959: /* perror("mkdir"); */
5960: /* } */
5961:
5962: /*-------- arguments in the command line --------*/
5963:
5964: /* Log file */
5965: strcat(filelog, optionfilefiname);
5966: strcat(filelog,".log"); /* */
5967: if((ficlog=fopen(filelog,"w"))==NULL) {
5968: printf("Problem with logfile %s\n",filelog);
5969: goto end;
5970: }
5971: fprintf(ficlog,"Log filename:%s\n",filelog);
5972: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5973: fprintf(ficlog,"\nEnter the parameter file name: \n");
5974: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5975: path=%s \n\
5976: optionfile=%s\n\
5977: optionfilext=%s\n\
1.156 brouard 5978: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5979:
1.167 brouard 5980: syscompilerinfo();
5981:
1.126 brouard 5982: printf("Local time (at start):%s",strstart);
5983: fprintf(ficlog,"Local time (at start): %s",strstart);
5984: fflush(ficlog);
5985: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5986: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5987:
5988: /* */
5989: strcpy(fileres,"r");
5990: strcat(fileres, optionfilefiname);
5991: strcat(fileres,".txt"); /* Other files have txt extension */
5992:
5993: /*---------arguments file --------*/
5994:
5995: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5996: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5997: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5998: fflush(ficlog);
1.149 brouard 5999: /* goto end; */
6000: exit(70);
1.126 brouard 6001: }
6002:
6003:
6004:
6005: strcpy(filereso,"o");
6006: strcat(filereso,fileres);
6007: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6008: printf("Problem with Output resultfile: %s\n", filereso);
6009: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6010: fflush(ficlog);
6011: goto end;
6012: }
6013:
6014: /* Reads comments: lines beginning with '#' */
6015: numlinepar=0;
6016: while((c=getc(ficpar))=='#' && c!= EOF){
6017: ungetc(c,ficpar);
6018: fgets(line, MAXLINE, ficpar);
6019: numlinepar++;
1.141 brouard 6020: fputs(line,stdout);
1.126 brouard 6021: fputs(line,ficparo);
6022: fputs(line,ficlog);
6023: }
6024: ungetc(c,ficpar);
6025:
6026: 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);
6027: numlinepar++;
6028: 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);
6029: 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);
6030: 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);
6031: fflush(ficlog);
6032: while((c=getc(ficpar))=='#' && c!= EOF){
6033: ungetc(c,ficpar);
6034: fgets(line, MAXLINE, ficpar);
6035: numlinepar++;
1.141 brouard 6036: fputs(line, stdout);
6037: //puts(line);
1.126 brouard 6038: fputs(line,ficparo);
6039: fputs(line,ficlog);
6040: }
6041: ungetc(c,ficpar);
6042:
6043:
1.145 brouard 6044: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6045: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6046: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6047: v1+v2*age+v2*v3 makes cptcovn = 3
6048: */
6049: if (strlen(model)>1)
1.145 brouard 6050: 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*/
6051: else
6052: ncovmodel=2;
1.126 brouard 6053: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 6054: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6055: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6056: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6057: 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);
6058: 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);
6059: fflush(stdout);
6060: fclose (ficlog);
6061: goto end;
6062: }
1.126 brouard 6063: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6064: delti=delti3[1][1];
6065: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6066: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6067: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6068: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6069: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6070: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6071: fclose (ficparo);
6072: fclose (ficlog);
6073: goto end;
6074: exit(0);
6075: }
6076: else if(mle==-3) {
6077: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6078: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6079: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6080: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6081: matcov=matrix(1,npar,1,npar);
6082: }
6083: else{
1.145 brouard 6084: /* Read guessed parameters */
1.126 brouard 6085: /* Reads comments: lines beginning with '#' */
6086: while((c=getc(ficpar))=='#' && c!= EOF){
6087: ungetc(c,ficpar);
6088: fgets(line, MAXLINE, ficpar);
6089: numlinepar++;
1.141 brouard 6090: fputs(line,stdout);
1.126 brouard 6091: fputs(line,ficparo);
6092: fputs(line,ficlog);
6093: }
6094: ungetc(c,ficpar);
6095:
6096: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6097: for(i=1; i <=nlstate; i++){
6098: j=0;
6099: for(jj=1; jj <=nlstate+ndeath; jj++){
6100: if(jj==i) continue;
6101: j++;
6102: fscanf(ficpar,"%1d%1d",&i1,&j1);
6103: if ((i1 != i) && (j1 != j)){
6104: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6105: It might be a problem of design; if ncovcol and the model are correct\n \
6106: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6107: exit(1);
6108: }
6109: fprintf(ficparo,"%1d%1d",i1,j1);
6110: if(mle==1)
6111: printf("%1d%1d",i,j);
6112: fprintf(ficlog,"%1d%1d",i,j);
6113: for(k=1; k<=ncovmodel;k++){
6114: fscanf(ficpar," %lf",¶m[i][j][k]);
6115: if(mle==1){
6116: printf(" %lf",param[i][j][k]);
6117: fprintf(ficlog," %lf",param[i][j][k]);
6118: }
6119: else
6120: fprintf(ficlog," %lf",param[i][j][k]);
6121: fprintf(ficparo," %lf",param[i][j][k]);
6122: }
6123: fscanf(ficpar,"\n");
6124: numlinepar++;
6125: if(mle==1)
6126: printf("\n");
6127: fprintf(ficlog,"\n");
6128: fprintf(ficparo,"\n");
6129: }
6130: }
6131: fflush(ficlog);
6132:
1.145 brouard 6133: /* Reads scales values */
1.126 brouard 6134: p=param[1][1];
6135:
6136: /* Reads comments: lines beginning with '#' */
6137: while((c=getc(ficpar))=='#' && c!= EOF){
6138: ungetc(c,ficpar);
6139: fgets(line, MAXLINE, ficpar);
6140: numlinepar++;
1.141 brouard 6141: fputs(line,stdout);
1.126 brouard 6142: fputs(line,ficparo);
6143: fputs(line,ficlog);
6144: }
6145: ungetc(c,ficpar);
6146:
6147: for(i=1; i <=nlstate; i++){
6148: for(j=1; j <=nlstate+ndeath-1; j++){
6149: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6150: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6151: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6152: exit(1);
6153: }
6154: printf("%1d%1d",i,j);
6155: fprintf(ficparo,"%1d%1d",i1,j1);
6156: fprintf(ficlog,"%1d%1d",i1,j1);
6157: for(k=1; k<=ncovmodel;k++){
6158: fscanf(ficpar,"%le",&delti3[i][j][k]);
6159: printf(" %le",delti3[i][j][k]);
6160: fprintf(ficparo," %le",delti3[i][j][k]);
6161: fprintf(ficlog," %le",delti3[i][j][k]);
6162: }
6163: fscanf(ficpar,"\n");
6164: numlinepar++;
6165: printf("\n");
6166: fprintf(ficparo,"\n");
6167: fprintf(ficlog,"\n");
6168: }
6169: }
6170: fflush(ficlog);
6171:
1.145 brouard 6172: /* Reads covariance matrix */
1.126 brouard 6173: delti=delti3[1][1];
6174:
6175:
6176: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6177:
6178: /* Reads comments: lines beginning with '#' */
6179: while((c=getc(ficpar))=='#' && c!= EOF){
6180: ungetc(c,ficpar);
6181: fgets(line, MAXLINE, ficpar);
6182: numlinepar++;
1.141 brouard 6183: fputs(line,stdout);
1.126 brouard 6184: fputs(line,ficparo);
6185: fputs(line,ficlog);
6186: }
6187: ungetc(c,ficpar);
6188:
6189: matcov=matrix(1,npar,1,npar);
1.131 brouard 6190: for(i=1; i <=npar; i++)
6191: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6192:
1.126 brouard 6193: for(i=1; i <=npar; i++){
1.145 brouard 6194: fscanf(ficpar,"%s",str);
1.126 brouard 6195: if(mle==1)
6196: printf("%s",str);
6197: fprintf(ficlog,"%s",str);
6198: fprintf(ficparo,"%s",str);
6199: for(j=1; j <=i; j++){
6200: fscanf(ficpar," %le",&matcov[i][j]);
6201: if(mle==1){
6202: printf(" %.5le",matcov[i][j]);
6203: }
6204: fprintf(ficlog," %.5le",matcov[i][j]);
6205: fprintf(ficparo," %.5le",matcov[i][j]);
6206: }
6207: fscanf(ficpar,"\n");
6208: numlinepar++;
6209: if(mle==1)
6210: printf("\n");
6211: fprintf(ficlog,"\n");
6212: fprintf(ficparo,"\n");
6213: }
6214: for(i=1; i <=npar; i++)
6215: for(j=i+1;j<=npar;j++)
6216: matcov[i][j]=matcov[j][i];
6217:
6218: if(mle==1)
6219: printf("\n");
6220: fprintf(ficlog,"\n");
6221:
6222: fflush(ficlog);
6223:
6224: /*-------- Rewriting parameter file ----------*/
6225: strcpy(rfileres,"r"); /* "Rparameterfile */
6226: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6227: strcat(rfileres,"."); /* */
6228: strcat(rfileres,optionfilext); /* Other files have txt extension */
6229: if((ficres =fopen(rfileres,"w"))==NULL) {
6230: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6231: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6232: }
6233: fprintf(ficres,"#%s\n",version);
6234: } /* End of mle != -3 */
6235:
6236:
6237: n= lastobs;
6238: num=lvector(1,n);
6239: moisnais=vector(1,n);
6240: annais=vector(1,n);
6241: moisdc=vector(1,n);
6242: andc=vector(1,n);
6243: agedc=vector(1,n);
6244: cod=ivector(1,n);
6245: weight=vector(1,n);
6246: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6247: mint=matrix(1,maxwav,1,n);
6248: anint=matrix(1,maxwav,1,n);
1.131 brouard 6249: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6250: tab=ivector(1,NCOVMAX);
1.144 brouard 6251: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6252:
1.136 brouard 6253: /* Reads data from file datafile */
6254: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6255: goto end;
6256:
6257: /* Calculation of the number of parameters from char model */
1.137 brouard 6258: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6259: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6260: k=3 V4 Tvar[k=3]= 4 (from V4)
6261: k=2 V1 Tvar[k=2]= 1 (from V1)
6262: k=1 Tvar[1]=2 (from V2)
6263: */
6264: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6265: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6266: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6267: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6268: */
6269: /* For model-covariate k tells which data-covariate to use but
6270: because this model-covariate is a construction we invent a new column
6271: ncovcol + k1
6272: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6273: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6274: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6275: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6276: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6277: */
1.145 brouard 6278: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6279: 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 6280: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6281: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6282: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6283: 4 covariates (3 plus signs)
6284: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6285: */
1.136 brouard 6286:
6287: if(decodemodel(model, lastobs) == 1)
6288: goto end;
6289:
1.137 brouard 6290: if((double)(lastobs-imx)/(double)imx > 1.10){
6291: nbwarn++;
6292: 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);
6293: 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);
6294: }
1.136 brouard 6295: /* if(mle==1){*/
1.137 brouard 6296: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6297: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6298: }
6299:
6300: /*-calculation of age at interview from date of interview and age at death -*/
6301: agev=matrix(1,maxwav,1,imx);
6302:
6303: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6304: goto end;
6305:
1.126 brouard 6306:
1.136 brouard 6307: agegomp=(int)agemin;
6308: free_vector(moisnais,1,n);
6309: free_vector(annais,1,n);
1.126 brouard 6310: /* free_matrix(mint,1,maxwav,1,n);
6311: free_matrix(anint,1,maxwav,1,n);*/
6312: free_vector(moisdc,1,n);
6313: free_vector(andc,1,n);
1.145 brouard 6314: /* */
6315:
1.126 brouard 6316: wav=ivector(1,imx);
6317: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6318: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6319: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6320:
6321: /* Concatenates waves */
6322: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6323: /* */
6324:
1.126 brouard 6325: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6326:
6327: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6328: ncodemax[1]=1;
1.145 brouard 6329: Ndum =ivector(-1,NCOVMAX);
6330: if (ncovmodel > 2)
6331: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6332:
6333: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6334: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6335: h=0;
6336:
6337:
6338: /*if (cptcovn > 0) */
1.126 brouard 6339:
1.145 brouard 6340:
1.126 brouard 6341: m=pow(2,cptcoveff);
6342:
1.131 brouard 6343: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6344: 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 */
6345: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6346: 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 6347: h++;
1.141 brouard 6348: if (h>m)
1.136 brouard 6349: h=1;
1.144 brouard 6350: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6351: * h 1 2 3 4
6352: *______________________________
6353: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6354: * 2 2 1 1 1
6355: * 3 i=2 1 2 1 1
6356: * 4 2 2 1 1
6357: * 5 i=3 1 i=2 1 2 1
6358: * 6 2 1 2 1
6359: * 7 i=4 1 2 2 1
6360: * 8 2 2 2 1
6361: * 9 i=5 1 i=3 1 i=2 1 1
6362: * 10 2 1 1 1
6363: * 11 i=6 1 2 1 1
6364: * 12 2 2 1 1
6365: * 13 i=7 1 i=4 1 2 1
6366: * 14 2 1 2 1
6367: * 15 i=8 1 2 2 1
6368: * 16 2 2 2 1
6369: */
1.141 brouard 6370: codtab[h][k]=j;
1.145 brouard 6371: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6372: 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 6373: }
6374: }
6375: }
6376: }
6377: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6378: codtab[1][2]=1;codtab[2][2]=2; */
6379: /* for(i=1; i <=m ;i++){
6380: for(k=1; k <=cptcovn; k++){
1.131 brouard 6381: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6382: }
6383: printf("\n");
6384: }
6385: scanf("%d",i);*/
1.145 brouard 6386:
6387: free_ivector(Ndum,-1,NCOVMAX);
6388:
6389:
1.126 brouard 6390:
6391: /*------------ gnuplot -------------*/
6392: strcpy(optionfilegnuplot,optionfilefiname);
6393: if(mle==-3)
6394: strcat(optionfilegnuplot,"-mort");
6395: strcat(optionfilegnuplot,".gp");
6396:
6397: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6398: printf("Problem with file %s",optionfilegnuplot);
6399: }
6400: else{
6401: fprintf(ficgp,"\n# %s\n", version);
6402: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6403: //fprintf(ficgp,"set missing 'NaNq'\n");
6404: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6405: }
6406: /* fclose(ficgp);*/
6407: /*--------- index.htm --------*/
6408:
6409: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6410: if(mle==-3)
6411: strcat(optionfilehtm,"-mort");
6412: strcat(optionfilehtm,".htm");
6413: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6414: printf("Problem with %s \n",optionfilehtm);
6415: exit(0);
1.126 brouard 6416: }
6417:
6418: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6419: strcat(optionfilehtmcov,"-cov.htm");
6420: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6421: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6422: }
6423: else{
6424: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6425: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6426: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6427: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6428: }
6429:
6430: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6431: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6432: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6433: \n\
6434: <hr size=\"2\" color=\"#EC5E5E\">\
6435: <ul><li><h4>Parameter files</h4>\n\
6436: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6437: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6438: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6439: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6440: - Date and time at start: %s</ul>\n",\
6441: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6442: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6443: fileres,fileres,\
6444: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6445: fflush(fichtm);
6446:
6447: strcpy(pathr,path);
6448: strcat(pathr,optionfilefiname);
6449: chdir(optionfilefiname); /* Move to directory named optionfile */
6450:
6451: /* Calculates basic frequencies. Computes observed prevalence at single age
6452: and prints on file fileres'p'. */
6453: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6454:
6455: fprintf(fichtm,"\n");
6456: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6457: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6458: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6459: imx,agemin,agemax,jmin,jmax,jmean);
6460: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6461: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6462: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6463: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6464: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6465:
6466:
6467: /* For Powell, parameters are in a vector p[] starting at p[1]
6468: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6469: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6470:
6471: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6472:
6473: if (mle==-3){
1.136 brouard 6474: ximort=matrix(1,NDIM,1,NDIM);
6475: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6476: cens=ivector(1,n);
6477: ageexmed=vector(1,n);
6478: agecens=vector(1,n);
6479: dcwave=ivector(1,n);
6480:
6481: for (i=1; i<=imx; i++){
6482: dcwave[i]=-1;
6483: for (m=firstpass; m<=lastpass; m++)
6484: if (s[m][i]>nlstate) {
6485: dcwave[i]=m;
6486: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6487: break;
6488: }
6489: }
6490:
6491: for (i=1; i<=imx; i++) {
6492: if (wav[i]>0){
6493: ageexmed[i]=agev[mw[1][i]][i];
6494: j=wav[i];
6495: agecens[i]=1.;
6496:
6497: if (ageexmed[i]> 1 && wav[i] > 0){
6498: agecens[i]=agev[mw[j][i]][i];
6499: cens[i]= 1;
6500: }else if (ageexmed[i]< 1)
6501: cens[i]= -1;
6502: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6503: cens[i]=0 ;
6504: }
6505: else cens[i]=-1;
6506: }
6507:
6508: for (i=1;i<=NDIM;i++) {
6509: for (j=1;j<=NDIM;j++)
6510: ximort[i][j]=(i == j ? 1.0 : 0.0);
6511: }
6512:
1.145 brouard 6513: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6514: /*printf("%lf %lf", p[1], p[2]);*/
6515:
6516:
1.136 brouard 6517: #ifdef GSL
6518: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6519: #else
1.126 brouard 6520: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6521: #endif
1.126 brouard 6522: strcpy(filerespow,"pow-mort");
6523: strcat(filerespow,fileres);
6524: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6525: printf("Problem with resultfile: %s\n", filerespow);
6526: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6527: }
1.136 brouard 6528: #ifdef GSL
6529: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6530: #else
1.126 brouard 6531: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6532: #endif
1.126 brouard 6533: /* for (i=1;i<=nlstate;i++)
6534: for(j=1;j<=nlstate+ndeath;j++)
6535: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6536: */
6537: fprintf(ficrespow,"\n");
1.136 brouard 6538: #ifdef GSL
6539: /* gsl starts here */
6540: T = gsl_multimin_fminimizer_nmsimplex;
6541: gsl_multimin_fminimizer *sfm = NULL;
6542: gsl_vector *ss, *x;
6543: gsl_multimin_function minex_func;
6544:
6545: /* Initial vertex size vector */
6546: ss = gsl_vector_alloc (NDIM);
6547:
6548: if (ss == NULL){
6549: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6550: }
6551: /* Set all step sizes to 1 */
6552: gsl_vector_set_all (ss, 0.001);
6553:
6554: /* Starting point */
1.126 brouard 6555:
1.136 brouard 6556: x = gsl_vector_alloc (NDIM);
6557:
6558: if (x == NULL){
6559: gsl_vector_free(ss);
6560: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6561: }
6562:
6563: /* Initialize method and iterate */
6564: /* p[1]=0.0268; p[NDIM]=0.083; */
6565: /* gsl_vector_set(x, 0, 0.0268); */
6566: /* gsl_vector_set(x, 1, 0.083); */
6567: gsl_vector_set(x, 0, p[1]);
6568: gsl_vector_set(x, 1, p[2]);
6569:
6570: minex_func.f = &gompertz_f;
6571: minex_func.n = NDIM;
6572: minex_func.params = (void *)&p; /* ??? */
6573:
6574: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6575: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6576:
6577: printf("Iterations beginning .....\n\n");
6578: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6579:
6580: iteri=0;
6581: while (rval == GSL_CONTINUE){
6582: iteri++;
6583: status = gsl_multimin_fminimizer_iterate(sfm);
6584:
6585: if (status) printf("error: %s\n", gsl_strerror (status));
6586: fflush(0);
6587:
6588: if (status)
6589: break;
6590:
6591: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6592: ssval = gsl_multimin_fminimizer_size (sfm);
6593:
6594: if (rval == GSL_SUCCESS)
6595: printf ("converged to a local maximum at\n");
6596:
6597: printf("%5d ", iteri);
6598: for (it = 0; it < NDIM; it++){
6599: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6600: }
6601: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6602: }
6603:
6604: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6605:
6606: gsl_vector_free(x); /* initial values */
6607: gsl_vector_free(ss); /* inital step size */
6608: for (it=0; it<NDIM; it++){
6609: p[it+1]=gsl_vector_get(sfm->x,it);
6610: fprintf(ficrespow," %.12lf", p[it]);
6611: }
6612: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6613: #endif
6614: #ifdef POWELL
6615: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6616: #endif
1.126 brouard 6617: fclose(ficrespow);
6618:
6619: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6620:
6621: for(i=1; i <=NDIM; i++)
6622: for(j=i+1;j<=NDIM;j++)
6623: matcov[i][j]=matcov[j][i];
6624:
6625: printf("\nCovariance matrix\n ");
6626: for(i=1; i <=NDIM; i++) {
6627: for(j=1;j<=NDIM;j++){
6628: printf("%f ",matcov[i][j]);
6629: }
6630: printf("\n ");
6631: }
6632:
6633: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6634: for (i=1;i<=NDIM;i++)
6635: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6636:
6637: lsurv=vector(1,AGESUP);
6638: lpop=vector(1,AGESUP);
6639: tpop=vector(1,AGESUP);
6640: lsurv[agegomp]=100000;
6641:
6642: for (k=agegomp;k<=AGESUP;k++) {
6643: agemortsup=k;
6644: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6645: }
6646:
6647: for (k=agegomp;k<agemortsup;k++)
6648: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6649:
6650: for (k=agegomp;k<agemortsup;k++){
6651: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6652: sumlpop=sumlpop+lpop[k];
6653: }
6654:
6655: tpop[agegomp]=sumlpop;
6656: for (k=agegomp;k<(agemortsup-3);k++){
6657: /* tpop[k+1]=2;*/
6658: tpop[k+1]=tpop[k]-lpop[k];
6659: }
6660:
6661:
6662: printf("\nAge lx qx dx Lx Tx e(x)\n");
6663: for (k=agegomp;k<(agemortsup-2);k++)
6664: 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]);
6665:
6666:
6667: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6668: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6669:
6670: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6671: stepm, weightopt,\
6672: model,imx,p,matcov,agemortsup);
6673:
6674: free_vector(lsurv,1,AGESUP);
6675: free_vector(lpop,1,AGESUP);
6676: free_vector(tpop,1,AGESUP);
1.136 brouard 6677: #ifdef GSL
6678: free_ivector(cens,1,n);
6679: free_vector(agecens,1,n);
6680: free_ivector(dcwave,1,n);
6681: free_matrix(ximort,1,NDIM,1,NDIM);
6682: #endif
1.126 brouard 6683: } /* Endof if mle==-3 */
6684:
6685: else{ /* For mle >=1 */
1.132 brouard 6686: globpr=0;/* debug */
6687: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6688: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6689: for (k=1; k<=npar;k++)
6690: printf(" %d %8.5f",k,p[k]);
6691: printf("\n");
6692: globpr=1; /* to print the contributions */
6693: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6694: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6695: for (k=1; k<=npar;k++)
6696: printf(" %d %8.5f",k,p[k]);
6697: printf("\n");
6698: if(mle>=1){ /* Could be 1 or 2 */
6699: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6700: }
6701:
6702: /*--------- results files --------------*/
6703: 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);
6704:
6705:
6706: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6707: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6708: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6709: for(i=1,jk=1; i <=nlstate; i++){
6710: for(k=1; k <=(nlstate+ndeath); k++){
6711: if (k != i) {
6712: printf("%d%d ",i,k);
6713: fprintf(ficlog,"%d%d ",i,k);
6714: fprintf(ficres,"%1d%1d ",i,k);
6715: for(j=1; j <=ncovmodel; j++){
6716: printf("%lf ",p[jk]);
6717: fprintf(ficlog,"%lf ",p[jk]);
6718: fprintf(ficres,"%lf ",p[jk]);
6719: jk++;
6720: }
6721: printf("\n");
6722: fprintf(ficlog,"\n");
6723: fprintf(ficres,"\n");
6724: }
6725: }
6726: }
6727: if(mle!=0){
6728: /* Computing hessian and covariance matrix */
6729: ftolhess=ftol; /* Usually correct */
6730: hesscov(matcov, p, npar, delti, ftolhess, func);
6731: }
6732: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6733: printf("# Scales (for hessian or gradient estimation)\n");
6734: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6735: for(i=1,jk=1; i <=nlstate; i++){
6736: for(j=1; j <=nlstate+ndeath; j++){
6737: if (j!=i) {
6738: fprintf(ficres,"%1d%1d",i,j);
6739: printf("%1d%1d",i,j);
6740: fprintf(ficlog,"%1d%1d",i,j);
6741: for(k=1; k<=ncovmodel;k++){
6742: printf(" %.5e",delti[jk]);
6743: fprintf(ficlog," %.5e",delti[jk]);
6744: fprintf(ficres," %.5e",delti[jk]);
6745: jk++;
6746: }
6747: printf("\n");
6748: fprintf(ficlog,"\n");
6749: fprintf(ficres,"\n");
6750: }
6751: }
6752: }
6753:
6754: 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");
6755: if(mle>=1)
6756: 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");
6757: 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");
6758: /* # 121 Var(a12)\n\ */
6759: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6760: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6761: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6762: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6763: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6764: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6765: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6766:
6767:
6768: /* Just to have a covariance matrix which will be more understandable
6769: even is we still don't want to manage dictionary of variables
6770: */
6771: for(itimes=1;itimes<=2;itimes++){
6772: jj=0;
6773: for(i=1; i <=nlstate; i++){
6774: for(j=1; j <=nlstate+ndeath; j++){
6775: if(j==i) continue;
6776: for(k=1; k<=ncovmodel;k++){
6777: jj++;
6778: ca[0]= k+'a'-1;ca[1]='\0';
6779: if(itimes==1){
6780: if(mle>=1)
6781: printf("#%1d%1d%d",i,j,k);
6782: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6783: fprintf(ficres,"#%1d%1d%d",i,j,k);
6784: }else{
6785: if(mle>=1)
6786: printf("%1d%1d%d",i,j,k);
6787: fprintf(ficlog,"%1d%1d%d",i,j,k);
6788: fprintf(ficres,"%1d%1d%d",i,j,k);
6789: }
6790: ll=0;
6791: for(li=1;li <=nlstate; li++){
6792: for(lj=1;lj <=nlstate+ndeath; lj++){
6793: if(lj==li) continue;
6794: for(lk=1;lk<=ncovmodel;lk++){
6795: ll++;
6796: if(ll<=jj){
6797: cb[0]= lk +'a'-1;cb[1]='\0';
6798: if(ll<jj){
6799: if(itimes==1){
6800: if(mle>=1)
6801: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6802: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6803: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6804: }else{
6805: if(mle>=1)
6806: printf(" %.5e",matcov[jj][ll]);
6807: fprintf(ficlog," %.5e",matcov[jj][ll]);
6808: fprintf(ficres," %.5e",matcov[jj][ll]);
6809: }
6810: }else{
6811: if(itimes==1){
6812: if(mle>=1)
6813: printf(" Var(%s%1d%1d)",ca,i,j);
6814: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6815: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6816: }else{
6817: if(mle>=1)
6818: printf(" %.5e",matcov[jj][ll]);
6819: fprintf(ficlog," %.5e",matcov[jj][ll]);
6820: fprintf(ficres," %.5e",matcov[jj][ll]);
6821: }
6822: }
6823: }
6824: } /* end lk */
6825: } /* end lj */
6826: } /* end li */
6827: if(mle>=1)
6828: printf("\n");
6829: fprintf(ficlog,"\n");
6830: fprintf(ficres,"\n");
6831: numlinepar++;
6832: } /* end k*/
6833: } /*end j */
6834: } /* end i */
6835: } /* end itimes */
6836:
6837: fflush(ficlog);
6838: fflush(ficres);
6839:
6840: while((c=getc(ficpar))=='#' && c!= EOF){
6841: ungetc(c,ficpar);
6842: fgets(line, MAXLINE, ficpar);
1.141 brouard 6843: fputs(line,stdout);
1.126 brouard 6844: fputs(line,ficparo);
6845: }
6846: ungetc(c,ficpar);
6847:
6848: estepm=0;
6849: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6850: if (estepm==0 || estepm < stepm) estepm=stepm;
6851: if (fage <= 2) {
6852: bage = ageminpar;
6853: fage = agemaxpar;
6854: }
6855:
6856: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6857: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6858: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6859:
6860: while((c=getc(ficpar))=='#' && c!= EOF){
6861: ungetc(c,ficpar);
6862: fgets(line, MAXLINE, ficpar);
1.141 brouard 6863: fputs(line,stdout);
1.126 brouard 6864: fputs(line,ficparo);
6865: }
6866: ungetc(c,ficpar);
6867:
6868: 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);
6869: 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);
6870: 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);
6871: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6872: 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);
6873:
6874: while((c=getc(ficpar))=='#' && c!= EOF){
6875: ungetc(c,ficpar);
6876: fgets(line, MAXLINE, ficpar);
1.141 brouard 6877: fputs(line,stdout);
1.126 brouard 6878: fputs(line,ficparo);
6879: }
6880: ungetc(c,ficpar);
6881:
6882:
6883: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6884: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6885:
6886: fscanf(ficpar,"pop_based=%d\n",&popbased);
6887: fprintf(ficparo,"pop_based=%d\n",popbased);
6888: fprintf(ficres,"pop_based=%d\n",popbased);
6889:
6890: while((c=getc(ficpar))=='#' && c!= EOF){
6891: ungetc(c,ficpar);
6892: fgets(line, MAXLINE, ficpar);
1.141 brouard 6893: fputs(line,stdout);
1.126 brouard 6894: fputs(line,ficparo);
6895: }
6896: ungetc(c,ficpar);
6897:
6898: 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);
6899: 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);
6900: 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);
6901: 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);
6902: 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);
6903: /* day and month of proj2 are not used but only year anproj2.*/
6904:
6905:
6906:
1.145 brouard 6907: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6908: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6909:
6910: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6911: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6912:
6913: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6914: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6915: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6916:
6917: /*------------ free_vector -------------*/
6918: /* chdir(path); */
6919:
6920: free_ivector(wav,1,imx);
6921: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6922: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6923: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6924: free_lvector(num,1,n);
6925: free_vector(agedc,1,n);
6926: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6927: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6928: fclose(ficparo);
6929: fclose(ficres);
6930:
6931:
6932: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 6933: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
6934: prlim=matrix(1,nlstate,1,nlstate);
6935: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 6936: fclose(ficrespl);
6937:
1.145 brouard 6938: #ifdef FREEEXIT2
6939: #include "freeexit2.h"
6940: #endif
6941:
1.126 brouard 6942: /*------------- h Pij x at various ages ------------*/
1.180 brouard 6943: /*#include "hpijx.h"*/
6944: hPijx(p, bage, fage);
1.145 brouard 6945: fclose(ficrespij);
1.126 brouard 6946:
1.145 brouard 6947: /*-------------- Variance of one-step probabilities---*/
6948: k=1;
1.126 brouard 6949: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6950:
6951:
6952: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6953: for(i=1;i<=AGESUP;i++)
6954: for(j=1;j<=NCOVMAX;j++)
6955: for(k=1;k<=NCOVMAX;k++)
6956: probs[i][j][k]=0.;
6957:
6958: /*---------- Forecasting ------------------*/
6959: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6960: if(prevfcast==1){
6961: /* if(stepm ==1){*/
6962: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6963: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6964: /* } */
6965: /* else{ */
6966: /* erreur=108; */
6967: /* 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); */
6968: /* 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); */
6969: /* } */
6970: }
6971:
6972:
1.127 brouard 6973: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6974:
6975: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6976: /* 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",\
6977: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6978: */
1.126 brouard 6979:
1.127 brouard 6980: if (mobilav!=0) {
6981: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6982: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6983: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6984: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6985: }
1.126 brouard 6986: }
6987:
6988:
1.127 brouard 6989: /*---------- Health expectancies, no variances ------------*/
6990:
1.126 brouard 6991: strcpy(filerese,"e");
6992: strcat(filerese,fileres);
6993: if((ficreseij=fopen(filerese,"w"))==NULL) {
6994: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6995: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6996: }
6997: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6998: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6999: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7000: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7001:
7002: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7003: fprintf(ficreseij,"\n#****** ");
7004: for(j=1;j<=cptcoveff;j++) {
7005: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7006: }
7007: fprintf(ficreseij,"******\n");
7008:
7009: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7010: oldm=oldms;savm=savms;
7011: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7012:
7013: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7014: /*}*/
1.127 brouard 7015: }
7016: fclose(ficreseij);
7017:
7018:
7019: /*---------- Health expectancies and variances ------------*/
7020:
7021:
7022: strcpy(filerest,"t");
7023: strcat(filerest,fileres);
7024: if((ficrest=fopen(filerest,"w"))==NULL) {
7025: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7026: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7027: }
7028: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7029: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7030:
1.126 brouard 7031:
7032: strcpy(fileresstde,"stde");
7033: strcat(fileresstde,fileres);
7034: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7035: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7036: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7037: }
7038: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7039: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7040:
7041: strcpy(filerescve,"cve");
7042: strcat(filerescve,fileres);
7043: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7044: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7045: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7046: }
7047: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7048: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7049:
7050: strcpy(fileresv,"v");
7051: strcat(fileresv,fileres);
7052: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7053: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7054: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7055: }
7056: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7057: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7058:
1.145 brouard 7059: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7060: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7061:
7062: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7063: fprintf(ficrest,"\n#****** ");
1.126 brouard 7064: for(j=1;j<=cptcoveff;j++)
7065: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7066: fprintf(ficrest,"******\n");
7067:
7068: fprintf(ficresstdeij,"\n#****** ");
7069: fprintf(ficrescveij,"\n#****** ");
7070: for(j=1;j<=cptcoveff;j++) {
7071: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7072: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7073: }
7074: fprintf(ficresstdeij,"******\n");
7075: fprintf(ficrescveij,"******\n");
7076:
7077: fprintf(ficresvij,"\n#****** ");
7078: for(j=1;j<=cptcoveff;j++)
7079: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7080: fprintf(ficresvij,"******\n");
7081:
7082: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7083: oldm=oldms;savm=savms;
1.127 brouard 7084: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7085: /*
7086: */
7087: /* goto endfree; */
1.126 brouard 7088:
7089: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7090: pstamp(ficrest);
1.145 brouard 7091:
7092:
1.128 brouard 7093: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 7094: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 7095: cptcod= 0; /* To be deleted */
7096: 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 7097: 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 7098: if(vpopbased==1)
7099: 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);
7100: else
7101: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7102: fprintf(ficrest,"# Age e.. (std) ");
7103: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7104: fprintf(ficrest,"\n");
1.126 brouard 7105:
1.128 brouard 7106: epj=vector(1,nlstate+1);
7107: for(age=bage; age <=fage ;age++){
7108: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7109: if (vpopbased==1) {
7110: if(mobilav ==0){
7111: for(i=1; i<=nlstate;i++)
7112: prlim[i][i]=probs[(int)age][i][k];
7113: }else{ /* mobilav */
7114: for(i=1; i<=nlstate;i++)
7115: prlim[i][i]=mobaverage[(int)age][i][k];
7116: }
1.126 brouard 7117: }
7118:
1.128 brouard 7119: fprintf(ficrest," %4.0f",age);
7120: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7121: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7122: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7123: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7124: }
7125: epj[nlstate+1] +=epj[j];
1.126 brouard 7126: }
7127:
1.128 brouard 7128: for(i=1, vepp=0.;i <=nlstate;i++)
7129: for(j=1;j <=nlstate;j++)
7130: vepp += vareij[i][j][(int)age];
7131: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7132: for(j=1;j <=nlstate;j++){
7133: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7134: }
7135: fprintf(ficrest,"\n");
1.126 brouard 7136: }
7137: }
7138: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7139: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7140: free_vector(epj,1,nlstate+1);
1.145 brouard 7141: /*}*/
1.126 brouard 7142: }
7143: free_vector(weight,1,n);
1.145 brouard 7144: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7145: free_imatrix(s,1,maxwav+1,1,n);
7146: free_matrix(anint,1,maxwav,1,n);
7147: free_matrix(mint,1,maxwav,1,n);
7148: free_ivector(cod,1,n);
7149: free_ivector(tab,1,NCOVMAX);
7150: fclose(ficresstdeij);
7151: fclose(ficrescveij);
7152: fclose(ficresvij);
7153: fclose(ficrest);
7154: fclose(ficpar);
7155:
7156: /*------- Variance of period (stable) prevalence------*/
7157:
7158: strcpy(fileresvpl,"vpl");
7159: strcat(fileresvpl,fileres);
7160: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7161: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7162: exit(0);
7163: }
7164: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7165:
1.145 brouard 7166: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7167: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7168:
7169: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7170: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7171: for(j=1;j<=cptcoveff;j++)
7172: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7173: fprintf(ficresvpl,"******\n");
7174:
7175: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7176: oldm=oldms;savm=savms;
7177: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7178: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7179: /*}*/
1.126 brouard 7180: }
7181:
7182: fclose(ficresvpl);
7183:
7184: /*---------- End : free ----------------*/
7185: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7186: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7187: } /* mle==-3 arrives here for freeing */
1.164 brouard 7188: /* endfree:*/
1.141 brouard 7189: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7190: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7191: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7192: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7193: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7194: free_matrix(covar,0,NCOVMAX,1,n);
7195: free_matrix(matcov,1,npar,1,npar);
7196: /*free_vector(delti,1,npar);*/
7197: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7198: free_matrix(agev,1,maxwav,1,imx);
7199: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7200:
1.145 brouard 7201: free_ivector(ncodemax,1,NCOVMAX);
7202: free_ivector(Tvar,1,NCOVMAX);
7203: free_ivector(Tprod,1,NCOVMAX);
7204: free_ivector(Tvaraff,1,NCOVMAX);
7205: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7206:
7207: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7208: free_imatrix(codtab,1,100,1,10);
7209: fflush(fichtm);
7210: fflush(ficgp);
7211:
7212:
7213: if((nberr >0) || (nbwarn>0)){
7214: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7215: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7216: }else{
7217: printf("End of Imach\n");
7218: fprintf(ficlog,"End of Imach\n");
7219: }
7220: printf("See log file on %s\n",filelog);
7221: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7222: /*(void) gettimeofday(&end_time,&tzp);*/
7223: rend_time = time(NULL);
7224: end_time = *localtime(&rend_time);
7225: /* tml = *localtime(&end_time.tm_sec); */
7226: strcpy(strtend,asctime(&end_time));
1.126 brouard 7227: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7228: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7229: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7230:
1.157 brouard 7231: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7232: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7233: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7234: /* printf("Total time was %d uSec.\n", total_usecs);*/
7235: /* if(fileappend(fichtm,optionfilehtm)){ */
7236: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7237: fclose(fichtm);
7238: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7239: fclose(fichtmcov);
7240: fclose(ficgp);
7241: fclose(ficlog);
7242: /*------ End -----------*/
7243:
7244:
7245: printf("Before Current directory %s!\n",pathcd);
7246: if(chdir(pathcd) != 0)
7247: printf("Can't move to directory %s!\n",path);
7248: if(getcwd(pathcd,MAXLINE) > 0)
7249: printf("Current directory %s!\n",pathcd);
7250: /*strcat(plotcmd,CHARSEPARATOR);*/
7251: sprintf(plotcmd,"gnuplot");
1.157 brouard 7252: #ifdef _WIN32
1.126 brouard 7253: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7254: #endif
7255: if(!stat(plotcmd,&info)){
1.158 brouard 7256: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7257: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7258: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7259: }else
7260: strcpy(pplotcmd,plotcmd);
1.157 brouard 7261: #ifdef __unix
1.126 brouard 7262: strcpy(plotcmd,GNUPLOTPROGRAM);
7263: if(!stat(plotcmd,&info)){
1.158 brouard 7264: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7265: }else
7266: strcpy(pplotcmd,plotcmd);
7267: #endif
7268: }else
7269: strcpy(pplotcmd,plotcmd);
7270:
7271: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7272: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7273:
7274: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7275: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7276: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7277: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7278: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7279: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7280: }
1.158 brouard 7281: printf(" Successful, please wait...");
1.126 brouard 7282: while (z[0] != 'q') {
7283: /* chdir(path); */
1.154 brouard 7284: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7285: scanf("%s",z);
7286: /* if (z[0] == 'c') system("./imach"); */
7287: if (z[0] == 'e') {
1.158 brouard 7288: #ifdef __APPLE__
1.152 brouard 7289: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7290: #elif __linux
7291: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7292: #else
1.152 brouard 7293: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7294: #endif
7295: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7296: system(pplotcmd);
1.126 brouard 7297: }
7298: else if (z[0] == 'g') system(plotcmd);
7299: else if (z[0] == 'q') exit(0);
7300: }
7301: end:
7302: while (z[0] != 'q') {
7303: printf("\nType q for exiting: ");
7304: scanf("%s",z);
7305: }
7306: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>