Annotation of imach/src/imach.c, revision 1.200
1.200 ! brouard 1: /* $Id: imach.c,v 1.199 2015/09/07 14:09:23 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.200 ! brouard 4: Revision 1.199 2015/09/07 14:09:23 brouard
! 5: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
! 6:
1.199 brouard 7: Revision 1.198 2015/09/03 07:14:39 brouard
8: Summary: 0.98q5 Flavia
9:
1.198 brouard 10: Revision 1.197 2015/09/01 18:24:39 brouard
11: *** empty log message ***
12:
1.197 brouard 13: Revision 1.196 2015/08/18 23:17:52 brouard
14: Summary: 0.98q5
15:
1.196 brouard 16: Revision 1.195 2015/08/18 16:28:39 brouard
17: Summary: Adding a hack for testing purpose
18:
19: After reading the title, ftol and model lines, if the comment line has
20: a q, starting with #q, the answer at the end of the run is quit. It
21: permits to run test files in batch with ctest. The former workaround was
22: $ echo q | imach foo.imach
23:
1.195 brouard 24: Revision 1.194 2015/08/18 13:32:00 brouard
25: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
26:
1.194 brouard 27: Revision 1.193 2015/08/04 07:17:42 brouard
28: Summary: 0.98q4
29:
1.193 brouard 30: Revision 1.192 2015/07/16 16:49:02 brouard
31: Summary: Fixing some outputs
32:
1.192 brouard 33: Revision 1.191 2015/07/14 10:00:33 brouard
34: Summary: Some fixes
35:
1.191 brouard 36: Revision 1.190 2015/05/05 08:51:13 brouard
37: Summary: Adding digits in output parameters (7 digits instead of 6)
38:
39: Fix 1+age+.
40:
1.190 brouard 41: Revision 1.189 2015/04/30 14:45:16 brouard
42: Summary: 0.98q2
43:
1.189 brouard 44: Revision 1.188 2015/04/30 08:27:53 brouard
45: *** empty log message ***
46:
1.188 brouard 47: Revision 1.187 2015/04/29 09:11:15 brouard
48: *** empty log message ***
49:
1.187 brouard 50: Revision 1.186 2015/04/23 12:01:52 brouard
51: Summary: V1*age is working now, version 0.98q1
52:
53: Some codes had been disabled in order to simplify and Vn*age was
54: working in the optimization phase, ie, giving correct MLE parameters,
55: but, as usual, outputs were not correct and program core dumped.
56:
1.186 brouard 57: Revision 1.185 2015/03/11 13:26:42 brouard
58: Summary: Inclusion of compile and links command line for Intel Compiler
59:
1.185 brouard 60: Revision 1.184 2015/03/11 11:52:39 brouard
61: Summary: Back from Windows 8. Intel Compiler
62:
1.184 brouard 63: Revision 1.183 2015/03/10 20:34:32 brouard
64: Summary: 0.98q0, trying with directest, mnbrak fixed
65:
66: We use directest instead of original Powell test; probably no
67: incidence on the results, but better justifications;
68: We fixed Numerical Recipes mnbrak routine which was wrong and gave
69: wrong results.
70:
1.183 brouard 71: Revision 1.182 2015/02/12 08:19:57 brouard
72: Summary: Trying to keep directest which seems simpler and more general
73: Author: Nicolas Brouard
74:
1.182 brouard 75: Revision 1.181 2015/02/11 23:22:24 brouard
76: Summary: Comments on Powell added
77:
78: Author:
79:
1.181 brouard 80: Revision 1.180 2015/02/11 17:33:45 brouard
81: Summary: Finishing move from main to function (hpijx and prevalence_limit)
82:
1.180 brouard 83: Revision 1.179 2015/01/04 09:57:06 brouard
84: Summary: back to OS/X
85:
1.179 brouard 86: Revision 1.178 2015/01/04 09:35:48 brouard
87: *** empty log message ***
88:
1.178 brouard 89: Revision 1.177 2015/01/03 18:40:56 brouard
90: Summary: Still testing ilc32 on OSX
91:
1.177 brouard 92: Revision 1.176 2015/01/03 16:45:04 brouard
93: *** empty log message ***
94:
1.176 brouard 95: Revision 1.175 2015/01/03 16:33:42 brouard
96: *** empty log message ***
97:
1.175 brouard 98: Revision 1.174 2015/01/03 16:15:49 brouard
99: Summary: Still in cross-compilation
100:
1.174 brouard 101: Revision 1.173 2015/01/03 12:06:26 brouard
102: Summary: trying to detect cross-compilation
103:
1.173 brouard 104: Revision 1.172 2014/12/27 12:07:47 brouard
105: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
106:
1.172 brouard 107: Revision 1.171 2014/12/23 13:26:59 brouard
108: Summary: Back from Visual C
109:
110: Still problem with utsname.h on Windows
111:
1.171 brouard 112: Revision 1.170 2014/12/23 11:17:12 brouard
113: Summary: Cleaning some \%% back to %%
114:
115: The escape was mandatory for a specific compiler (which one?), but too many warnings.
116:
1.170 brouard 117: Revision 1.169 2014/12/22 23:08:31 brouard
118: Summary: 0.98p
119:
120: Outputs some informations on compiler used, OS etc. Testing on different platforms.
121:
1.169 brouard 122: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 123: Summary: update
1.169 brouard 124:
1.168 brouard 125: Revision 1.167 2014/12/22 13:50:56 brouard
126: Summary: Testing uname and compiler version and if compiled 32 or 64
127:
128: Testing on Linux 64
129:
1.167 brouard 130: Revision 1.166 2014/12/22 11:40:47 brouard
131: *** empty log message ***
132:
1.166 brouard 133: Revision 1.165 2014/12/16 11:20:36 brouard
134: Summary: After compiling on Visual C
135:
136: * imach.c (Module): Merging 1.61 to 1.162
137:
1.165 brouard 138: Revision 1.164 2014/12/16 10:52:11 brouard
139: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
140:
141: * imach.c (Module): Merging 1.61 to 1.162
142:
1.164 brouard 143: Revision 1.163 2014/12/16 10:30:11 brouard
144: * imach.c (Module): Merging 1.61 to 1.162
145:
1.163 brouard 146: Revision 1.162 2014/09/25 11:43:39 brouard
147: Summary: temporary backup 0.99!
148:
1.162 brouard 149: Revision 1.1 2014/09/16 11:06:58 brouard
150: Summary: With some code (wrong) for nlopt
151:
152: Author:
153:
154: Revision 1.161 2014/09/15 20:41:41 brouard
155: Summary: Problem with macro SQR on Intel compiler
156:
1.161 brouard 157: Revision 1.160 2014/09/02 09:24:05 brouard
158: *** empty log message ***
159:
1.160 brouard 160: Revision 1.159 2014/09/01 10:34:10 brouard
161: Summary: WIN32
162: Author: Brouard
163:
1.159 brouard 164: Revision 1.158 2014/08/27 17:11:51 brouard
165: *** empty log message ***
166:
1.158 brouard 167: Revision 1.157 2014/08/27 16:26:55 brouard
168: Summary: Preparing windows Visual studio version
169: Author: Brouard
170:
171: In order to compile on Visual studio, time.h is now correct and time_t
172: and tm struct should be used. difftime should be used but sometimes I
173: just make the differences in raw time format (time(&now).
174: Trying to suppress #ifdef LINUX
175: Add xdg-open for __linux in order to open default browser.
176:
1.157 brouard 177: Revision 1.156 2014/08/25 20:10:10 brouard
178: *** empty log message ***
179:
1.156 brouard 180: Revision 1.155 2014/08/25 18:32:34 brouard
181: Summary: New compile, minor changes
182: Author: Brouard
183:
1.155 brouard 184: Revision 1.154 2014/06/20 17:32:08 brouard
185: Summary: Outputs now all graphs of convergence to period prevalence
186:
1.154 brouard 187: Revision 1.153 2014/06/20 16:45:46 brouard
188: Summary: If 3 live state, convergence to period prevalence on same graph
189: Author: Brouard
190:
1.153 brouard 191: Revision 1.152 2014/06/18 17:54:09 brouard
192: Summary: open browser, use gnuplot on same dir than imach if not found in the path
193:
1.152 brouard 194: Revision 1.151 2014/06/18 16:43:30 brouard
195: *** empty log message ***
196:
1.151 brouard 197: Revision 1.150 2014/06/18 16:42:35 brouard
198: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
199: Author: brouard
200:
1.150 brouard 201: Revision 1.149 2014/06/18 15:51:14 brouard
202: Summary: Some fixes in parameter files errors
203: Author: Nicolas Brouard
204:
1.149 brouard 205: Revision 1.148 2014/06/17 17:38:48 brouard
206: Summary: Nothing new
207: Author: Brouard
208:
209: Just a new packaging for OS/X version 0.98nS
210:
1.148 brouard 211: Revision 1.147 2014/06/16 10:33:11 brouard
212: *** empty log message ***
213:
1.147 brouard 214: Revision 1.146 2014/06/16 10:20:28 brouard
215: Summary: Merge
216: Author: Brouard
217:
218: Merge, before building revised version.
219:
1.146 brouard 220: Revision 1.145 2014/06/10 21:23:15 brouard
221: Summary: Debugging with valgrind
222: Author: Nicolas Brouard
223:
224: Lot of changes in order to output the results with some covariates
225: After the Edimburgh REVES conference 2014, it seems mandatory to
226: improve the code.
227: No more memory valgrind error but a lot has to be done in order to
228: continue the work of splitting the code into subroutines.
229: Also, decodemodel has been improved. Tricode is still not
230: optimal. nbcode should be improved. Documentation has been added in
231: the source code.
232:
1.144 brouard 233: Revision 1.143 2014/01/26 09:45:38 brouard
234: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
235:
236: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
237: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
238:
1.143 brouard 239: Revision 1.142 2014/01/26 03:57:36 brouard
240: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
241:
242: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
243:
1.142 brouard 244: Revision 1.141 2014/01/26 02:42:01 brouard
245: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
246:
1.141 brouard 247: Revision 1.140 2011/09/02 10:37:54 brouard
248: Summary: times.h is ok with mingw32 now.
249:
1.140 brouard 250: Revision 1.139 2010/06/14 07:50:17 brouard
251: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
252: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
253:
1.139 brouard 254: Revision 1.138 2010/04/30 18:19:40 brouard
255: *** empty log message ***
256:
1.138 brouard 257: Revision 1.137 2010/04/29 18:11:38 brouard
258: (Module): Checking covariates for more complex models
259: than V1+V2. A lot of change to be done. Unstable.
260:
1.137 brouard 261: Revision 1.136 2010/04/26 20:30:53 brouard
262: (Module): merging some libgsl code. Fixing computation
263: of likelione (using inter/intrapolation if mle = 0) in order to
264: get same likelihood as if mle=1.
265: Some cleaning of code and comments added.
266:
1.136 brouard 267: Revision 1.135 2009/10/29 15:33:14 brouard
268: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
269:
1.135 brouard 270: Revision 1.134 2009/10/29 13:18:53 brouard
271: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
272:
1.134 brouard 273: Revision 1.133 2009/07/06 10:21:25 brouard
274: just nforces
275:
1.133 brouard 276: Revision 1.132 2009/07/06 08:22:05 brouard
277: Many tings
278:
1.132 brouard 279: Revision 1.131 2009/06/20 16:22:47 brouard
280: Some dimensions resccaled
281:
1.131 brouard 282: Revision 1.130 2009/05/26 06:44:34 brouard
283: (Module): Max Covariate is now set to 20 instead of 8. A
284: lot of cleaning with variables initialized to 0. Trying to make
285: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
286:
1.130 brouard 287: Revision 1.129 2007/08/31 13:49:27 lievre
288: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
289:
1.129 lievre 290: Revision 1.128 2006/06/30 13:02:05 brouard
291: (Module): Clarifications on computing e.j
292:
1.128 brouard 293: Revision 1.127 2006/04/28 18:11:50 brouard
294: (Module): Yes the sum of survivors was wrong since
295: imach-114 because nhstepm was no more computed in the age
296: loop. Now we define nhstepma in the age loop.
297: (Module): In order to speed up (in case of numerous covariates) we
298: compute health expectancies (without variances) in a first step
299: and then all the health expectancies with variances or standard
300: deviation (needs data from the Hessian matrices) which slows the
301: computation.
302: In the future we should be able to stop the program is only health
303: expectancies and graph are needed without standard deviations.
304:
1.127 brouard 305: Revision 1.126 2006/04/28 17:23:28 brouard
306: (Module): Yes the sum of survivors was wrong since
307: imach-114 because nhstepm was no more computed in the age
308: loop. Now we define nhstepma in the age loop.
309: Version 0.98h
310:
1.126 brouard 311: Revision 1.125 2006/04/04 15:20:31 lievre
312: Errors in calculation of health expectancies. Age was not initialized.
313: Forecasting file added.
314:
315: Revision 1.124 2006/03/22 17:13:53 lievre
316: Parameters are printed with %lf instead of %f (more numbers after the comma).
317: The log-likelihood is printed in the log file
318:
319: Revision 1.123 2006/03/20 10:52:43 brouard
320: * imach.c (Module): <title> changed, corresponds to .htm file
321: name. <head> headers where missing.
322:
323: * imach.c (Module): Weights can have a decimal point as for
324: English (a comma might work with a correct LC_NUMERIC environment,
325: otherwise the weight is truncated).
326: Modification of warning when the covariates values are not 0 or
327: 1.
328: Version 0.98g
329:
330: Revision 1.122 2006/03/20 09:45:41 brouard
331: (Module): Weights can have a decimal point as for
332: English (a comma might work with a correct LC_NUMERIC environment,
333: otherwise the weight is truncated).
334: Modification of warning when the covariates values are not 0 or
335: 1.
336: Version 0.98g
337:
338: Revision 1.121 2006/03/16 17:45:01 lievre
339: * imach.c (Module): Comments concerning covariates added
340:
341: * imach.c (Module): refinements in the computation of lli if
342: status=-2 in order to have more reliable computation if stepm is
343: not 1 month. Version 0.98f
344:
345: Revision 1.120 2006/03/16 15:10:38 lievre
346: (Module): refinements in the computation of lli if
347: status=-2 in order to have more reliable computation if stepm is
348: not 1 month. Version 0.98f
349:
350: Revision 1.119 2006/03/15 17:42:26 brouard
351: (Module): Bug if status = -2, the loglikelihood was
352: computed as likelihood omitting the logarithm. Version O.98e
353:
354: Revision 1.118 2006/03/14 18:20:07 brouard
355: (Module): varevsij Comments added explaining the second
356: table of variances if popbased=1 .
357: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
358: (Module): Function pstamp added
359: (Module): Version 0.98d
360:
361: Revision 1.117 2006/03/14 17:16:22 brouard
362: (Module): varevsij Comments added explaining the second
363: table of variances if popbased=1 .
364: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
365: (Module): Function pstamp added
366: (Module): Version 0.98d
367:
368: Revision 1.116 2006/03/06 10:29:27 brouard
369: (Module): Variance-covariance wrong links and
370: varian-covariance of ej. is needed (Saito).
371:
372: Revision 1.115 2006/02/27 12:17:45 brouard
373: (Module): One freematrix added in mlikeli! 0.98c
374:
375: Revision 1.114 2006/02/26 12:57:58 brouard
376: (Module): Some improvements in processing parameter
377: filename with strsep.
378:
379: Revision 1.113 2006/02/24 14:20:24 brouard
380: (Module): Memory leaks checks with valgrind and:
381: datafile was not closed, some imatrix were not freed and on matrix
382: allocation too.
383:
384: Revision 1.112 2006/01/30 09:55:26 brouard
385: (Module): Back to gnuplot.exe instead of wgnuplot.exe
386:
387: Revision 1.111 2006/01/25 20:38:18 brouard
388: (Module): Lots of cleaning and bugs added (Gompertz)
389: (Module): Comments can be added in data file. Missing date values
390: can be a simple dot '.'.
391:
392: Revision 1.110 2006/01/25 00:51:50 brouard
393: (Module): Lots of cleaning and bugs added (Gompertz)
394:
395: Revision 1.109 2006/01/24 19:37:15 brouard
396: (Module): Comments (lines starting with a #) are allowed in data.
397:
398: Revision 1.108 2006/01/19 18:05:42 lievre
399: Gnuplot problem appeared...
400: To be fixed
401:
402: Revision 1.107 2006/01/19 16:20:37 brouard
403: Test existence of gnuplot in imach path
404:
405: Revision 1.106 2006/01/19 13:24:36 brouard
406: Some cleaning and links added in html output
407:
408: Revision 1.105 2006/01/05 20:23:19 lievre
409: *** empty log message ***
410:
411: Revision 1.104 2005/09/30 16:11:43 lievre
412: (Module): sump fixed, loop imx fixed, and simplifications.
413: (Module): If the status is missing at the last wave but we know
414: that the person is alive, then we can code his/her status as -2
415: (instead of missing=-1 in earlier versions) and his/her
416: contributions to the likelihood is 1 - Prob of dying from last
417: health status (= 1-p13= p11+p12 in the easiest case of somebody in
418: the healthy state at last known wave). Version is 0.98
419:
420: Revision 1.103 2005/09/30 15:54:49 lievre
421: (Module): sump fixed, loop imx fixed, and simplifications.
422:
423: Revision 1.102 2004/09/15 17:31:30 brouard
424: Add the possibility to read data file including tab characters.
425:
426: Revision 1.101 2004/09/15 10:38:38 brouard
427: Fix on curr_time
428:
429: Revision 1.100 2004/07/12 18:29:06 brouard
430: Add version for Mac OS X. Just define UNIX in Makefile
431:
432: Revision 1.99 2004/06/05 08:57:40 brouard
433: *** empty log message ***
434:
435: Revision 1.98 2004/05/16 15:05:56 brouard
436: New version 0.97 . First attempt to estimate force of mortality
437: directly from the data i.e. without the need of knowing the health
438: state at each age, but using a Gompertz model: log u =a + b*age .
439: This is the basic analysis of mortality and should be done before any
440: other analysis, in order to test if the mortality estimated from the
441: cross-longitudinal survey is different from the mortality estimated
442: from other sources like vital statistic data.
443:
444: The same imach parameter file can be used but the option for mle should be -3.
445:
1.133 brouard 446: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 447: former routines in order to include the new code within the former code.
448:
449: The output is very simple: only an estimate of the intercept and of
450: the slope with 95% confident intervals.
451:
452: Current limitations:
453: A) Even if you enter covariates, i.e. with the
454: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
455: B) There is no computation of Life Expectancy nor Life Table.
456:
457: Revision 1.97 2004/02/20 13:25:42 lievre
458: Version 0.96d. Population forecasting command line is (temporarily)
459: suppressed.
460:
461: Revision 1.96 2003/07/15 15:38:55 brouard
462: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
463: rewritten within the same printf. Workaround: many printfs.
464:
465: Revision 1.95 2003/07/08 07:54:34 brouard
466: * imach.c (Repository):
467: (Repository): Using imachwizard code to output a more meaningful covariance
468: matrix (cov(a12,c31) instead of numbers.
469:
470: Revision 1.94 2003/06/27 13:00:02 brouard
471: Just cleaning
472:
473: Revision 1.93 2003/06/25 16:33:55 brouard
474: (Module): On windows (cygwin) function asctime_r doesn't
475: exist so I changed back to asctime which exists.
476: (Module): Version 0.96b
477:
478: Revision 1.92 2003/06/25 16:30:45 brouard
479: (Module): On windows (cygwin) function asctime_r doesn't
480: exist so I changed back to asctime which exists.
481:
482: Revision 1.91 2003/06/25 15:30:29 brouard
483: * imach.c (Repository): Duplicated warning errors corrected.
484: (Repository): Elapsed time after each iteration is now output. It
485: helps to forecast when convergence will be reached. Elapsed time
486: is stamped in powell. We created a new html file for the graphs
487: concerning matrix of covariance. It has extension -cov.htm.
488:
489: Revision 1.90 2003/06/24 12:34:15 brouard
490: (Module): Some bugs corrected for windows. Also, when
491: mle=-1 a template is output in file "or"mypar.txt with the design
492: of the covariance matrix to be input.
493:
494: Revision 1.89 2003/06/24 12:30:52 brouard
495: (Module): Some bugs corrected for windows. Also, when
496: mle=-1 a template is output in file "or"mypar.txt with the design
497: of the covariance matrix to be input.
498:
499: Revision 1.88 2003/06/23 17:54:56 brouard
500: * 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.
501:
502: Revision 1.87 2003/06/18 12:26:01 brouard
503: Version 0.96
504:
505: Revision 1.86 2003/06/17 20:04:08 brouard
506: (Module): Change position of html and gnuplot routines and added
507: routine fileappend.
508:
509: Revision 1.85 2003/06/17 13:12:43 brouard
510: * imach.c (Repository): Check when date of death was earlier that
511: current date of interview. It may happen when the death was just
512: prior to the death. In this case, dh was negative and likelihood
513: was wrong (infinity). We still send an "Error" but patch by
514: assuming that the date of death was just one stepm after the
515: interview.
516: (Repository): Because some people have very long ID (first column)
517: we changed int to long in num[] and we added a new lvector for
518: memory allocation. But we also truncated to 8 characters (left
519: truncation)
520: (Repository): No more line truncation errors.
521:
522: Revision 1.84 2003/06/13 21:44:43 brouard
523: * imach.c (Repository): Replace "freqsummary" at a correct
524: place. It differs from routine "prevalence" which may be called
525: many times. Probs is memory consuming and must be used with
526: parcimony.
527: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
528:
529: Revision 1.83 2003/06/10 13:39:11 lievre
530: *** empty log message ***
531:
532: Revision 1.82 2003/06/05 15:57:20 brouard
533: Add log in imach.c and fullversion number is now printed.
534:
535: */
536: /*
537: Interpolated Markov Chain
538:
539: Short summary of the programme:
540:
541: This program computes Healthy Life Expectancies from
542: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
543: first survey ("cross") where individuals from different ages are
544: interviewed on their health status or degree of disability (in the
545: case of a health survey which is our main interest) -2- at least a
546: second wave of interviews ("longitudinal") which measure each change
547: (if any) in individual health status. Health expectancies are
548: computed from the time spent in each health state according to a
549: model. More health states you consider, more time is necessary to reach the
550: Maximum Likelihood of the parameters involved in the model. The
551: simplest model is the multinomial logistic model where pij is the
552: probability to be observed in state j at the second wave
553: conditional to be observed in state i at the first wave. Therefore
554: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
555: 'age' is age and 'sex' is a covariate. If you want to have a more
556: complex model than "constant and age", you should modify the program
557: where the markup *Covariates have to be included here again* invites
558: you to do it. More covariates you add, slower the
559: convergence.
560:
561: The advantage of this computer programme, compared to a simple
562: multinomial logistic model, is clear when the delay between waves is not
563: identical for each individual. Also, if a individual missed an
564: intermediate interview, the information is lost, but taken into
565: account using an interpolation or extrapolation.
566:
567: hPijx is the probability to be observed in state i at age x+h
568: conditional to the observed state i at age x. The delay 'h' can be
569: split into an exact number (nh*stepm) of unobserved intermediate
570: states. This elementary transition (by month, quarter,
571: semester or year) is modelled as a multinomial logistic. The hPx
572: matrix is simply the matrix product of nh*stepm elementary matrices
573: and the contribution of each individual to the likelihood is simply
574: hPijx.
575:
576: Also this programme outputs the covariance matrix of the parameters but also
577: of the life expectancies. It also computes the period (stable) prevalence.
578:
1.133 brouard 579: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
580: Institut national d'études démographiques, Paris.
1.126 brouard 581: This software have been partly granted by Euro-REVES, a concerted action
582: from the European Union.
583: It is copyrighted identically to a GNU software product, ie programme and
584: software can be distributed freely for non commercial use. Latest version
585: can be accessed at http://euroreves.ined.fr/imach .
586:
587: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
588: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
589:
590: **********************************************************************/
591: /*
592: main
593: read parameterfile
594: read datafile
595: concatwav
596: freqsummary
597: if (mle >= 1)
598: mlikeli
599: print results files
600: if mle==1
601: computes hessian
602: read end of parameter file: agemin, agemax, bage, fage, estepm
603: begin-prev-date,...
604: open gnuplot file
605: open html file
1.145 brouard 606: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
607: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
608: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
609: freexexit2 possible for memory heap.
610:
611: h Pij x | pij_nom ficrestpij
612: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
613: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
614: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
615:
616: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
617: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
618: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
619: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
620: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
621:
1.126 brouard 622: forecasting if prevfcast==1 prevforecast call prevalence()
623: health expectancies
624: Variance-covariance of DFLE
625: prevalence()
626: movingaverage()
627: varevsij()
628: if popbased==1 varevsij(,popbased)
629: total life expectancies
630: Variance of period (stable) prevalence
631: end
632: */
633:
1.187 brouard 634: /* #define DEBUG */
635: /* #define DEBUGBRENT */
1.165 brouard 636: #define POWELL /* Instead of NLOPT */
1.192 brouard 637: #define POWELLF1F3 /* Skip test */
1.186 brouard 638: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
639: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 640:
641: #include <math.h>
642: #include <stdio.h>
643: #include <stdlib.h>
644: #include <string.h>
1.159 brouard 645:
646: #ifdef _WIN32
647: #include <io.h>
1.172 brouard 648: #include <windows.h>
649: #include <tchar.h>
1.159 brouard 650: #else
1.126 brouard 651: #include <unistd.h>
1.159 brouard 652: #endif
1.126 brouard 653:
654: #include <limits.h>
655: #include <sys/types.h>
1.171 brouard 656:
657: #if defined(__GNUC__)
658: #include <sys/utsname.h> /* Doesn't work on Windows */
659: #endif
660:
1.126 brouard 661: #include <sys/stat.h>
662: #include <errno.h>
1.159 brouard 663: /* extern int errno; */
1.126 brouard 664:
1.157 brouard 665: /* #ifdef LINUX */
666: /* #include <time.h> */
667: /* #include "timeval.h" */
668: /* #else */
669: /* #include <sys/time.h> */
670: /* #endif */
671:
1.126 brouard 672: #include <time.h>
673:
1.136 brouard 674: #ifdef GSL
675: #include <gsl/gsl_errno.h>
676: #include <gsl/gsl_multimin.h>
677: #endif
678:
1.167 brouard 679:
1.162 brouard 680: #ifdef NLOPT
681: #include <nlopt.h>
682: typedef struct {
683: double (* function)(double [] );
684: } myfunc_data ;
685: #endif
686:
1.126 brouard 687: /* #include <libintl.h> */
688: /* #define _(String) gettext (String) */
689:
1.141 brouard 690: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 691:
692: #define GNUPLOTPROGRAM "gnuplot"
693: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
694: #define FILENAMELENGTH 132
695:
696: #define GLOCK_ERROR_NOPATH -1 /* empty path */
697: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
698:
1.144 brouard 699: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
700: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 701:
702: #define NINTERVMAX 8
1.144 brouard 703: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
704: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
705: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197 brouard 706: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.126 brouard 707: #define MAXN 20000
1.144 brouard 708: #define YEARM 12. /**< Number of months per year */
1.126 brouard 709: #define AGESUP 130
710: #define AGEBASE 40
1.194 brouard 711: #define AGEOVERFLOW 1.e20
1.164 brouard 712: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 713: #ifdef _WIN32
714: #define DIRSEPARATOR '\\'
715: #define CHARSEPARATOR "\\"
716: #define ODIRSEPARATOR '/'
717: #else
1.126 brouard 718: #define DIRSEPARATOR '/'
719: #define CHARSEPARATOR "/"
720: #define ODIRSEPARATOR '\\'
721: #endif
722:
1.200 ! brouard 723: /* $Id: imach.c,v 1.199 2015/09/07 14:09:23 brouard Exp $ */
1.126 brouard 724: /* $State: Exp $ */
1.196 brouard 725: #include "version.h"
726: char version[]=__IMACH_VERSION__;
1.197 brouard 727: char copyright[]="September 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.200 ! brouard 728: char fullversion[]="$Revision: 1.199 $ $Date: 2015/09/07 14:09:23 $";
1.126 brouard 729: char strstart[80];
730: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 731: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 732: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 733: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
734: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
735: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
736: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
737: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
738: int cptcovprodnoage=0; /**< Number of covariate products without age */
739: int cptcoveff=0; /* Total number of covariates to vary for printing results */
740: int cptcov=0; /* Working variable */
1.126 brouard 741: int npar=NPARMAX;
742: int nlstate=2; /* Number of live states */
743: int ndeath=1; /* Number of dead states */
1.130 brouard 744: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 745: int popbased=0;
746:
747: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 748: int maxwav=0; /* Maxim number of waves */
749: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
750: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
751: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 752: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 753: int mle=1, weightopt=0;
1.126 brouard 754: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
755: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
756: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
757: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 758: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 759: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 760: double **matprod2(); /* test */
1.126 brouard 761: double **oldm, **newm, **savm; /* Working pointers to matrices */
762: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 763: /*FILE *fic ; */ /* Used in readdata only */
764: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 765: FILE *ficlog, *ficrespow;
1.130 brouard 766: int globpr=0; /* Global variable for printing or not */
1.126 brouard 767: double fretone; /* Only one call to likelihood */
1.130 brouard 768: long ipmx=0; /* Number of contributions */
1.126 brouard 769: double sw; /* Sum of weights */
770: char filerespow[FILENAMELENGTH];
771: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
772: FILE *ficresilk;
773: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
774: FILE *ficresprobmorprev;
775: FILE *fichtm, *fichtmcov; /* Html File */
776: FILE *ficreseij;
777: char filerese[FILENAMELENGTH];
778: FILE *ficresstdeij;
779: char fileresstde[FILENAMELENGTH];
780: FILE *ficrescveij;
781: char filerescve[FILENAMELENGTH];
782: FILE *ficresvij;
783: char fileresv[FILENAMELENGTH];
784: FILE *ficresvpl;
785: char fileresvpl[FILENAMELENGTH];
786: char title[MAXLINE];
787: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
788: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
789: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
790: char command[FILENAMELENGTH];
791: int outcmd=0;
792:
793: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
794:
795: char filelog[FILENAMELENGTH]; /* Log file */
796: char filerest[FILENAMELENGTH];
797: char fileregp[FILENAMELENGTH];
798: char popfile[FILENAMELENGTH];
799:
800: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
801:
1.157 brouard 802: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
803: /* struct timezone tzp; */
804: /* extern int gettimeofday(); */
805: struct tm tml, *gmtime(), *localtime();
806:
807: extern time_t time();
808:
809: struct tm start_time, end_time, curr_time, last_time, forecast_time;
810: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
811: struct tm tm;
812:
1.126 brouard 813: char strcurr[80], strfor[80];
814:
815: char *endptr;
816: long lval;
817: double dval;
818:
819: #define NR_END 1
820: #define FREE_ARG char*
821: #define FTOL 1.0e-10
822:
823: #define NRANSI
824: #define ITMAX 200
825:
826: #define TOL 2.0e-4
827:
828: #define CGOLD 0.3819660
829: #define ZEPS 1.0e-10
830: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
831:
832: #define GOLD 1.618034
833: #define GLIMIT 100.0
834: #define TINY 1.0e-20
835:
836: static double maxarg1,maxarg2;
837: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
838: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
839:
840: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
841: #define rint(a) floor(a+0.5)
1.166 brouard 842: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 843: #define mytinydouble 1.0e-16
1.166 brouard 844: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
845: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
846: /* static double dsqrarg; */
847: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 848: static double sqrarg;
849: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
850: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
851: int agegomp= AGEGOMP;
852:
853: int imx;
854: int stepm=1;
855: /* Stepm, step in month: minimum step interpolation*/
856:
857: int estepm;
858: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
859:
860: int m,nb;
861: long *num;
1.197 brouard 862: int firstpass=0, lastpass=4,*cod, *cens;
1.192 brouard 863: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
864: covariate for which somebody answered excluding
865: undefined. Usually 2: 0 and 1. */
866: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
867: covariate for which somebody answered including
868: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 869: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
870: double **pmmij, ***probs;
871: double *ageexmed,*agecens;
872: double dateintmean=0;
873:
874: double *weight;
875: int **s; /* Status */
1.141 brouard 876: double *agedc;
1.145 brouard 877: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 878: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 879: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 880: double idx;
881: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197 brouard 882: int *Tage;
1.145 brouard 883: int *Ndum; /** Freq of modality (tricode */
1.200 ! brouard 884: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141 brouard 885: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 886: double *lsurv, *lpop, *tpop;
887:
1.143 brouard 888: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
889: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 890:
891: /**************** split *************************/
892: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
893: {
894: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
895: the name of the file (name), its extension only (ext) and its first part of the name (finame)
896: */
897: char *ss; /* pointer */
1.186 brouard 898: int l1=0, l2=0; /* length counters */
1.126 brouard 899:
900: l1 = strlen(path ); /* length of path */
901: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
902: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
903: if ( ss == NULL ) { /* no directory, so determine current directory */
904: strcpy( name, path ); /* we got the fullname name because no directory */
905: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
906: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
907: /* get current working directory */
908: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 909: #ifdef WIN32
910: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
911: #else
912: if (getcwd(dirc, FILENAME_MAX) == NULL) {
913: #endif
1.126 brouard 914: return( GLOCK_ERROR_GETCWD );
915: }
916: /* got dirc from getcwd*/
917: printf(" DIRC = %s \n",dirc);
918: } else { /* strip direcotry from path */
919: ss++; /* after this, the filename */
920: l2 = strlen( ss ); /* length of filename */
921: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
922: strcpy( name, ss ); /* save file name */
923: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 924: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 925: printf(" DIRC2 = %s \n",dirc);
926: }
927: /* We add a separator at the end of dirc if not exists */
928: l1 = strlen( dirc ); /* length of directory */
929: if( dirc[l1-1] != DIRSEPARATOR ){
930: dirc[l1] = DIRSEPARATOR;
931: dirc[l1+1] = 0;
932: printf(" DIRC3 = %s \n",dirc);
933: }
934: ss = strrchr( name, '.' ); /* find last / */
935: if (ss >0){
936: ss++;
937: strcpy(ext,ss); /* save extension */
938: l1= strlen( name);
939: l2= strlen(ss)+1;
940: strncpy( finame, name, l1-l2);
941: finame[l1-l2]= 0;
942: }
943:
944: return( 0 ); /* we're done */
945: }
946:
947:
948: /******************************************/
949:
950: void replace_back_to_slash(char *s, char*t)
951: {
952: int i;
953: int lg=0;
954: i=0;
955: lg=strlen(t);
956: for(i=0; i<= lg; i++) {
957: (s[i] = t[i]);
958: if (t[i]== '\\') s[i]='/';
959: }
960: }
961:
1.132 brouard 962: char *trimbb(char *out, char *in)
1.137 brouard 963: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 964: char *s;
965: s=out;
966: while (*in != '\0'){
1.137 brouard 967: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 968: in++;
969: }
970: *out++ = *in++;
971: }
972: *out='\0';
973: return s;
974: }
975:
1.187 brouard 976: /* char *substrchaine(char *out, char *in, char *chain) */
977: /* { */
978: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
979: /* char *s, *t; */
980: /* t=in;s=out; */
981: /* while ((*in != *chain) && (*in != '\0')){ */
982: /* *out++ = *in++; */
983: /* } */
984:
985: /* /\* *in matches *chain *\/ */
986: /* while ((*in++ == *chain++) && (*in != '\0')){ */
987: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
988: /* } */
989: /* in--; chain--; */
990: /* while ( (*in != '\0')){ */
991: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
992: /* *out++ = *in++; */
993: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
994: /* } */
995: /* *out='\0'; */
996: /* out=s; */
997: /* return out; */
998: /* } */
999: char *substrchaine(char *out, char *in, char *chain)
1000: {
1001: /* Substract chain 'chain' from 'in', return and output 'out' */
1002: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1003:
1004: char *strloc;
1005:
1006: strcpy (out, in);
1007: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1008: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1009: if(strloc != NULL){
1010: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1011: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1012: /* strcpy (strloc, strloc +strlen(chain));*/
1013: }
1014: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1015: return out;
1016: }
1017:
1018:
1.145 brouard 1019: char *cutl(char *blocc, char *alocc, char *in, char occ)
1020: {
1.187 brouard 1021: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 1022: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 1023: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 1024: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1025: */
1.160 brouard 1026: char *s, *t;
1.145 brouard 1027: t=in;s=in;
1028: while ((*in != occ) && (*in != '\0')){
1029: *alocc++ = *in++;
1030: }
1031: if( *in == occ){
1032: *(alocc)='\0';
1033: s=++in;
1034: }
1035:
1036: if (s == t) {/* occ not found */
1037: *(alocc-(in-s))='\0';
1038: in=s;
1039: }
1040: while ( *in != '\0'){
1041: *blocc++ = *in++;
1042: }
1043:
1044: *blocc='\0';
1045: return t;
1046: }
1.137 brouard 1047: char *cutv(char *blocc, char *alocc, char *in, char occ)
1048: {
1.187 brouard 1049: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1050: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1051: gives blocc="abcdef2ghi" and alocc="j".
1052: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1053: */
1054: char *s, *t;
1055: t=in;s=in;
1056: while (*in != '\0'){
1057: while( *in == occ){
1058: *blocc++ = *in++;
1059: s=in;
1060: }
1061: *blocc++ = *in++;
1062: }
1063: if (s == t) /* occ not found */
1064: *(blocc-(in-s))='\0';
1065: else
1066: *(blocc-(in-s)-1)='\0';
1067: in=s;
1068: while ( *in != '\0'){
1069: *alocc++ = *in++;
1070: }
1071:
1072: *alocc='\0';
1073: return s;
1074: }
1075:
1.126 brouard 1076: int nbocc(char *s, char occ)
1077: {
1078: int i,j=0;
1079: int lg=20;
1080: i=0;
1081: lg=strlen(s);
1082: for(i=0; i<= lg; i++) {
1083: if (s[i] == occ ) j++;
1084: }
1085: return j;
1086: }
1087:
1.137 brouard 1088: /* void cutv(char *u,char *v, char*t, char occ) */
1089: /* { */
1090: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1091: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1092: /* gives u="abcdef2ghi" and v="j" *\/ */
1093: /* int i,lg,j,p=0; */
1094: /* i=0; */
1095: /* lg=strlen(t); */
1096: /* for(j=0; j<=lg-1; j++) { */
1097: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1098: /* } */
1.126 brouard 1099:
1.137 brouard 1100: /* for(j=0; j<p; j++) { */
1101: /* (u[j] = t[j]); */
1102: /* } */
1103: /* u[p]='\0'; */
1.126 brouard 1104:
1.137 brouard 1105: /* for(j=0; j<= lg; j++) { */
1106: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1107: /* } */
1108: /* } */
1.126 brouard 1109:
1.160 brouard 1110: #ifdef _WIN32
1111: char * strsep(char **pp, const char *delim)
1112: {
1113: char *p, *q;
1114:
1115: if ((p = *pp) == NULL)
1116: return 0;
1117: if ((q = strpbrk (p, delim)) != NULL)
1118: {
1119: *pp = q + 1;
1120: *q = '\0';
1121: }
1122: else
1123: *pp = 0;
1124: return p;
1125: }
1126: #endif
1127:
1.126 brouard 1128: /********************** nrerror ********************/
1129:
1130: void nrerror(char error_text[])
1131: {
1132: fprintf(stderr,"ERREUR ...\n");
1133: fprintf(stderr,"%s\n",error_text);
1134: exit(EXIT_FAILURE);
1135: }
1136: /*********************** vector *******************/
1137: double *vector(int nl, int nh)
1138: {
1139: double *v;
1140: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1141: if (!v) nrerror("allocation failure in vector");
1142: return v-nl+NR_END;
1143: }
1144:
1145: /************************ free vector ******************/
1146: void free_vector(double*v, int nl, int nh)
1147: {
1148: free((FREE_ARG)(v+nl-NR_END));
1149: }
1150:
1151: /************************ivector *******************************/
1152: int *ivector(long nl,long nh)
1153: {
1154: int *v;
1155: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1156: if (!v) nrerror("allocation failure in ivector");
1157: return v-nl+NR_END;
1158: }
1159:
1160: /******************free ivector **************************/
1161: void free_ivector(int *v, long nl, long nh)
1162: {
1163: free((FREE_ARG)(v+nl-NR_END));
1164: }
1165:
1166: /************************lvector *******************************/
1167: long *lvector(long nl,long nh)
1168: {
1169: long *v;
1170: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1171: if (!v) nrerror("allocation failure in ivector");
1172: return v-nl+NR_END;
1173: }
1174:
1175: /******************free lvector **************************/
1176: void free_lvector(long *v, long nl, long nh)
1177: {
1178: free((FREE_ARG)(v+nl-NR_END));
1179: }
1180:
1181: /******************* imatrix *******************************/
1182: int **imatrix(long nrl, long nrh, long ncl, long nch)
1183: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1184: {
1185: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1186: int **m;
1187:
1188: /* allocate pointers to rows */
1189: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1190: if (!m) nrerror("allocation failure 1 in matrix()");
1191: m += NR_END;
1192: m -= nrl;
1193:
1194:
1195: /* allocate rows and set pointers to them */
1196: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1197: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1198: m[nrl] += NR_END;
1199: m[nrl] -= ncl;
1200:
1201: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1202:
1203: /* return pointer to array of pointers to rows */
1204: return m;
1205: }
1206:
1207: /****************** free_imatrix *************************/
1208: void free_imatrix(m,nrl,nrh,ncl,nch)
1209: int **m;
1210: long nch,ncl,nrh,nrl;
1211: /* free an int matrix allocated by imatrix() */
1212: {
1213: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1214: free((FREE_ARG) (m+nrl-NR_END));
1215: }
1216:
1217: /******************* matrix *******************************/
1218: double **matrix(long nrl, long nrh, long ncl, long nch)
1219: {
1220: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1221: double **m;
1222:
1223: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1224: if (!m) nrerror("allocation failure 1 in matrix()");
1225: m += NR_END;
1226: m -= nrl;
1227:
1228: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1229: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1230: m[nrl] += NR_END;
1231: m[nrl] -= ncl;
1232:
1233: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1234: return m;
1.145 brouard 1235: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1236: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1237: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1238: */
1239: }
1240:
1241: /*************************free matrix ************************/
1242: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1243: {
1244: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1245: free((FREE_ARG)(m+nrl-NR_END));
1246: }
1247:
1248: /******************* ma3x *******************************/
1249: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1250: {
1251: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1252: double ***m;
1253:
1254: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1255: if (!m) nrerror("allocation failure 1 in matrix()");
1256: m += NR_END;
1257: m -= nrl;
1258:
1259: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1260: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1261: m[nrl] += NR_END;
1262: m[nrl] -= ncl;
1263:
1264: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1265:
1266: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1267: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1268: m[nrl][ncl] += NR_END;
1269: m[nrl][ncl] -= nll;
1270: for (j=ncl+1; j<=nch; j++)
1271: m[nrl][j]=m[nrl][j-1]+nlay;
1272:
1273: for (i=nrl+1; i<=nrh; i++) {
1274: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1275: for (j=ncl+1; j<=nch; j++)
1276: m[i][j]=m[i][j-1]+nlay;
1277: }
1278: return m;
1279: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1280: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1281: */
1282: }
1283:
1284: /*************************free ma3x ************************/
1285: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1286: {
1287: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1288: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1289: free((FREE_ARG)(m+nrl-NR_END));
1290: }
1291:
1292: /*************** function subdirf ***********/
1293: char *subdirf(char fileres[])
1294: {
1295: /* Caution optionfilefiname is hidden */
1296: strcpy(tmpout,optionfilefiname);
1297: strcat(tmpout,"/"); /* Add to the right */
1298: strcat(tmpout,fileres);
1299: return tmpout;
1300: }
1301:
1302: /*************** function subdirf2 ***********/
1303: char *subdirf2(char fileres[], char *preop)
1304: {
1305:
1306: /* Caution optionfilefiname is hidden */
1307: strcpy(tmpout,optionfilefiname);
1308: strcat(tmpout,"/");
1309: strcat(tmpout,preop);
1310: strcat(tmpout,fileres);
1311: return tmpout;
1312: }
1313:
1314: /*************** function subdirf3 ***********/
1315: char *subdirf3(char fileres[], char *preop, char *preop2)
1316: {
1317:
1318: /* Caution optionfilefiname is hidden */
1319: strcpy(tmpout,optionfilefiname);
1320: strcat(tmpout,"/");
1321: strcat(tmpout,preop);
1322: strcat(tmpout,preop2);
1323: strcat(tmpout,fileres);
1324: return tmpout;
1325: }
1326:
1.162 brouard 1327: char *asc_diff_time(long time_sec, char ascdiff[])
1328: {
1329: long sec_left, days, hours, minutes;
1330: days = (time_sec) / (60*60*24);
1331: sec_left = (time_sec) % (60*60*24);
1332: hours = (sec_left) / (60*60) ;
1333: sec_left = (sec_left) %(60*60);
1334: minutes = (sec_left) /60;
1335: sec_left = (sec_left) % (60);
1336: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1337: return ascdiff;
1338: }
1339:
1.126 brouard 1340: /***************** f1dim *************************/
1341: extern int ncom;
1342: extern double *pcom,*xicom;
1343: extern double (*nrfunc)(double []);
1344:
1345: double f1dim(double x)
1346: {
1347: int j;
1348: double f;
1349: double *xt;
1350:
1351: xt=vector(1,ncom);
1352: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1353: f=(*nrfunc)(xt);
1354: free_vector(xt,1,ncom);
1355: return f;
1356: }
1357:
1358: /*****************brent *************************/
1359: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1360: {
1361: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1362: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1363: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1364: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1365: * returned function value.
1366: */
1.126 brouard 1367: int iter;
1368: double a,b,d,etemp;
1.159 brouard 1369: double fu=0,fv,fw,fx;
1.164 brouard 1370: double ftemp=0.;
1.126 brouard 1371: double p,q,r,tol1,tol2,u,v,w,x,xm;
1372: double e=0.0;
1373:
1374: a=(ax < cx ? ax : cx);
1375: b=(ax > cx ? ax : cx);
1376: x=w=v=bx;
1377: fw=fv=fx=(*f)(x);
1378: for (iter=1;iter<=ITMAX;iter++) {
1379: xm=0.5*(a+b);
1380: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1381: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1382: printf(".");fflush(stdout);
1383: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1384: #ifdef DEBUGBRENT
1.126 brouard 1385: 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);
1386: 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);
1387: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1388: #endif
1389: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1390: *xmin=x;
1391: return fx;
1392: }
1393: ftemp=fu;
1394: if (fabs(e) > tol1) {
1395: r=(x-w)*(fx-fv);
1396: q=(x-v)*(fx-fw);
1397: p=(x-v)*q-(x-w)*r;
1398: q=2.0*(q-r);
1399: if (q > 0.0) p = -p;
1400: q=fabs(q);
1401: etemp=e;
1402: e=d;
1403: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1404: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1405: else {
1406: d=p/q;
1407: u=x+d;
1408: if (u-a < tol2 || b-u < tol2)
1409: d=SIGN(tol1,xm-x);
1410: }
1411: } else {
1412: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1413: }
1414: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1415: fu=(*f)(u);
1416: if (fu <= fx) {
1417: if (u >= x) a=x; else b=x;
1418: SHFT(v,w,x,u)
1.183 brouard 1419: SHFT(fv,fw,fx,fu)
1420: } else {
1421: if (u < x) a=u; else b=u;
1422: if (fu <= fw || w == x) {
1423: v=w;
1424: w=u;
1425: fv=fw;
1426: fw=fu;
1427: } else if (fu <= fv || v == x || v == w) {
1428: v=u;
1429: fv=fu;
1430: }
1431: }
1.126 brouard 1432: }
1433: nrerror("Too many iterations in brent");
1434: *xmin=x;
1435: return fx;
1436: }
1437:
1438: /****************** mnbrak ***********************/
1439:
1440: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1441: double (*func)(double))
1.183 brouard 1442: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1443: the downhill direction (defined by the function as evaluated at the initial points) and returns
1444: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1445: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1446: */
1.126 brouard 1447: double ulim,u,r,q, dum;
1448: double fu;
1.187 brouard 1449:
1450: double scale=10.;
1451: int iterscale=0;
1452:
1453: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1454: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1455:
1456:
1457: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1458: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1459: /* *bx = *ax - (*ax - *bx)/scale; */
1460: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1461: /* } */
1462:
1.126 brouard 1463: if (*fb > *fa) {
1464: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1465: SHFT(dum,*fb,*fa,dum)
1466: }
1.126 brouard 1467: *cx=(*bx)+GOLD*(*bx-*ax);
1468: *fc=(*func)(*cx);
1.183 brouard 1469: #ifdef DEBUG
1470: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1471: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1472: #endif
1473: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1474: r=(*bx-*ax)*(*fb-*fc);
1475: q=(*bx-*cx)*(*fb-*fa);
1476: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1477: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1478: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1479: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1480: fu=(*func)(u);
1.163 brouard 1481: #ifdef DEBUG
1482: /* f(x)=A(x-u)**2+f(u) */
1483: double A, fparabu;
1484: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1485: fparabu= *fa - A*(*ax-u)*(*ax-u);
1486: 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);
1487: 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);
1.183 brouard 1488: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1489: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1490: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1491: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1492: #endif
1.184 brouard 1493: #ifdef MNBRAKORIGINAL
1.183 brouard 1494: #else
1.191 brouard 1495: /* if (fu > *fc) { */
1496: /* #ifdef DEBUG */
1497: /* printf("mnbrak4 fu > fc \n"); */
1498: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1499: /* #endif */
1500: /* /\* SHFT(u,*cx,*cx,u) /\\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\\/ *\/ */
1501: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1502: /* dum=u; /\* Shifting c and u *\/ */
1503: /* u = *cx; */
1504: /* *cx = dum; */
1505: /* dum = fu; */
1506: /* fu = *fc; */
1507: /* *fc =dum; */
1508: /* } else { /\* end *\/ */
1509: /* #ifdef DEBUG */
1510: /* printf("mnbrak3 fu < fc \n"); */
1511: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1512: /* #endif */
1513: /* dum=u; /\* Shifting c and u *\/ */
1514: /* u = *cx; */
1515: /* *cx = dum; */
1516: /* dum = fu; */
1517: /* fu = *fc; */
1518: /* *fc =dum; */
1519: /* } */
1.183 brouard 1520: #ifdef DEBUG
1.191 brouard 1521: printf("mnbrak34 fu < or >= fc \n");
1522: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1523: #endif
1.191 brouard 1524: dum=u; /* Shifting c and u */
1525: u = *cx;
1526: *cx = dum;
1527: dum = fu;
1528: fu = *fc;
1529: *fc =dum;
1.183 brouard 1530: #endif
1.162 brouard 1531: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1532: #ifdef DEBUG
1533: printf("mnbrak2 u after c but before ulim\n");
1534: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1535: #endif
1.126 brouard 1536: fu=(*func)(u);
1537: if (fu < *fc) {
1.183 brouard 1538: #ifdef DEBUG
1539: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1540: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1541: #endif
1.126 brouard 1542: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1543: SHFT(*fb,*fc,fu,(*func)(u))
1544: }
1.162 brouard 1545: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1546: #ifdef DEBUG
1547: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1548: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1549: #endif
1.126 brouard 1550: u=ulim;
1551: fu=(*func)(u);
1.183 brouard 1552: } else { /* u could be left to b (if r > q parabola has a maximum) */
1553: #ifdef DEBUG
1554: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1555: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1556: #endif
1.126 brouard 1557: u=(*cx)+GOLD*(*cx-*bx);
1558: fu=(*func)(u);
1.183 brouard 1559: } /* end tests */
1.126 brouard 1560: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1561: SHFT(*fa,*fb,*fc,fu)
1562: #ifdef DEBUG
1563: printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
1564: fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
1565: #endif
1566: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126 brouard 1567: }
1568:
1569: /*************** linmin ************************/
1.162 brouard 1570: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1571: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1572: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1573: the value of func at the returned location p . This is actually all accomplished by calling the
1574: routines mnbrak and brent .*/
1.126 brouard 1575: int ncom;
1576: double *pcom,*xicom;
1577: double (*nrfunc)(double []);
1578:
1579: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1580: {
1581: double brent(double ax, double bx, double cx,
1582: double (*f)(double), double tol, double *xmin);
1583: double f1dim(double x);
1584: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1585: double *fc, double (*func)(double));
1586: int j;
1587: double xx,xmin,bx,ax;
1588: double fx,fb,fa;
1.187 brouard 1589:
1590: double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126 brouard 1591:
1592: ncom=n;
1593: pcom=vector(1,n);
1594: xicom=vector(1,n);
1595: nrfunc=func;
1596: for (j=1;j<=n;j++) {
1597: pcom[j]=p[j];
1598: xicom[j]=xi[j];
1599: }
1.187 brouard 1600:
1.192 brouard 1601: /* axs=0.0; */
1602: /* xxss=1; /\* 1 and using scale *\/ */
1.187 brouard 1603: xxs=1;
1.192 brouard 1604: /* do{ */
1.187 brouard 1605: ax=0.;
1606: xx= xxs;
1607: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1608: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1609: /* xt[x,j]=pcom[j]+x*xicom[j] f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j)) */
1610: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1611: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1612: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1613: /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus [0:xi[j]]*/
1.192 brouard 1614: /* if (fx != fx){ */
1615: /* xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
1616: /* printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n", axs, xxs, fx,fb, fa, xx, ax, bx); */
1617: /* } */
1618: /* }while(fx != fx); */
1.187 brouard 1619:
1.191 brouard 1620: #ifdef DEBUGLINMIN
1621: printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n", ax,xx,bx,fa,fx,fb);
1622: #endif
1.187 brouard 1623: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1624: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1625: /* fmin = f(p[j] + xmin * xi[j]) */
1626: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1627: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1628: #ifdef DEBUG
1629: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1630: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1631: #endif
1.191 brouard 1632: #ifdef DEBUGLINMIN
1633: printf("linmin end ");
1634: #endif
1.126 brouard 1635: for (j=1;j<=n;j++) {
1.188 brouard 1636: /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187 brouard 1637: xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189 brouard 1638: /* if(xxs <1.0) */
1639: /* printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs ); */
1.187 brouard 1640: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1641: }
1.189 brouard 1642: /* printf("\n"); */
1.191 brouard 1643: #ifdef DEBUGLINMIN
1644: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1645: for (j=1;j<=n;j++) {
1646: printf(" xi[%d]= %12.7f p[%d]= %12.7f",j,xi[j],j,p[j]);
1647: if(j % ncovmodel == 0)
1648: printf("\n");
1649: }
1650: #endif
1.126 brouard 1651: free_vector(xicom,1,n);
1652: free_vector(pcom,1,n);
1653: }
1654:
1655:
1656: /*************** powell ************************/
1.162 brouard 1657: /*
1658: Minimization of a function func of n variables. Input consists of an initial starting point
1659: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1660: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1661: such that failure to decrease by more than this amount on one iteration signals doneness. On
1662: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1663: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1664: */
1.126 brouard 1665: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1666: double (*func)(double []))
1667: {
1668: void linmin(double p[], double xi[], int n, double *fret,
1669: double (*func)(double []));
1670: int i,ibig,j;
1671: double del,t,*pt,*ptt,*xit;
1.181 brouard 1672: double directest;
1.126 brouard 1673: double fp,fptt;
1674: double *xits;
1675: int niterf, itmp;
1676:
1677: pt=vector(1,n);
1678: ptt=vector(1,n);
1679: xit=vector(1,n);
1680: xits=vector(1,n);
1681: *fret=(*func)(p);
1682: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1683: rcurr_time = time(NULL);
1.126 brouard 1684: for (*iter=1;;++(*iter)) {
1.187 brouard 1685: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1686: ibig=0;
1687: del=0.0;
1.157 brouard 1688: rlast_time=rcurr_time;
1689: /* (void) gettimeofday(&curr_time,&tzp); */
1690: rcurr_time = time(NULL);
1691: curr_time = *localtime(&rcurr_time);
1692: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1693: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1694: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1695: for (i=1;i<=n;i++) {
1.126 brouard 1696: printf(" %d %.12f",i, p[i]);
1697: fprintf(ficlog," %d %.12lf",i, p[i]);
1698: fprintf(ficrespow," %.12lf", p[i]);
1699: }
1700: printf("\n");
1701: fprintf(ficlog,"\n");
1702: fprintf(ficrespow,"\n");fflush(ficrespow);
1703: if(*iter <=3){
1.157 brouard 1704: tml = *localtime(&rcurr_time);
1705: strcpy(strcurr,asctime(&tml));
1706: rforecast_time=rcurr_time;
1.126 brouard 1707: itmp = strlen(strcurr);
1708: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1709: strcurr[itmp-1]='\0';
1.162 brouard 1710: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1711: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1712: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1713: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1714: forecast_time = *localtime(&rforecast_time);
1715: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1716: itmp = strlen(strfor);
1717: if(strfor[itmp-1]=='\n')
1718: strfor[itmp-1]='\0';
1.157 brouard 1719: 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);
1720: 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 1721: }
1722: }
1.187 brouard 1723: for (i=1;i<=n;i++) { /* For each direction i */
1724: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1725: fptt=(*fret);
1726: #ifdef DEBUG
1.164 brouard 1727: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1728: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1729: #endif
1.187 brouard 1730: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1731: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1732: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1733: /* Outputs are fret(new point p) p is updated and xit rescaled */
1734: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1735: /* because that direction will be replaced unless the gain del is small */
1736: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1737: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1738: /* with the new direction. */
1.126 brouard 1739: del=fabs(fptt-(*fret));
1740: ibig=i;
1741: }
1742: #ifdef DEBUG
1743: printf("%d %.12e",i,(*fret));
1744: fprintf(ficlog,"%d %.12e",i,(*fret));
1745: for (j=1;j<=n;j++) {
1746: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1747: printf(" x(%d)=%.12e",j,xit[j]);
1748: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1749: }
1750: for(j=1;j<=n;j++) {
1.162 brouard 1751: printf(" p(%d)=%.12e",j,p[j]);
1752: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1753: }
1754: printf("\n");
1755: fprintf(ficlog,"\n");
1756: #endif
1.187 brouard 1757: } /* end loop on each direction i */
1758: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1759: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1760: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1761: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1762: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1763: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1764: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1765: /* decreased of more than 3.84 */
1766: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1767: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1768: /* By adding 10 parameters more the gain should be 18.31 */
1769:
1770: /* Starting the program with initial values given by a former maximization will simply change */
1771: /* the scales of the directions and the directions, because the are reset to canonical directions */
1772: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1773: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1774: #ifdef DEBUG
1775: int k[2],l;
1776: k[0]=1;
1777: k[1]=-1;
1778: printf("Max: %.12e",(*func)(p));
1779: fprintf(ficlog,"Max: %.12e",(*func)(p));
1780: for (j=1;j<=n;j++) {
1781: printf(" %.12e",p[j]);
1782: fprintf(ficlog," %.12e",p[j]);
1783: }
1784: printf("\n");
1785: fprintf(ficlog,"\n");
1786: for(l=0;l<=1;l++) {
1787: for (j=1;j<=n;j++) {
1788: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1789: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1790: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1791: }
1792: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1793: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1794: }
1795: #endif
1796:
1797:
1798: free_vector(xit,1,n);
1799: free_vector(xits,1,n);
1800: free_vector(ptt,1,n);
1801: free_vector(pt,1,n);
1802: return;
1.192 brouard 1803: } /* enough precision */
1.126 brouard 1804: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1805: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1806: ptt[j]=2.0*p[j]-pt[j];
1807: xit[j]=p[j]-pt[j];
1808: pt[j]=p[j];
1809: }
1.181 brouard 1810: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1811: #ifdef POWELLF1F3
1812: #else
1.161 brouard 1813: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1814: #endif
1.162 brouard 1815: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1816: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1817: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1818: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1819: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1820: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1821: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1822: #ifdef NRCORIGINAL
1823: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1824: #else
1825: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161 brouard 1826: t= t- del*SQR(fp-fptt);
1.183 brouard 1827: #endif
1.182 brouard 1828: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1.161 brouard 1829: #ifdef DEBUG
1.181 brouard 1830: 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);
1831: 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 1832: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1833: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1834: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1835: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1836: 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);
1837: 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);
1838: #endif
1.183 brouard 1839: #ifdef POWELLORIGINAL
1840: if (t < 0.0) { /* Then we use it for new direction */
1841: #else
1.182 brouard 1842: if (directest*t < 0.0) { /* Contradiction between both tests */
1.192 brouard 1843: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1844: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1845: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1846: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1847: }
1.181 brouard 1848: if (directest < 0.0) { /* Then we use it for new direction */
1849: #endif
1.191 brouard 1850: #ifdef DEBUGLINMIN
1851: printf("Before linmin in direction P%d-P0\n",n);
1852: for (j=1;j<=n;j++) {
1853: printf("Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1854: if(j % ncovmodel == 0)
1855: printf("\n");
1856: }
1857: #endif
1.187 brouard 1858: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1859: #ifdef DEBUGLINMIN
1860: for (j=1;j<=n;j++) {
1861: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1862: if(j % ncovmodel == 0)
1863: printf("\n");
1864: }
1865: #endif
1.126 brouard 1866: for (j=1;j<=n;j++) {
1.181 brouard 1867: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1868: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1869: }
1.181 brouard 1870: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1871: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1872:
1.126 brouard 1873: #ifdef DEBUG
1.164 brouard 1874: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1875: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1876: for(j=1;j<=n;j++){
1877: printf(" %.12e",xit[j]);
1878: fprintf(ficlog," %.12e",xit[j]);
1879: }
1880: printf("\n");
1881: fprintf(ficlog,"\n");
1882: #endif
1.192 brouard 1883: } /* end of t or directest negative */
1884: #ifdef POWELLF1F3
1885: #else
1.162 brouard 1886: } /* end if (fptt < fp) */
1.192 brouard 1887: #endif
1888: } /* loop iteration */
1.126 brouard 1889: }
1890:
1891: /**** Prevalence limit (stable or period prevalence) ****************/
1892:
1893: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1894: {
1895: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1896: matrix by transitions matrix until convergence is reached */
1.169 brouard 1897:
1.126 brouard 1898: int i, ii,j,k;
1899: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1900: /* double **matprod2(); */ /* test */
1.131 brouard 1901: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1902: double **newm;
1903: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1904:
1.126 brouard 1905: for (ii=1;ii<=nlstate+ndeath;ii++)
1906: for (j=1;j<=nlstate+ndeath;j++){
1907: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1908: }
1.169 brouard 1909:
1910: cov[1]=1.;
1911:
1912: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1913: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1914: newm=savm;
1915: /* Covariates have to be included here again */
1.138 brouard 1916: cov[2]=agefin;
1.187 brouard 1917: if(nagesqr==1)
1918: cov[3]= agefin*agefin;;
1.138 brouard 1919: for (k=1; k<=cptcovn;k++) {
1.200 ! brouard 1920: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
! 1921: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198 brouard 1922: /* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); */
1.138 brouard 1923: }
1.186 brouard 1924: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 ! brouard 1925: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
! 1926: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186 brouard 1927: for (k=1; k<=cptcovprod;k++) /* Useless */
1.200 ! brouard 1928: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
! 1929: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138 brouard 1930:
1931: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1932: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1933: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1934: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1935: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1936: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1937:
1.126 brouard 1938: savm=oldm;
1939: oldm=newm;
1940: maxmax=0.;
1941: for(j=1;j<=nlstate;j++){
1942: min=1.;
1943: max=0.;
1944: for(i=1; i<=nlstate; i++) {
1945: sumnew=0;
1946: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1947: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1948: /*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 1949: max=FMAX(max,prlim[i][j]);
1950: min=FMIN(min,prlim[i][j]);
1951: }
1952: maxmin=max-min;
1953: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1954: } /* j loop */
1.126 brouard 1955: if(maxmax < ftolpl){
1956: return prlim;
1957: }
1.169 brouard 1958: } /* age loop */
1959: return prlim; /* should not reach here */
1.126 brouard 1960: }
1961:
1962: /*************** transition probabilities ***************/
1963:
1964: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1965: {
1.138 brouard 1966: /* According to parameters values stored in x and the covariate's values stored in cov,
1967: computes the probability to be observed in state j being in state i by appying the
1968: model to the ncovmodel covariates (including constant and age).
1969: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1970: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1971: ncth covariate in the global vector x is given by the formula:
1972: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1973: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1974: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1975: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1976: Outputs ps[i][j] the probability to be observed in j being in j according to
1977: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1978: */
1979: double s1, lnpijopii;
1.126 brouard 1980: /*double t34;*/
1.164 brouard 1981: int i,j, nc, ii, jj;
1.126 brouard 1982:
1983: for(i=1; i<= nlstate; i++){
1984: for(j=1; j<i;j++){
1.138 brouard 1985: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1986: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1987: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1988: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1989: }
1.138 brouard 1990: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1991: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1992: }
1993: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1994: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1995: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1996: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1997: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1998: }
1.138 brouard 1999: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 2000: }
2001: }
2002:
2003: for(i=1; i<= nlstate; i++){
2004: s1=0;
1.131 brouard 2005: for(j=1; j<i; j++){
1.138 brouard 2006: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2007: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2008: }
2009: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 2010: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2011: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2012: }
1.138 brouard 2013: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 2014: ps[i][i]=1./(s1+1.);
1.138 brouard 2015: /* Computing other pijs */
1.126 brouard 2016: for(j=1; j<i; j++)
2017: ps[i][j]= exp(ps[i][j])*ps[i][i];
2018: for(j=i+1; j<=nlstate+ndeath; j++)
2019: ps[i][j]= exp(ps[i][j])*ps[i][i];
2020: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2021: } /* end i */
2022:
2023: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2024: for(jj=1; jj<= nlstate+ndeath; jj++){
2025: ps[ii][jj]=0;
2026: ps[ii][ii]=1;
2027: }
2028: }
2029:
1.145 brouard 2030:
2031: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2032: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2033: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2034: /* } */
2035: /* printf("\n "); */
2036: /* } */
2037: /* printf("\n ");printf("%lf ",cov[2]);*/
2038: /*
1.126 brouard 2039: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2040: goto end;*/
2041: return ps;
2042: }
2043:
2044: /**************** Product of 2 matrices ******************/
2045:
1.145 brouard 2046: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2047: {
2048: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2049: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2050: /* in, b, out are matrice of pointers which should have been initialized
2051: before: only the contents of out is modified. The function returns
2052: a pointer to pointers identical to out */
1.145 brouard 2053: int i, j, k;
1.126 brouard 2054: for(i=nrl; i<= nrh; i++)
1.145 brouard 2055: for(k=ncolol; k<=ncoloh; k++){
2056: out[i][k]=0.;
2057: for(j=ncl; j<=nch; j++)
2058: out[i][k] +=in[i][j]*b[j][k];
2059: }
1.126 brouard 2060: return out;
2061: }
2062:
2063:
2064: /************* Higher Matrix Product ***************/
2065:
2066: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2067: {
2068: /* Computes the transition matrix starting at age 'age' over
2069: 'nhstepm*hstepm*stepm' months (i.e. until
2070: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2071: nhstepm*hstepm matrices.
2072: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2073: (typically every 2 years instead of every month which is too big
2074: for the memory).
2075: Model is determined by parameters x and covariates have to be
2076: included manually here.
2077:
2078: */
2079:
2080: int i, j, d, h, k;
1.131 brouard 2081: double **out, cov[NCOVMAX+1];
1.126 brouard 2082: double **newm;
1.187 brouard 2083: double agexact;
1.126 brouard 2084:
2085: /* Hstepm could be zero and should return the unit matrix */
2086: for (i=1;i<=nlstate+ndeath;i++)
2087: for (j=1;j<=nlstate+ndeath;j++){
2088: oldm[i][j]=(i==j ? 1.0 : 0.0);
2089: po[i][j][0]=(i==j ? 1.0 : 0.0);
2090: }
2091: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2092: for(h=1; h <=nhstepm; h++){
2093: for(d=1; d <=hstepm; d++){
2094: newm=savm;
2095: /* Covariates have to be included here again */
2096: cov[1]=1.;
1.187 brouard 2097: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2098: cov[2]=agexact;
2099: if(nagesqr==1)
2100: cov[3]= agexact*agexact;
1.131 brouard 2101: for (k=1; k<=cptcovn;k++)
1.200 ! brouard 2102: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
! 2103: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186 brouard 2104: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2105: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 ! brouard 2106: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
! 2107: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145 brouard 2108: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200 ! brouard 2109: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
! 2110: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126 brouard 2111:
2112:
2113: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2114: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2115: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2116: pmij(pmmij,cov,ncovmodel,x,nlstate));
2117: savm=oldm;
2118: oldm=newm;
2119: }
2120: for(i=1; i<=nlstate+ndeath; i++)
2121: for(j=1;j<=nlstate+ndeath;j++) {
2122: po[i][j][h]=newm[i][j];
1.128 brouard 2123: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2124: }
1.128 brouard 2125: /*printf("h=%d ",h);*/
1.126 brouard 2126: } /* end h */
1.128 brouard 2127: /* printf("\n H=%d \n",h); */
1.126 brouard 2128: return po;
2129: }
2130:
1.162 brouard 2131: #ifdef NLOPT
2132: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2133: double fret;
2134: double *xt;
2135: int j;
2136: myfunc_data *d2 = (myfunc_data *) pd;
2137: /* xt = (p1-1); */
2138: xt=vector(1,n);
2139: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2140:
2141: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2142: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2143: printf("Function = %.12lf ",fret);
2144: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2145: printf("\n");
2146: free_vector(xt,1,n);
2147: return fret;
2148: }
2149: #endif
1.126 brouard 2150:
2151: /*************** log-likelihood *************/
2152: double func( double *x)
2153: {
2154: int i, ii, j, k, mi, d, kk;
1.131 brouard 2155: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2156: double **out;
2157: double sw; /* Sum of weights */
2158: double lli; /* Individual log likelihood */
2159: int s1, s2;
2160: double bbh, survp;
2161: long ipmx;
1.187 brouard 2162: double agexact;
1.126 brouard 2163: /*extern weight */
2164: /* We are differentiating ll according to initial status */
2165: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2166: /*for(i=1;i<imx;i++)
2167: printf(" %d\n",s[4][i]);
2168: */
1.162 brouard 2169:
2170: ++countcallfunc;
2171:
1.126 brouard 2172: cov[1]=1.;
2173:
2174: for(k=1; k<=nlstate; k++) ll[k]=0.;
2175:
2176: if(mle==1){
2177: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2178: /* Computes the values of the ncovmodel covariates of the model
2179: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2180: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2181: to be observed in j being in i according to the model.
2182: */
1.145 brouard 2183: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2184: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2185: }
1.137 brouard 2186: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2187: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2188: has been calculated etc */
1.126 brouard 2189: for(mi=1; mi<= wav[i]-1; mi++){
2190: for (ii=1;ii<=nlstate+ndeath;ii++)
2191: for (j=1;j<=nlstate+ndeath;j++){
2192: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2193: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2194: }
2195: for(d=0; d<dh[mi][i]; d++){
2196: newm=savm;
1.187 brouard 2197: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2198: cov[2]=agexact;
2199: if(nagesqr==1)
2200: cov[3]= agexact*agexact;
1.126 brouard 2201: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2202: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2203: }
2204: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2205: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2206: savm=oldm;
2207: oldm=newm;
2208: } /* end mult */
2209:
2210: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2211: /* But now since version 0.9 we anticipate for bias at large stepm.
2212: * If stepm is larger than one month (smallest stepm) and if the exact delay
2213: * (in months) between two waves is not a multiple of stepm, we rounded to
2214: * the nearest (and in case of equal distance, to the lowest) interval but now
2215: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2216: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2217: * probability in order to take into account the bias as a fraction of the way
2218: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2219: * -stepm/2 to stepm/2 .
2220: * For stepm=1 the results are the same as for previous versions of Imach.
2221: * For stepm > 1 the results are less biased than in previous versions.
2222: */
2223: s1=s[mw[mi][i]][i];
2224: s2=s[mw[mi+1][i]][i];
2225: bbh=(double)bh[mi][i]/(double)stepm;
2226: /* bias bh is positive if real duration
2227: * is higher than the multiple of stepm and negative otherwise.
2228: */
2229: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2230: if( s2 > nlstate){
2231: /* i.e. if s2 is a death state and if the date of death is known
2232: then the contribution to the likelihood is the probability to
2233: die between last step unit time and current step unit time,
2234: which is also equal to probability to die before dh
2235: minus probability to die before dh-stepm .
2236: In version up to 0.92 likelihood was computed
2237: as if date of death was unknown. Death was treated as any other
2238: health state: the date of the interview describes the actual state
2239: and not the date of a change in health state. The former idea was
2240: to consider that at each interview the state was recorded
2241: (healthy, disable or death) and IMaCh was corrected; but when we
2242: introduced the exact date of death then we should have modified
2243: the contribution of an exact death to the likelihood. This new
2244: contribution is smaller and very dependent of the step unit
2245: stepm. It is no more the probability to die between last interview
2246: and month of death but the probability to survive from last
2247: interview up to one month before death multiplied by the
2248: probability to die within a month. Thanks to Chris
2249: Jackson for correcting this bug. Former versions increased
2250: mortality artificially. The bad side is that we add another loop
2251: which slows down the processing. The difference can be up to 10%
2252: lower mortality.
2253: */
1.183 brouard 2254: /* If, at the beginning of the maximization mostly, the
2255: cumulative probability or probability to be dead is
2256: constant (ie = 1) over time d, the difference is equal to
2257: 0. out[s1][3] = savm[s1][3]: probability, being at state
2258: s1 at precedent wave, to be dead a month before current
2259: wave is equal to probability, being at state s1 at
2260: precedent wave, to be dead at mont of the current
2261: wave. Then the observed probability (that this person died)
2262: is null according to current estimated parameter. In fact,
2263: it should be very low but not zero otherwise the log go to
2264: infinity.
2265: */
2266: /* #ifdef INFINITYORIGINAL */
2267: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2268: /* #else */
2269: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2270: /* lli=log(mytinydouble); */
2271: /* else */
2272: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2273: /* #endif */
2274: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2275:
2276: } else if (s2==-2) {
2277: for (j=1,survp=0. ; j<=nlstate; j++)
2278: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2279: /*survp += out[s1][j]; */
2280: lli= log(survp);
2281: }
2282:
2283: else if (s2==-4) {
2284: for (j=3,survp=0. ; j<=nlstate; j++)
2285: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2286: lli= log(survp);
2287: }
2288:
2289: else if (s2==-5) {
2290: for (j=1,survp=0. ; j<=2; j++)
2291: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2292: lli= log(survp);
2293: }
2294:
2295: else{
2296: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2297: /* 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 */
2298: }
2299: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2300: /*if(lli ==000.0)*/
2301: /*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); */
2302: ipmx +=1;
2303: sw += weight[i];
2304: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2305: /* if (lli < log(mytinydouble)){ */
2306: /* printf("Close to inf lli = %.10lf < %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
2307: /* fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
2308: /* } */
1.126 brouard 2309: } /* end of wave */
2310: } /* end of individual */
2311: } else if(mle==2){
2312: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2313: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2314: for(mi=1; mi<= wav[i]-1; mi++){
2315: for (ii=1;ii<=nlstate+ndeath;ii++)
2316: for (j=1;j<=nlstate+ndeath;j++){
2317: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2318: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2319: }
2320: for(d=0; d<=dh[mi][i]; d++){
2321: newm=savm;
1.187 brouard 2322: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2323: cov[2]=agexact;
2324: if(nagesqr==1)
2325: cov[3]= agexact*agexact;
1.126 brouard 2326: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2327: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2328: }
2329: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2330: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2331: savm=oldm;
2332: oldm=newm;
2333: } /* end mult */
2334:
2335: s1=s[mw[mi][i]][i];
2336: s2=s[mw[mi+1][i]][i];
2337: bbh=(double)bh[mi][i]/(double)stepm;
2338: 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 */
2339: ipmx +=1;
2340: sw += weight[i];
2341: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2342: } /* end of wave */
2343: } /* end of individual */
2344: } else if(mle==3){ /* exponential inter-extrapolation */
2345: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2346: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2347: for(mi=1; mi<= wav[i]-1; mi++){
2348: for (ii=1;ii<=nlstate+ndeath;ii++)
2349: for (j=1;j<=nlstate+ndeath;j++){
2350: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2351: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2352: }
2353: for(d=0; d<dh[mi][i]; d++){
2354: newm=savm;
1.187 brouard 2355: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2356: cov[2]=agexact;
2357: if(nagesqr==1)
2358: cov[3]= agexact*agexact;
1.126 brouard 2359: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2360: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2361: }
2362: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2363: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2364: savm=oldm;
2365: oldm=newm;
2366: } /* end mult */
2367:
2368: s1=s[mw[mi][i]][i];
2369: s2=s[mw[mi+1][i]][i];
2370: bbh=(double)bh[mi][i]/(double)stepm;
2371: 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 */
2372: ipmx +=1;
2373: sw += weight[i];
2374: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2375: } /* end of wave */
2376: } /* end of individual */
2377: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2378: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2379: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2380: for(mi=1; mi<= wav[i]-1; mi++){
2381: for (ii=1;ii<=nlstate+ndeath;ii++)
2382: for (j=1;j<=nlstate+ndeath;j++){
2383: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2384: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2385: }
2386: for(d=0; d<dh[mi][i]; d++){
2387: newm=savm;
1.187 brouard 2388: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2389: cov[2]=agexact;
2390: if(nagesqr==1)
2391: cov[3]= agexact*agexact;
1.126 brouard 2392: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2393: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2394: }
2395:
2396: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2397: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2398: savm=oldm;
2399: oldm=newm;
2400: } /* end mult */
2401:
2402: s1=s[mw[mi][i]][i];
2403: s2=s[mw[mi+1][i]][i];
2404: if( s2 > nlstate){
2405: lli=log(out[s1][s2] - savm[s1][s2]);
2406: }else{
2407: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2408: }
2409: ipmx +=1;
2410: sw += weight[i];
2411: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2412: /* 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]); */
2413: } /* end of wave */
2414: } /* end of individual */
2415: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2416: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2417: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2418: for(mi=1; mi<= wav[i]-1; mi++){
2419: for (ii=1;ii<=nlstate+ndeath;ii++)
2420: for (j=1;j<=nlstate+ndeath;j++){
2421: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2422: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2423: }
2424: for(d=0; d<dh[mi][i]; d++){
2425: newm=savm;
1.187 brouard 2426: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2427: cov[2]=agexact;
2428: if(nagesqr==1)
2429: cov[3]= agexact*agexact;
1.126 brouard 2430: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2431: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2432: }
2433:
2434: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2435: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2436: savm=oldm;
2437: oldm=newm;
2438: } /* end mult */
2439:
2440: s1=s[mw[mi][i]][i];
2441: s2=s[mw[mi+1][i]][i];
2442: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2443: ipmx +=1;
2444: sw += weight[i];
2445: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2446: /*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]);*/
2447: } /* end of wave */
2448: } /* end of individual */
2449: } /* End of if */
2450: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2451: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2452: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2453: return -l;
2454: }
2455:
2456: /*************** log-likelihood *************/
2457: double funcone( double *x)
2458: {
2459: /* Same as likeli but slower because of a lot of printf and if */
2460: int i, ii, j, k, mi, d, kk;
1.131 brouard 2461: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2462: double **out;
2463: double lli; /* Individual log likelihood */
2464: double llt;
2465: int s1, s2;
2466: double bbh, survp;
1.187 brouard 2467: double agexact;
1.126 brouard 2468: /*extern weight */
2469: /* We are differentiating ll according to initial status */
2470: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2471: /*for(i=1;i<imx;i++)
2472: printf(" %d\n",s[4][i]);
2473: */
2474: cov[1]=1.;
2475:
2476: for(k=1; k<=nlstate; k++) ll[k]=0.;
2477:
2478: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2479: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2480: for(mi=1; mi<= wav[i]-1; mi++){
2481: for (ii=1;ii<=nlstate+ndeath;ii++)
2482: for (j=1;j<=nlstate+ndeath;j++){
2483: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2484: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2485: }
2486: for(d=0; d<dh[mi][i]; d++){
2487: newm=savm;
1.187 brouard 2488: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2489: cov[2]=agexact;
2490: if(nagesqr==1)
2491: cov[3]= agexact*agexact;
1.126 brouard 2492: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2493: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2494: }
1.187 brouard 2495:
1.145 brouard 2496: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2497: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2498: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2499: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2500: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2501: savm=oldm;
2502: oldm=newm;
2503: } /* end mult */
2504:
2505: s1=s[mw[mi][i]][i];
2506: s2=s[mw[mi+1][i]][i];
2507: bbh=(double)bh[mi][i]/(double)stepm;
2508: /* bias is positive if real duration
2509: * is higher than the multiple of stepm and negative otherwise.
2510: */
2511: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2512: lli=log(out[s1][s2] - savm[s1][s2]);
2513: } else if (s2==-2) {
2514: for (j=1,survp=0. ; j<=nlstate; j++)
2515: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2516: lli= log(survp);
2517: }else if (mle==1){
2518: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2519: } else if(mle==2){
2520: 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 */
2521: } else if(mle==3){ /* exponential inter-extrapolation */
2522: 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 */
2523: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2524: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2525: } else{ /* mle=0 back to 1 */
2526: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2527: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2528: } /* End of if */
2529: ipmx +=1;
2530: sw += weight[i];
2531: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2532: /*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 2533: if(globpr){
1.141 brouard 2534: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2535: %11.6f %11.6f %11.6f ", \
2536: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2537: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2538: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2539: llt +=ll[k]*gipmx/gsw;
2540: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2541: }
2542: fprintf(ficresilk," %10.6f\n", -llt);
2543: }
2544: } /* end of wave */
2545: } /* end of individual */
2546: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2547: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2548: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2549: if(globpr==0){ /* First time we count the contributions and weights */
2550: gipmx=ipmx;
2551: gsw=sw;
2552: }
2553: return -l;
2554: }
2555:
2556:
2557: /*************** function likelione ***********/
2558: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2559: {
2560: /* This routine should help understanding what is done with
2561: the selection of individuals/waves and
2562: to check the exact contribution to the likelihood.
2563: Plotting could be done.
2564: */
2565: int k;
2566:
2567: if(*globpri !=0){ /* Just counts and sums, no printings */
2568: strcpy(fileresilk,"ilk");
2569: strcat(fileresilk,fileres);
2570: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2571: printf("Problem with resultfile: %s\n", fileresilk);
2572: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2573: }
2574: 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");
2575: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2576: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2577: for(k=1; k<=nlstate; k++)
2578: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2579: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2580: }
2581:
2582: *fretone=(*funcone)(p);
2583: if(*globpri !=0){
2584: fclose(ficresilk);
2585: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2586: fflush(fichtm);
2587: }
2588: return;
2589: }
2590:
2591:
2592: /*********** Maximum Likelihood Estimation ***************/
2593:
2594: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2595: {
1.165 brouard 2596: int i,j, iter=0;
1.126 brouard 2597: double **xi;
2598: double fret;
2599: double fretone; /* Only one call to likelihood */
2600: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2601:
2602: #ifdef NLOPT
2603: int creturn;
2604: nlopt_opt opt;
2605: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2606: double *lb;
2607: double minf; /* the minimum objective value, upon return */
2608: double * p1; /* Shifted parameters from 0 instead of 1 */
2609: myfunc_data dinst, *d = &dinst;
2610: #endif
2611:
2612:
1.126 brouard 2613: xi=matrix(1,npar,1,npar);
2614: for (i=1;i<=npar;i++)
2615: for (j=1;j<=npar;j++)
2616: xi[i][j]=(i==j ? 1.0 : 0.0);
2617: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2618: strcpy(filerespow,"pow");
2619: strcat(filerespow,fileres);
2620: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2621: printf("Problem with resultfile: %s\n", filerespow);
2622: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2623: }
2624: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2625: for (i=1;i<=nlstate;i++)
2626: for(j=1;j<=nlstate+ndeath;j++)
2627: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2628: fprintf(ficrespow,"\n");
1.162 brouard 2629: #ifdef POWELL
1.126 brouard 2630: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2631: #endif
1.126 brouard 2632:
1.162 brouard 2633: #ifdef NLOPT
2634: #ifdef NEWUOA
2635: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2636: #else
2637: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2638: #endif
2639: lb=vector(0,npar-1);
2640: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2641: nlopt_set_lower_bounds(opt, lb);
2642: nlopt_set_initial_step1(opt, 0.1);
2643:
2644: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2645: d->function = func;
2646: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2647: nlopt_set_min_objective(opt, myfunc, d);
2648: nlopt_set_xtol_rel(opt, ftol);
2649: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2650: printf("nlopt failed! %d\n",creturn);
2651: }
2652: else {
2653: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2654: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2655: iter=1; /* not equal */
2656: }
2657: nlopt_destroy(opt);
2658: #endif
1.126 brouard 2659: free_matrix(xi,1,npar,1,npar);
2660: fclose(ficrespow);
1.180 brouard 2661: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2662: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2663: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2664:
2665: }
2666:
2667: /**** Computes Hessian and covariance matrix ***/
2668: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2669: {
2670: double **a,**y,*x,pd;
2671: double **hess;
1.164 brouard 2672: int i, j;
1.126 brouard 2673: int *indx;
2674:
2675: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2676: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2677: void lubksb(double **a, int npar, int *indx, double b[]) ;
2678: void ludcmp(double **a, int npar, int *indx, double *d) ;
2679: double gompertz(double p[]);
2680: hess=matrix(1,npar,1,npar);
2681:
2682: printf("\nCalculation of the hessian matrix. Wait...\n");
2683: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2684: for (i=1;i<=npar;i++){
2685: printf("%d",i);fflush(stdout);
2686: fprintf(ficlog,"%d",i);fflush(ficlog);
2687:
2688: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2689:
2690: /* printf(" %f ",p[i]);
2691: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2692: }
2693:
2694: for (i=1;i<=npar;i++) {
2695: for (j=1;j<=npar;j++) {
2696: if (j>i) {
2697: printf(".%d%d",i,j);fflush(stdout);
2698: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2699: hess[i][j]=hessij(p,delti,i,j,func,npar);
2700:
2701: hess[j][i]=hess[i][j];
2702: /*printf(" %lf ",hess[i][j]);*/
2703: }
2704: }
2705: }
2706: printf("\n");
2707: fprintf(ficlog,"\n");
2708:
2709: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2710: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2711:
2712: a=matrix(1,npar,1,npar);
2713: y=matrix(1,npar,1,npar);
2714: x=vector(1,npar);
2715: indx=ivector(1,npar);
2716: for (i=1;i<=npar;i++)
2717: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2718: ludcmp(a,npar,indx,&pd);
2719:
2720: for (j=1;j<=npar;j++) {
2721: for (i=1;i<=npar;i++) x[i]=0;
2722: x[j]=1;
2723: lubksb(a,npar,indx,x);
2724: for (i=1;i<=npar;i++){
2725: matcov[i][j]=x[i];
2726: }
2727: }
2728:
2729: printf("\n#Hessian matrix#\n");
2730: fprintf(ficlog,"\n#Hessian matrix#\n");
2731: for (i=1;i<=npar;i++) {
2732: for (j=1;j<=npar;j++) {
2733: printf("%.3e ",hess[i][j]);
2734: fprintf(ficlog,"%.3e ",hess[i][j]);
2735: }
2736: printf("\n");
2737: fprintf(ficlog,"\n");
2738: }
2739:
2740: /* Recompute Inverse */
2741: for (i=1;i<=npar;i++)
2742: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2743: ludcmp(a,npar,indx,&pd);
2744:
2745: /* printf("\n#Hessian matrix recomputed#\n");
2746:
2747: for (j=1;j<=npar;j++) {
2748: for (i=1;i<=npar;i++) x[i]=0;
2749: x[j]=1;
2750: lubksb(a,npar,indx,x);
2751: for (i=1;i<=npar;i++){
2752: y[i][j]=x[i];
2753: printf("%.3e ",y[i][j]);
2754: fprintf(ficlog,"%.3e ",y[i][j]);
2755: }
2756: printf("\n");
2757: fprintf(ficlog,"\n");
2758: }
2759: */
2760:
2761: free_matrix(a,1,npar,1,npar);
2762: free_matrix(y,1,npar,1,npar);
2763: free_vector(x,1,npar);
2764: free_ivector(indx,1,npar);
2765: free_matrix(hess,1,npar,1,npar);
2766:
2767:
2768: }
2769:
2770: /*************** hessian matrix ****************/
2771: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2772: {
2773: int i;
2774: int l=1, lmax=20;
2775: double k1,k2;
1.132 brouard 2776: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2777: double res;
2778: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2779: double fx;
2780: int k=0,kmax=10;
2781: double l1;
2782:
2783: fx=func(x);
2784: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2785: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2786: l1=pow(10,l);
2787: delts=delt;
2788: for(k=1 ; k <kmax; k=k+1){
2789: delt = delta*(l1*k);
2790: p2[theta]=x[theta] +delt;
1.145 brouard 2791: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2792: p2[theta]=x[theta]-delt;
2793: k2=func(p2)-fx;
2794: /*res= (k1-2.0*fx+k2)/delt/delt; */
2795: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2796:
1.132 brouard 2797: #ifdef DEBUGHESS
1.126 brouard 2798: 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);
2799: 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);
2800: #endif
2801: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2802: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2803: k=kmax;
2804: }
2805: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2806: k=kmax; l=lmax*10;
1.126 brouard 2807: }
2808: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2809: delts=delt;
2810: }
2811: }
2812: }
2813: delti[theta]=delts;
2814: return res;
2815:
2816: }
2817:
2818: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2819: {
2820: int i;
1.164 brouard 2821: int l=1, lmax=20;
1.126 brouard 2822: double k1,k2,k3,k4,res,fx;
1.132 brouard 2823: double p2[MAXPARM+1];
1.126 brouard 2824: int k;
2825:
2826: fx=func(x);
2827: for (k=1; k<=2; k++) {
2828: for (i=1;i<=npar;i++) p2[i]=x[i];
2829: p2[thetai]=x[thetai]+delti[thetai]/k;
2830: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2831: k1=func(p2)-fx;
2832:
2833: p2[thetai]=x[thetai]+delti[thetai]/k;
2834: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2835: k2=func(p2)-fx;
2836:
2837: p2[thetai]=x[thetai]-delti[thetai]/k;
2838: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2839: k3=func(p2)-fx;
2840:
2841: p2[thetai]=x[thetai]-delti[thetai]/k;
2842: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2843: k4=func(p2)-fx;
2844: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2845: #ifdef DEBUG
2846: 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);
2847: 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);
2848: #endif
2849: }
2850: return res;
2851: }
2852:
2853: /************** Inverse of matrix **************/
2854: void ludcmp(double **a, int n, int *indx, double *d)
2855: {
2856: int i,imax,j,k;
2857: double big,dum,sum,temp;
2858: double *vv;
2859:
2860: vv=vector(1,n);
2861: *d=1.0;
2862: for (i=1;i<=n;i++) {
2863: big=0.0;
2864: for (j=1;j<=n;j++)
2865: if ((temp=fabs(a[i][j])) > big) big=temp;
2866: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2867: vv[i]=1.0/big;
2868: }
2869: for (j=1;j<=n;j++) {
2870: for (i=1;i<j;i++) {
2871: sum=a[i][j];
2872: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2873: a[i][j]=sum;
2874: }
2875: big=0.0;
2876: for (i=j;i<=n;i++) {
2877: sum=a[i][j];
2878: for (k=1;k<j;k++)
2879: sum -= a[i][k]*a[k][j];
2880: a[i][j]=sum;
2881: if ( (dum=vv[i]*fabs(sum)) >= big) {
2882: big=dum;
2883: imax=i;
2884: }
2885: }
2886: if (j != imax) {
2887: for (k=1;k<=n;k++) {
2888: dum=a[imax][k];
2889: a[imax][k]=a[j][k];
2890: a[j][k]=dum;
2891: }
2892: *d = -(*d);
2893: vv[imax]=vv[j];
2894: }
2895: indx[j]=imax;
2896: if (a[j][j] == 0.0) a[j][j]=TINY;
2897: if (j != n) {
2898: dum=1.0/(a[j][j]);
2899: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2900: }
2901: }
2902: free_vector(vv,1,n); /* Doesn't work */
2903: ;
2904: }
2905:
2906: void lubksb(double **a, int n, int *indx, double b[])
2907: {
2908: int i,ii=0,ip,j;
2909: double sum;
2910:
2911: for (i=1;i<=n;i++) {
2912: ip=indx[i];
2913: sum=b[ip];
2914: b[ip]=b[i];
2915: if (ii)
2916: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2917: else if (sum) ii=i;
2918: b[i]=sum;
2919: }
2920: for (i=n;i>=1;i--) {
2921: sum=b[i];
2922: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2923: b[i]=sum/a[i][i];
2924: }
2925: }
2926:
2927: void pstamp(FILE *fichier)
2928: {
1.196 brouard 2929: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126 brouard 2930: }
2931:
2932: /************ Frequencies ********************/
2933: 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[])
2934: { /* Some frequencies */
2935:
1.164 brouard 2936: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2937: int first;
2938: double ***freq; /* Frequencies */
2939: double *pp, **prop;
2940: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2941: char fileresp[FILENAMELENGTH];
2942:
2943: pp=vector(1,nlstate);
2944: prop=matrix(1,nlstate,iagemin,iagemax+3);
2945: strcpy(fileresp,"p");
2946: strcat(fileresp,fileres);
2947: if((ficresp=fopen(fileresp,"w"))==NULL) {
2948: printf("Problem with prevalence resultfile: %s\n", fileresp);
2949: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2950: exit(0);
2951: }
2952: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2953: j1=0;
2954:
2955: j=cptcoveff;
2956: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2957:
2958: first=1;
2959:
1.169 brouard 2960: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2961: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2962: /* j1++; */
1.145 brouard 2963: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2964: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2965: scanf("%d", i);*/
2966: for (i=-5; i<=nlstate+ndeath; i++)
2967: for (jk=-5; jk<=nlstate+ndeath; jk++)
2968: for(m=iagemin; m <= iagemax+3; m++)
2969: freq[i][jk][m]=0;
1.143 brouard 2970:
2971: for (i=1; i<=nlstate; i++)
2972: for(m=iagemin; m <= iagemax+3; m++)
2973: prop[i][m]=0;
1.126 brouard 2974:
2975: dateintsum=0;
2976: k2cpt=0;
2977: for (i=1; i<=imx; i++) {
2978: bool=1;
1.144 brouard 2979: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2980: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 2981: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145 brouard 2982: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2983: bool=0;
1.198 brouard 2984: /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n",
2985: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
2986: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
2987: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144 brouard 2988: }
1.126 brouard 2989: }
1.144 brouard 2990:
1.126 brouard 2991: if (bool==1){
2992: for(m=firstpass; m<=lastpass; m++){
2993: k2=anint[m][i]+(mint[m][i]/12.);
2994: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2995: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2996: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2997: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2998: if (m<lastpass) {
2999: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3000: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3001: }
3002:
3003: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
3004: dateintsum=dateintsum+k2;
3005: k2cpt++;
3006: }
3007: /*}*/
3008: }
3009: }
1.145 brouard 3010: } /* end i */
1.126 brouard 3011:
3012: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3013: pstamp(ficresp);
3014: if (cptcovn>0) {
3015: fprintf(ficresp, "\n#********** Variable ");
1.198 brouard 3016: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 3017: fprintf(ficresp, "**********\n#");
1.143 brouard 3018: fprintf(ficlog, "\n#********** Variable ");
1.198 brouard 3019: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143 brouard 3020: fprintf(ficlog, "**********\n#");
1.126 brouard 3021: }
3022: for(i=1; i<=nlstate;i++)
3023: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3024: fprintf(ficresp, "\n");
3025:
3026: for(i=iagemin; i <= iagemax+3; i++){
3027: if(i==iagemax+3){
3028: fprintf(ficlog,"Total");
3029: }else{
3030: if(first==1){
3031: first=0;
3032: printf("See log file for details...\n");
3033: }
3034: fprintf(ficlog,"Age %d", i);
3035: }
3036: for(jk=1; jk <=nlstate ; jk++){
3037: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3038: pp[jk] += freq[jk][m][i];
3039: }
3040: for(jk=1; jk <=nlstate ; jk++){
3041: for(m=-1, pos=0; m <=0 ; m++)
3042: pos += freq[jk][m][i];
3043: if(pp[jk]>=1.e-10){
3044: if(first==1){
1.132 brouard 3045: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3046: }
3047: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3048: }else{
3049: if(first==1)
3050: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3051: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3052: }
3053: }
3054:
3055: for(jk=1; jk <=nlstate ; jk++){
3056: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3057: pp[jk] += freq[jk][m][i];
3058: }
3059: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3060: pos += pp[jk];
3061: posprop += prop[jk][i];
3062: }
3063: for(jk=1; jk <=nlstate ; jk++){
3064: if(pos>=1.e-5){
3065: if(first==1)
3066: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3067: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3068: }else{
3069: if(first==1)
3070: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3071: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3072: }
3073: if( i <= iagemax){
3074: if(pos>=1.e-5){
3075: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3076: /*probs[i][jk][j1]= pp[jk]/pos;*/
3077: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3078: }
3079: else
3080: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3081: }
3082: }
3083:
3084: for(jk=-1; jk <=nlstate+ndeath; jk++)
3085: for(m=-1; m <=nlstate+ndeath; m++)
3086: if(freq[jk][m][i] !=0 ) {
3087: if(first==1)
3088: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3089: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3090: }
3091: if(i <= iagemax)
3092: fprintf(ficresp,"\n");
3093: if(first==1)
3094: printf("Others in log...\n");
3095: fprintf(ficlog,"\n");
3096: }
1.145 brouard 3097: /*}*/
1.126 brouard 3098: }
3099: dateintmean=dateintsum/k2cpt;
3100:
3101: fclose(ficresp);
3102: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3103: free_vector(pp,1,nlstate);
3104: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3105: /* End of Freq */
3106: }
3107:
3108: /************ Prevalence ********************/
3109: 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)
3110: {
3111: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3112: in each health status at the date of interview (if between dateprev1 and dateprev2).
3113: We still use firstpass and lastpass as another selection.
3114: */
3115:
1.164 brouard 3116: int i, m, jk, j1, bool, z1,j;
3117:
3118: double **prop;
3119: double posprop;
1.126 brouard 3120: double y2; /* in fractional years */
3121: int iagemin, iagemax;
1.145 brouard 3122: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3123:
3124: iagemin= (int) agemin;
3125: iagemax= (int) agemax;
3126: /*pp=vector(1,nlstate);*/
3127: prop=matrix(1,nlstate,iagemin,iagemax+3);
3128: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3129: j1=0;
3130:
1.145 brouard 3131: /*j=cptcoveff;*/
1.126 brouard 3132: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3133:
1.145 brouard 3134: first=1;
3135: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3136: /*for(i1=1; i1<=ncodemax[k1];i1++){
3137: j1++;*/
1.126 brouard 3138:
3139: for (i=1; i<=nlstate; i++)
3140: for(m=iagemin; m <= iagemax+3; m++)
3141: prop[i][m]=0.0;
3142:
3143: for (i=1; i<=imx; i++) { /* Each individual */
3144: bool=1;
3145: if (cptcovn>0) {
3146: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3147: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
1.126 brouard 3148: bool=0;
3149: }
3150: if (bool==1) {
3151: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3152: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3153: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3154: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3155: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3156: 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);
3157: if (s[m][i]>0 && s[m][i]<=nlstate) {
3158: /*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]]);*/
3159: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3160: prop[s[m][i]][iagemax+3] += weight[i];
3161: }
3162: }
3163: } /* end selection of waves */
3164: }
3165: }
3166: for(i=iagemin; i <= iagemax+3; i++){
3167: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3168: posprop += prop[jk][i];
3169: }
1.145 brouard 3170:
1.126 brouard 3171: for(jk=1; jk <=nlstate ; jk++){
3172: if( i <= iagemax){
3173: if(posprop>=1.e-5){
3174: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3175: } else{
3176: if(first==1){
3177: first=0;
3178: 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]);
3179: }
3180: }
1.126 brouard 3181: }
3182: }/* end jk */
3183: }/* end i */
1.145 brouard 3184: /*} *//* end i1 */
3185: } /* end j1 */
1.126 brouard 3186:
3187: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3188: /*free_vector(pp,1,nlstate);*/
3189: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3190: } /* End of prevalence */
3191:
3192: /************* Waves Concatenation ***************/
3193:
3194: 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)
3195: {
3196: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3197: Death is a valid wave (if date is known).
3198: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3199: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3200: and mw[mi+1][i]. dh depends on stepm.
3201: */
3202:
3203: int i, mi, m;
3204: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3205: double sum=0., jmean=0.;*/
3206: int first;
3207: int j, k=0,jk, ju, jl;
3208: double sum=0.;
3209: first=0;
1.164 brouard 3210: jmin=100000;
1.126 brouard 3211: jmax=-1;
3212: jmean=0.;
3213: for(i=1; i<=imx; i++){
3214: mi=0;
3215: m=firstpass;
3216: while(s[m][i] <= nlstate){
3217: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3218: mw[++mi][i]=m;
3219: if(m >=lastpass)
3220: break;
3221: else
3222: m++;
3223: }/* end while */
3224: if (s[m][i] > nlstate){
3225: mi++; /* Death is another wave */
3226: /* if(mi==0) never been interviewed correctly before death */
3227: /* Only death is a correct wave */
3228: mw[mi][i]=m;
3229: }
3230:
3231: wav[i]=mi;
3232: if(mi==0){
3233: nbwarn++;
3234: if(first==0){
3235: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3236: first=1;
3237: }
3238: if(first==1){
3239: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3240: }
3241: } /* end mi==0 */
3242: } /* End individuals */
3243:
3244: for(i=1; i<=imx; i++){
3245: for(mi=1; mi<wav[i];mi++){
3246: if (stepm <=0)
3247: dh[mi][i]=1;
3248: else{
3249: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3250: if (agedc[i] < 2*AGESUP) {
3251: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3252: if(j==0) j=1; /* Survives at least one month after exam */
3253: else if(j<0){
3254: nberr++;
3255: 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]);
3256: j=1; /* Temporary Dangerous patch */
3257: 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);
3258: 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]);
3259: 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);
3260: }
3261: k=k+1;
3262: if (j >= jmax){
3263: jmax=j;
3264: ijmax=i;
3265: }
3266: if (j <= jmin){
3267: jmin=j;
3268: ijmin=i;
3269: }
3270: sum=sum+j;
3271: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3272: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3273: }
3274: }
3275: else{
3276: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3277: /* 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]); */
3278:
3279: k=k+1;
3280: if (j >= jmax) {
3281: jmax=j;
3282: ijmax=i;
3283: }
3284: else if (j <= jmin){
3285: jmin=j;
3286: ijmin=i;
3287: }
3288: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3289: /*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]);*/
3290: if(j<0){
3291: nberr++;
3292: 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]);
3293: 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]);
3294: }
3295: sum=sum+j;
3296: }
3297: jk= j/stepm;
3298: jl= j -jk*stepm;
3299: ju= j -(jk+1)*stepm;
3300: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3301: if(jl==0){
3302: dh[mi][i]=jk;
3303: bh[mi][i]=0;
3304: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3305: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3306: dh[mi][i]=jk+1;
3307: bh[mi][i]=ju;
3308: }
3309: }else{
3310: if(jl <= -ju){
3311: dh[mi][i]=jk;
3312: bh[mi][i]=jl; /* bias is positive if real duration
3313: * is higher than the multiple of stepm and negative otherwise.
3314: */
3315: }
3316: else{
3317: dh[mi][i]=jk+1;
3318: bh[mi][i]=ju;
3319: }
3320: if(dh[mi][i]==0){
3321: dh[mi][i]=1; /* At least one step */
3322: bh[mi][i]=ju; /* At least one step */
3323: /* 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);*/
3324: }
3325: } /* end if mle */
3326: }
3327: } /* end wave */
3328: }
3329: jmean=sum/k;
3330: 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 3331: 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 3332: }
3333:
3334: /*********** Tricode ****************************/
1.145 brouard 3335: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3336: {
1.144 brouard 3337: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3338: /* 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 3339: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3340: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3341: * nbcode[Tvar[j]][1]=
1.144 brouard 3342: */
1.130 brouard 3343:
1.145 brouard 3344: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3345: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3346: int cptcode=0; /* Modality max of covariates j */
3347: int modmincovj=0; /* Modality min of covariates j */
3348:
3349:
1.126 brouard 3350: cptcoveff=0;
3351:
1.144 brouard 3352: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3353:
1.145 brouard 3354: /* Loop on covariates without age and products */
1.186 brouard 3355: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3356: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3357: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3358: modality of this covariate Vj*/
1.145 brouard 3359: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3360: * If product of Vn*Vm, still boolean *:
3361: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3362: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3363: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3364: modality of the nth covariate of individual i. */
1.145 brouard 3365: if (ij > modmaxcovj)
3366: modmaxcovj=ij;
3367: else if (ij < modmincovj)
3368: modmincovj=ij;
3369: if ((ij < -1) && (ij > NCOVMAX)){
3370: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3371: exit(1);
3372: }else
1.136 brouard 3373: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3374: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3375: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3376: /* getting the maximum value of the modality of the covariate
3377: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3378: female is 1, then modmaxcovj=1.*/
1.192 brouard 3379: } /* end for loop on individuals i */
1.145 brouard 3380: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3381: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145 brouard 3382: cptcode=modmaxcovj;
1.137 brouard 3383: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3384: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3385: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3386: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3387: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3388: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3389: if( k != -1){
3390: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3391: covariate for which somebody answered excluding
3392: undefined. Usually 2: 0 and 1. */
3393: }
3394: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3395: covariate for which somebody answered including
3396: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3397: }
3398: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3399: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3400: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3401:
1.136 brouard 3402: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3403: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3404: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145 brouard 3405: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3406: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3407: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3408: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3409: nbcode[Tvar[j]][ij]=k;
3410: nbcode[Tvar[j]][1]=0;
3411: nbcode[Tvar[j]][2]=1;
3412: nbcode[Tvar[j]][3]=2;
1.197 brouard 3413: To be continued (not working yet).
1.145 brouard 3414: */
1.197 brouard 3415: ij=0; /* ij is similar to i but can jump over null modalities */
3416: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
3417: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192 brouard 3418: break;
3419: }
3420: ij++;
1.197 brouard 3421: nbcode[Tvar[j]][ij]=i; /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
1.192 brouard 3422: cptcode = ij; /* New max modality for covar j */
3423: } /* end of loop on modality i=-1 to 1 or more */
3424:
3425: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3426: /* /\*recode from 0 *\/ */
3427: /* k is a modality. If we have model=V1+V1*sex */
3428: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3429: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3430: /* } */
3431: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3432: /* if (ij > ncodemax[j]) { */
3433: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3434: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3435: /* break; */
3436: /* } */
3437: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3438: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3439:
1.145 brouard 3440: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3441:
1.187 brouard 3442: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3443: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3444: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3445: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3446: }
1.126 brouard 3447:
1.192 brouard 3448: ij=0;
1.145 brouard 3449: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3450: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3451: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3452: ij++;
1.145 brouard 3453: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3454: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3455: }else{
3456: /* Tvaraff[ij]=0; */
3457: }
1.126 brouard 3458: }
1.192 brouard 3459: /* ij--; */
1.144 brouard 3460: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3461:
1.126 brouard 3462: }
3463:
1.145 brouard 3464:
1.126 brouard 3465: /*********** Health Expectancies ****************/
3466:
1.127 brouard 3467: 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 3468:
3469: {
3470: /* Health expectancies, no variances */
1.164 brouard 3471: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3472: int nhstepma, nstepma; /* Decreasing with age */
3473: double age, agelim, hf;
3474: double ***p3mat;
3475: double eip;
3476:
3477: pstamp(ficreseij);
3478: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3479: fprintf(ficreseij,"# Age");
3480: for(i=1; i<=nlstate;i++){
3481: for(j=1; j<=nlstate;j++){
3482: fprintf(ficreseij," e%1d%1d ",i,j);
3483: }
3484: fprintf(ficreseij," e%1d. ",i);
3485: }
3486: fprintf(ficreseij,"\n");
3487:
3488:
3489: if(estepm < stepm){
3490: printf ("Problem %d lower than %d\n",estepm, stepm);
3491: }
3492: else hstepm=estepm;
3493: /* We compute the life expectancy from trapezoids spaced every estepm months
3494: * This is mainly to measure the difference between two models: for example
3495: * if stepm=24 months pijx are given only every 2 years and by summing them
3496: * we are calculating an estimate of the Life Expectancy assuming a linear
3497: * progression in between and thus overestimating or underestimating according
3498: * to the curvature of the survival function. If, for the same date, we
3499: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3500: * to compare the new estimate of Life expectancy with the same linear
3501: * hypothesis. A more precise result, taking into account a more precise
3502: * curvature will be obtained if estepm is as small as stepm. */
3503:
3504: /* For example we decided to compute the life expectancy with the smallest unit */
3505: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3506: nhstepm is the number of hstepm from age to agelim
3507: nstepm is the number of stepm from age to agelin.
3508: Look at hpijx to understand the reason of that which relies in memory size
3509: and note for a fixed period like estepm months */
3510: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3511: survival function given by stepm (the optimization length). Unfortunately it
3512: means that if the survival funtion is printed only each two years of age and if
3513: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3514: results. So we changed our mind and took the option of the best precision.
3515: */
3516: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3517:
3518: agelim=AGESUP;
3519: /* If stepm=6 months */
3520: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3521: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3522:
3523: /* nhstepm age range expressed in number of stepm */
3524: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3525: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3526: /* if (stepm >= YEARM) hstepm=1;*/
3527: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3528: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3529:
3530: for (age=bage; age<=fage; age ++){
3531: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3532: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3533: /* if (stepm >= YEARM) hstepm=1;*/
3534: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3535:
3536: /* If stepm=6 months */
3537: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3538: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3539:
3540: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3541:
3542: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3543:
3544: printf("%d|",(int)age);fflush(stdout);
3545: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3546:
3547: /* Computing expectancies */
3548: for(i=1; i<=nlstate;i++)
3549: for(j=1; j<=nlstate;j++)
3550: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3551: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3552:
3553: /* 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]);*/
3554:
3555: }
3556:
3557: fprintf(ficreseij,"%3.0f",age );
3558: for(i=1; i<=nlstate;i++){
3559: eip=0;
3560: for(j=1; j<=nlstate;j++){
3561: eip +=eij[i][j][(int)age];
3562: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3563: }
3564: fprintf(ficreseij,"%9.4f", eip );
3565: }
3566: fprintf(ficreseij,"\n");
3567:
3568: }
3569: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3570: printf("\n");
3571: fprintf(ficlog,"\n");
3572:
3573: }
3574:
1.127 brouard 3575: 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 3576:
3577: {
3578: /* Covariances of health expectancies eij and of total life expectancies according
3579: to initial status i, ei. .
3580: */
3581: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3582: int nhstepma, nstepma; /* Decreasing with age */
3583: double age, agelim, hf;
3584: double ***p3matp, ***p3matm, ***varhe;
3585: double **dnewm,**doldm;
3586: double *xp, *xm;
3587: double **gp, **gm;
3588: double ***gradg, ***trgradg;
3589: int theta;
3590:
3591: double eip, vip;
3592:
3593: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3594: xp=vector(1,npar);
3595: xm=vector(1,npar);
3596: dnewm=matrix(1,nlstate*nlstate,1,npar);
3597: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3598:
3599: pstamp(ficresstdeij);
3600: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3601: fprintf(ficresstdeij,"# Age");
3602: for(i=1; i<=nlstate;i++){
3603: for(j=1; j<=nlstate;j++)
3604: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3605: fprintf(ficresstdeij," e%1d. ",i);
3606: }
3607: fprintf(ficresstdeij,"\n");
3608:
3609: pstamp(ficrescveij);
3610: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3611: fprintf(ficrescveij,"# Age");
3612: for(i=1; i<=nlstate;i++)
3613: for(j=1; j<=nlstate;j++){
3614: cptj= (j-1)*nlstate+i;
3615: for(i2=1; i2<=nlstate;i2++)
3616: for(j2=1; j2<=nlstate;j2++){
3617: cptj2= (j2-1)*nlstate+i2;
3618: if(cptj2 <= cptj)
3619: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3620: }
3621: }
3622: fprintf(ficrescveij,"\n");
3623:
3624: if(estepm < stepm){
3625: printf ("Problem %d lower than %d\n",estepm, stepm);
3626: }
3627: else hstepm=estepm;
3628: /* We compute the life expectancy from trapezoids spaced every estepm months
3629: * This is mainly to measure the difference between two models: for example
3630: * if stepm=24 months pijx are given only every 2 years and by summing them
3631: * we are calculating an estimate of the Life Expectancy assuming a linear
3632: * progression in between and thus overestimating or underestimating according
3633: * to the curvature of the survival function. If, for the same date, we
3634: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3635: * to compare the new estimate of Life expectancy with the same linear
3636: * hypothesis. A more precise result, taking into account a more precise
3637: * curvature will be obtained if estepm is as small as stepm. */
3638:
3639: /* For example we decided to compute the life expectancy with the smallest unit */
3640: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3641: nhstepm is the number of hstepm from age to agelim
3642: nstepm is the number of stepm from age to agelin.
3643: Look at hpijx to understand the reason of that which relies in memory size
3644: and note for a fixed period like estepm months */
3645: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3646: survival function given by stepm (the optimization length). Unfortunately it
3647: means that if the survival funtion is printed only each two years of age and if
3648: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3649: results. So we changed our mind and took the option of the best precision.
3650: */
3651: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3652:
3653: /* If stepm=6 months */
3654: /* nhstepm age range expressed in number of stepm */
3655: agelim=AGESUP;
3656: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3657: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3658: /* if (stepm >= YEARM) hstepm=1;*/
3659: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3660:
3661: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3662: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3663: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3664: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3665: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3666: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3667:
3668: for (age=bage; age<=fage; age ++){
3669: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3670: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3671: /* if (stepm >= YEARM) hstepm=1;*/
3672: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3673:
3674: /* If stepm=6 months */
3675: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3676: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3677:
3678: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3679:
3680: /* Computing Variances of health expectancies */
3681: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3682: decrease memory allocation */
3683: for(theta=1; theta <=npar; theta++){
3684: for(i=1; i<=npar; i++){
3685: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3686: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3687: }
3688: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3689: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3690:
3691: for(j=1; j<= nlstate; j++){
3692: for(i=1; i<=nlstate; i++){
3693: for(h=0; h<=nhstepm-1; h++){
3694: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3695: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3696: }
3697: }
3698: }
3699:
3700: for(ij=1; ij<= nlstate*nlstate; ij++)
3701: for(h=0; h<=nhstepm-1; h++){
3702: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3703: }
3704: }/* End theta */
3705:
3706:
3707: for(h=0; h<=nhstepm-1; h++)
3708: for(j=1; j<=nlstate*nlstate;j++)
3709: for(theta=1; theta <=npar; theta++)
3710: trgradg[h][j][theta]=gradg[h][theta][j];
3711:
3712:
3713: for(ij=1;ij<=nlstate*nlstate;ij++)
3714: for(ji=1;ji<=nlstate*nlstate;ji++)
3715: varhe[ij][ji][(int)age] =0.;
3716:
3717: printf("%d|",(int)age);fflush(stdout);
3718: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3719: for(h=0;h<=nhstepm-1;h++){
3720: for(k=0;k<=nhstepm-1;k++){
3721: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3722: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3723: for(ij=1;ij<=nlstate*nlstate;ij++)
3724: for(ji=1;ji<=nlstate*nlstate;ji++)
3725: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3726: }
3727: }
3728:
3729: /* Computing expectancies */
3730: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3731: for(i=1; i<=nlstate;i++)
3732: for(j=1; j<=nlstate;j++)
3733: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3734: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3735:
3736: /* 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]);*/
3737:
3738: }
3739:
3740: fprintf(ficresstdeij,"%3.0f",age );
3741: for(i=1; i<=nlstate;i++){
3742: eip=0.;
3743: vip=0.;
3744: for(j=1; j<=nlstate;j++){
3745: eip += eij[i][j][(int)age];
3746: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3747: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3748: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3749: }
3750: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3751: }
3752: fprintf(ficresstdeij,"\n");
3753:
3754: fprintf(ficrescveij,"%3.0f",age );
3755: for(i=1; i<=nlstate;i++)
3756: for(j=1; j<=nlstate;j++){
3757: cptj= (j-1)*nlstate+i;
3758: for(i2=1; i2<=nlstate;i2++)
3759: for(j2=1; j2<=nlstate;j2++){
3760: cptj2= (j2-1)*nlstate+i2;
3761: if(cptj2 <= cptj)
3762: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3763: }
3764: }
3765: fprintf(ficrescveij,"\n");
3766:
3767: }
3768: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3769: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3770: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3771: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3772: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3773: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3774: printf("\n");
3775: fprintf(ficlog,"\n");
3776:
3777: free_vector(xm,1,npar);
3778: free_vector(xp,1,npar);
3779: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3780: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3781: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3782: }
3783:
3784: /************ Variance ******************/
3785: 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[])
3786: {
3787: /* Variance of health expectancies */
3788: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3789: /* double **newm;*/
1.169 brouard 3790: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3791:
3792: int movingaverage();
1.126 brouard 3793: double **dnewm,**doldm;
3794: double **dnewmp,**doldmp;
3795: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3796: int k;
1.126 brouard 3797: double *xp;
3798: double **gp, **gm; /* for var eij */
3799: double ***gradg, ***trgradg; /*for var eij */
3800: double **gradgp, **trgradgp; /* for var p point j */
3801: double *gpp, *gmp; /* for var p point j */
3802: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3803: double ***p3mat;
3804: double age,agelim, hf;
3805: double ***mobaverage;
3806: int theta;
3807: char digit[4];
3808: char digitp[25];
3809:
3810: char fileresprobmorprev[FILENAMELENGTH];
3811:
3812: if(popbased==1){
3813: if(mobilav!=0)
3814: strcpy(digitp,"-populbased-mobilav-");
3815: else strcpy(digitp,"-populbased-nomobil-");
3816: }
3817: else
3818: strcpy(digitp,"-stablbased-");
3819:
3820: if (mobilav!=0) {
3821: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3822: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3823: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3824: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3825: }
3826: }
3827:
3828: strcpy(fileresprobmorprev,"prmorprev");
3829: sprintf(digit,"%-d",ij);
3830: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3831: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3832: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3833: strcat(fileresprobmorprev,fileres);
3834: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3835: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3836: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3837: }
3838: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3839:
3840: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3841: pstamp(ficresprobmorprev);
3842: 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);
3843: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3844: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3845: fprintf(ficresprobmorprev," p.%-d SE",j);
3846: for(i=1; i<=nlstate;i++)
3847: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3848: }
3849: fprintf(ficresprobmorprev,"\n");
3850: fprintf(ficgp,"\n# Routine varevsij");
1.200 ! brouard 3851: fprintf(ficgp,"\nunset title \n");
! 3852: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126 brouard 3853: 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");
3854: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3855: /* } */
3856: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3857: pstamp(ficresvij);
3858: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3859: if(popbased==1)
1.128 brouard 3860: 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 3861: else
3862: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3863: fprintf(ficresvij,"# Age");
3864: for(i=1; i<=nlstate;i++)
3865: for(j=1; j<=nlstate;j++)
3866: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3867: fprintf(ficresvij,"\n");
3868:
3869: xp=vector(1,npar);
3870: dnewm=matrix(1,nlstate,1,npar);
3871: doldm=matrix(1,nlstate,1,nlstate);
3872: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3873: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3874:
3875: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3876: gpp=vector(nlstate+1,nlstate+ndeath);
3877: gmp=vector(nlstate+1,nlstate+ndeath);
3878: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3879:
3880: if(estepm < stepm){
3881: printf ("Problem %d lower than %d\n",estepm, stepm);
3882: }
3883: else hstepm=estepm;
3884: /* For example we decided to compute the life expectancy with the smallest unit */
3885: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3886: nhstepm is the number of hstepm from age to agelim
3887: nstepm is the number of stepm from age to agelin.
1.128 brouard 3888: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3889: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3890: survival function given by stepm (the optimization length). Unfortunately it
3891: means that if the survival funtion is printed every two years of age and if
3892: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3893: results. So we changed our mind and took the option of the best precision.
3894: */
3895: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3896: agelim = AGESUP;
3897: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3898: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3899: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3900: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3901: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3902: gp=matrix(0,nhstepm,1,nlstate);
3903: gm=matrix(0,nhstepm,1,nlstate);
3904:
3905:
3906: for(theta=1; theta <=npar; theta++){
3907: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3908: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3909: }
3910: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3911: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3912:
3913: if (popbased==1) {
3914: if(mobilav ==0){
3915: for(i=1; i<=nlstate;i++)
3916: prlim[i][i]=probs[(int)age][i][ij];
3917: }else{ /* mobilav */
3918: for(i=1; i<=nlstate;i++)
3919: prlim[i][i]=mobaverage[(int)age][i][ij];
3920: }
3921: }
3922:
3923: for(j=1; j<= nlstate; j++){
3924: for(h=0; h<=nhstepm; h++){
3925: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3926: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3927: }
3928: }
3929: /* This for computing probability of death (h=1 means
3930: computed over hstepm matrices product = hstepm*stepm months)
3931: as a weighted average of prlim.
3932: */
3933: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3934: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3935: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3936: }
3937: /* end probability of death */
3938:
3939: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3940: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3941: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3942: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3943:
3944: if (popbased==1) {
3945: if(mobilav ==0){
3946: for(i=1; i<=nlstate;i++)
3947: prlim[i][i]=probs[(int)age][i][ij];
3948: }else{ /* mobilav */
3949: for(i=1; i<=nlstate;i++)
3950: prlim[i][i]=mobaverage[(int)age][i][ij];
3951: }
3952: }
3953:
1.128 brouard 3954: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3955: for(h=0; h<=nhstepm; h++){
3956: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3957: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3958: }
3959: }
3960: /* This for computing probability of death (h=1 means
3961: computed over hstepm matrices product = hstepm*stepm months)
3962: as a weighted average of prlim.
3963: */
3964: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3965: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3966: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3967: }
3968: /* end probability of death */
3969:
3970: for(j=1; j<= nlstate; j++) /* vareij */
3971: for(h=0; h<=nhstepm; h++){
3972: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3973: }
3974:
3975: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3976: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3977: }
3978:
3979: } /* End theta */
3980:
3981: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3982:
3983: for(h=0; h<=nhstepm; h++) /* veij */
3984: for(j=1; j<=nlstate;j++)
3985: for(theta=1; theta <=npar; theta++)
3986: trgradg[h][j][theta]=gradg[h][theta][j];
3987:
3988: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3989: for(theta=1; theta <=npar; theta++)
3990: trgradgp[j][theta]=gradgp[theta][j];
3991:
3992:
3993: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3994: for(i=1;i<=nlstate;i++)
3995: for(j=1;j<=nlstate;j++)
3996: vareij[i][j][(int)age] =0.;
3997:
3998: for(h=0;h<=nhstepm;h++){
3999: for(k=0;k<=nhstepm;k++){
4000: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4001: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4002: for(i=1;i<=nlstate;i++)
4003: for(j=1;j<=nlstate;j++)
4004: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4005: }
4006: }
4007:
4008: /* pptj */
4009: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4010: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4011: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4012: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4013: varppt[j][i]=doldmp[j][i];
4014: /* end ppptj */
4015: /* x centered again */
4016: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4017: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
4018:
4019: if (popbased==1) {
4020: if(mobilav ==0){
4021: for(i=1; i<=nlstate;i++)
4022: prlim[i][i]=probs[(int)age][i][ij];
4023: }else{ /* mobilav */
4024: for(i=1; i<=nlstate;i++)
4025: prlim[i][i]=mobaverage[(int)age][i][ij];
4026: }
4027: }
4028:
4029: /* This for computing probability of death (h=1 means
4030: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4031: as a weighted average of prlim.
4032: */
4033: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4034: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4035: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4036: }
4037: /* end probability of death */
4038:
4039: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4040: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4041: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4042: for(i=1; i<=nlstate;i++){
4043: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4044: }
4045: }
4046: fprintf(ficresprobmorprev,"\n");
4047:
4048: fprintf(ficresvij,"%.0f ",age );
4049: for(i=1; i<=nlstate;i++)
4050: for(j=1; j<=nlstate;j++){
4051: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4052: }
4053: fprintf(ficresvij,"\n");
4054: free_matrix(gp,0,nhstepm,1,nlstate);
4055: free_matrix(gm,0,nhstepm,1,nlstate);
4056: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4057: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4058: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4059: } /* End age */
4060: free_vector(gpp,nlstate+1,nlstate+ndeath);
4061: free_vector(gmp,nlstate+1,nlstate+ndeath);
4062: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4063: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199 brouard 4064: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4065: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126 brouard 4066: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4067: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.200 ! brouard 4068: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
1.126 brouard 4069: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4070: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4071: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4072: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4073: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4074: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4075: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.199 brouard 4076: fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
4077: /* 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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
1.126 brouard 4078: */
1.199 brouard 4079: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.200 ! brouard 4080: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
1.126 brouard 4081:
4082: free_vector(xp,1,npar);
4083: free_matrix(doldm,1,nlstate,1,nlstate);
4084: free_matrix(dnewm,1,nlstate,1,npar);
4085: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4086: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4087: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4088: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4089: fclose(ficresprobmorprev);
4090: fflush(ficgp);
4091: fflush(fichtm);
4092: } /* end varevsij */
4093:
4094: /************ Variance of prevlim ******************/
4095: 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[])
4096: {
4097: /* Variance of prevalence limit */
4098: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4099:
1.126 brouard 4100: double **dnewm,**doldm;
4101: int i, j, nhstepm, hstepm;
4102: double *xp;
4103: double *gp, *gm;
4104: double **gradg, **trgradg;
4105: double age,agelim;
4106: int theta;
4107:
4108: pstamp(ficresvpl);
4109: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4110: fprintf(ficresvpl,"# Age");
4111: for(i=1; i<=nlstate;i++)
4112: fprintf(ficresvpl," %1d-%1d",i,i);
4113: fprintf(ficresvpl,"\n");
4114:
4115: xp=vector(1,npar);
4116: dnewm=matrix(1,nlstate,1,npar);
4117: doldm=matrix(1,nlstate,1,nlstate);
4118:
4119: hstepm=1*YEARM; /* Every year of age */
4120: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4121: agelim = AGESUP;
4122: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4123: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4124: if (stepm >= YEARM) hstepm=1;
4125: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4126: gradg=matrix(1,npar,1,nlstate);
4127: gp=vector(1,nlstate);
4128: gm=vector(1,nlstate);
4129:
4130: for(theta=1; theta <=npar; theta++){
4131: for(i=1; i<=npar; i++){ /* Computes gradient */
4132: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4133: }
4134: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4135: for(i=1;i<=nlstate;i++)
4136: gp[i] = prlim[i][i];
4137:
4138: for(i=1; i<=npar; i++) /* Computes gradient */
4139: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4140: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
4141: for(i=1;i<=nlstate;i++)
4142: gm[i] = prlim[i][i];
4143:
4144: for(i=1;i<=nlstate;i++)
4145: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4146: } /* End theta */
4147:
4148: trgradg =matrix(1,nlstate,1,npar);
4149:
4150: for(j=1; j<=nlstate;j++)
4151: for(theta=1; theta <=npar; theta++)
4152: trgradg[j][theta]=gradg[theta][j];
4153:
4154: for(i=1;i<=nlstate;i++)
4155: varpl[i][(int)age] =0.;
4156: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4157: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4158: for(i=1;i<=nlstate;i++)
4159: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4160:
4161: fprintf(ficresvpl,"%.0f ",age );
4162: for(i=1; i<=nlstate;i++)
4163: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4164: fprintf(ficresvpl,"\n");
4165: free_vector(gp,1,nlstate);
4166: free_vector(gm,1,nlstate);
4167: free_matrix(gradg,1,npar,1,nlstate);
4168: free_matrix(trgradg,1,nlstate,1,npar);
4169: } /* End age */
4170:
4171: free_vector(xp,1,npar);
4172: free_matrix(doldm,1,nlstate,1,npar);
4173: free_matrix(dnewm,1,nlstate,1,nlstate);
4174:
4175: }
4176:
4177: /************ Variance of one-step probabilities ******************/
4178: 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[])
4179: {
1.164 brouard 4180: int i, j=0, k1, l1, tj;
1.126 brouard 4181: int k2, l2, j1, z1;
1.164 brouard 4182: int k=0, l;
1.145 brouard 4183: int first=1, first1, first2;
1.126 brouard 4184: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4185: double **dnewm,**doldm;
4186: double *xp;
4187: double *gp, *gm;
4188: double **gradg, **trgradg;
4189: double **mu;
1.164 brouard 4190: double age, cov[NCOVMAX+1];
1.126 brouard 4191: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4192: int theta;
4193: char fileresprob[FILENAMELENGTH];
4194: char fileresprobcov[FILENAMELENGTH];
4195: char fileresprobcor[FILENAMELENGTH];
4196: double ***varpij;
4197:
4198: strcpy(fileresprob,"prob");
4199: strcat(fileresprob,fileres);
4200: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4201: printf("Problem with resultfile: %s\n", fileresprob);
4202: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4203: }
4204: strcpy(fileresprobcov,"probcov");
4205: strcat(fileresprobcov,fileres);
4206: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4207: printf("Problem with resultfile: %s\n", fileresprobcov);
4208: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4209: }
4210: strcpy(fileresprobcor,"probcor");
4211: strcat(fileresprobcor,fileres);
4212: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4213: printf("Problem with resultfile: %s\n", fileresprobcor);
4214: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4215: }
4216: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4217: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4218: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4219: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4220: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4221: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4222: pstamp(ficresprob);
4223: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4224: fprintf(ficresprob,"# Age");
4225: pstamp(ficresprobcov);
4226: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4227: fprintf(ficresprobcov,"# Age");
4228: pstamp(ficresprobcor);
4229: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4230: fprintf(ficresprobcor,"# Age");
4231:
4232:
4233: for(i=1; i<=nlstate;i++)
4234: for(j=1; j<=(nlstate+ndeath);j++){
4235: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4236: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4237: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4238: }
4239: /* fprintf(ficresprob,"\n");
4240: fprintf(ficresprobcov,"\n");
4241: fprintf(ficresprobcor,"\n");
4242: */
1.131 brouard 4243: xp=vector(1,npar);
1.126 brouard 4244: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4245: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4246: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4247: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4248: first=1;
4249: fprintf(ficgp,"\n# Routine varprob");
4250: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4251: fprintf(fichtm,"\n");
4252:
1.200 ! brouard 4253: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
1.197 brouard 4254: fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
4255: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126 brouard 4256: and drawn. It helps understanding how is the covariance between two incidences.\
4257: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4258: 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. \
4259: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4260: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4261: standard deviations wide on each axis. <br>\
4262: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4263: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4264: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4265:
4266: cov[1]=1;
1.145 brouard 4267: /* tj=cptcoveff; */
4268: tj = (int) pow(2,cptcoveff);
1.126 brouard 4269: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4270: j1=0;
1.145 brouard 4271: for(j1=1; j1<=tj;j1++){
4272: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4273: /*j1++;*/
1.126 brouard 4274: if (cptcovn>0) {
4275: fprintf(ficresprob, "\n#********** Variable ");
1.198 brouard 4276: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4277: fprintf(ficresprob, "**********\n#\n");
4278: fprintf(ficresprobcov, "\n#********** Variable ");
1.198 brouard 4279: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4280: fprintf(ficresprobcov, "**********\n#\n");
4281:
4282: fprintf(ficgp, "\n#********** Variable ");
1.198 brouard 4283: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4284: fprintf(ficgp, "**********\n#\n");
4285:
4286:
4287: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
1.198 brouard 4288: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4289: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4290:
4291: fprintf(ficresprobcor, "\n#********** Variable ");
1.198 brouard 4292: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4293: fprintf(ficresprobcor, "**********\n#");
4294: }
4295:
1.145 brouard 4296: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4297: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4298: gp=vector(1,(nlstate)*(nlstate+ndeath));
4299: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4300: for (age=bage; age<=fage; age ++){
4301: cov[2]=age;
1.187 brouard 4302: if(nagesqr==1)
4303: cov[3]= age*age;
1.126 brouard 4304: for (k=1; k<=cptcovn;k++) {
1.200 ! brouard 4305: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
! 4306: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145 brouard 4307: * 1 1 1 1 1
4308: * 2 2 1 1 1
4309: * 3 1 2 1 1
4310: */
4311: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4312: }
1.186 brouard 4313: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 ! brouard 4314: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126 brouard 4315: for (k=1; k<=cptcovprod;k++)
1.200 ! brouard 4316: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126 brouard 4317:
4318:
4319: for(theta=1; theta <=npar; theta++){
4320: for(i=1; i<=npar; i++)
4321: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4322:
4323: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4324:
4325: k=0;
4326: for(i=1; i<= (nlstate); i++){
4327: for(j=1; j<=(nlstate+ndeath);j++){
4328: k=k+1;
4329: gp[k]=pmmij[i][j];
4330: }
4331: }
4332:
4333: for(i=1; i<=npar; i++)
4334: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4335:
4336: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4337: k=0;
4338: for(i=1; i<=(nlstate); i++){
4339: for(j=1; j<=(nlstate+ndeath);j++){
4340: k=k+1;
4341: gm[k]=pmmij[i][j];
4342: }
4343: }
4344:
4345: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4346: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4347: }
4348:
4349: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4350: for(theta=1; theta <=npar; theta++)
4351: trgradg[j][theta]=gradg[theta][j];
4352:
4353: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4354: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4355:
4356: pmij(pmmij,cov,ncovmodel,x,nlstate);
4357:
4358: k=0;
4359: for(i=1; i<=(nlstate); i++){
4360: for(j=1; j<=(nlstate+ndeath);j++){
4361: k=k+1;
4362: mu[k][(int) age]=pmmij[i][j];
4363: }
4364: }
4365: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4366: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4367: varpij[i][j][(int)age] = doldm[i][j];
4368:
4369: /*printf("\n%d ",(int)age);
4370: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4371: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4372: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4373: }*/
4374:
4375: fprintf(ficresprob,"\n%d ",(int)age);
4376: fprintf(ficresprobcov,"\n%d ",(int)age);
4377: fprintf(ficresprobcor,"\n%d ",(int)age);
4378:
4379: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4380: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4381: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4382: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4383: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4384: }
4385: i=0;
4386: for (k=1; k<=(nlstate);k++){
4387: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4388: i++;
1.126 brouard 4389: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4390: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4391: for (j=1; j<=i;j++){
1.145 brouard 4392: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4393: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4394: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4395: }
4396: }
4397: }/* end of loop for state */
4398: } /* end of loop for age */
1.145 brouard 4399: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4400: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4401: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4402: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4403:
1.126 brouard 4404: /* Confidence intervalle of pij */
4405: /*
1.131 brouard 4406: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4407: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4408: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4409: 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);
4410: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4411: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4412: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4413: */
4414:
4415: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4416: first1=1;first2=2;
1.126 brouard 4417: for (k2=1; k2<=(nlstate);k2++){
4418: for (l2=1; l2<=(nlstate+ndeath);l2++){
4419: if(l2==k2) continue;
4420: j=(k2-1)*(nlstate+ndeath)+l2;
4421: for (k1=1; k1<=(nlstate);k1++){
4422: for (l1=1; l1<=(nlstate+ndeath);l1++){
4423: if(l1==k1) continue;
4424: i=(k1-1)*(nlstate+ndeath)+l1;
4425: if(i<=j) continue;
4426: for (age=bage; age<=fage; age ++){
4427: if ((int)age %5==0){
4428: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4429: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4430: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4431: mu1=mu[i][(int) age]/stepm*YEARM ;
4432: mu2=mu[j][(int) age]/stepm*YEARM;
4433: c12=cv12/sqrt(v1*v2);
4434: /* Computing eigen value of matrix of covariance */
4435: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4436: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4437: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4438: if(first2==1){
4439: first1=0;
4440: 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);
4441: }
4442: 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);
4443: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4444: /* lc2=fabs(lc2); */
1.135 brouard 4445: }
4446:
1.126 brouard 4447: /* Eigen vectors */
4448: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4449: /*v21=sqrt(1.-v11*v11); *//* error */
4450: v21=(lc1-v1)/cv12*v11;
4451: v12=-v21;
4452: v22=v11;
4453: tnalp=v21/v11;
4454: if(first1==1){
4455: first1=0;
4456: 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);
4457: }
4458: 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);
4459: /*printf(fignu*/
4460: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4461: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4462: if(first==1){
4463: first=0;
1.200 ! brouard 4464: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126 brouard 4465: fprintf(ficgp,"\nset parametric;unset label");
4466: 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.199 brouard 4467: fprintf(ficgp,"\nset ter svg size 640, 480");
1.126 brouard 4468: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.199 brouard 4469: :<a href=\"%s%d%1d%1d-%1d%1d.svg\">\
4470: %s%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.126 brouard 4471: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4472: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.199 brouard 4473: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126 brouard 4474: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.199 brouard 4475: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126 brouard 4476: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4477: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4478: 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",\
4479: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4480: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4481: }else{
4482: first=0;
4483: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4484: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4485: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4486: 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",\
4487: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4488: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4489: }/* if first */
4490: } /* age mod 5 */
4491: } /* end loop age */
1.200 ! brouard 4492: fprintf(ficgp,"\nset out;\nset out \"%s%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
1.126 brouard 4493: first=1;
4494: } /*l12 */
4495: } /* k12 */
4496: } /*l1 */
4497: }/* k1 */
1.169 brouard 4498: /* } */ /* loop covariates */
1.126 brouard 4499: }
4500: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4501: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4502: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4503: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4504: free_vector(xp,1,npar);
4505: fclose(ficresprob);
4506: fclose(ficresprobcov);
4507: fclose(ficresprobcor);
4508: fflush(ficgp);
4509: fflush(fichtmcov);
4510: }
4511:
4512:
4513: /******************* Printing html file ***********/
4514: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4515: int lastpass, int stepm, int weightopt, char model[],\
4516: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4517: int popforecast, int estepm ,\
4518: double jprev1, double mprev1,double anprev1, \
4519: double jprev2, double mprev2,double anprev2){
4520: int jj1, k1, i1, cpt;
4521:
4522: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4523: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4524: </ul>");
4525: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4526: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4527: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4528: fprintf(fichtm,"\
4529: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4530: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4531: fprintf(fichtm,"\
4532: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4533: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4534: fprintf(fichtm,"\
1.128 brouard 4535: - (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 4536: <a href=\"%s\">%s</a> <br>\n",
4537: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4538: fprintf(fichtm,"\
4539: - Population projections by age and states: \
4540: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4541:
4542: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4543:
1.145 brouard 4544: m=pow(2,cptcoveff);
1.126 brouard 4545: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4546:
4547: jj1=0;
4548: for(k1=1; k1<=m;k1++){
1.192 brouard 4549: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4550: jj1++;
4551: if (cptcovn > 0) {
4552: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4553: for (cpt=1; cpt<=cptcoveff;cpt++){
1.198 brouard 4554: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4555: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192 brouard 4556: }
1.126 brouard 4557: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4558: }
4559: /* Pij */
1.199 brouard 4560: 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.svg\">%s%d_1.svg</a><br> \
4561: <img src=\"%s%d_1.svg\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4562: /* Quasi-incidences */
4563: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.199 brouard 4564: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.svg\">%s%d_2.svg</a><br> \
4565: <img src=\"%s%d_2.svg\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4566: /* Period (stable) prevalence in each health state */
1.154 brouard 4567: for(cpt=1; cpt<=nlstate;cpt++){
1.199 brouard 4568: 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.svg\">%s%d_%d.svg</a><br> \
4569: <img src=\"%s%d_%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126 brouard 4570: }
4571: for(cpt=1; cpt<=nlstate;cpt++) {
1.199 brouard 4572: 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.svg\">%s%d%d.svg</a> <br> \
4573: <img src=\"%s%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
1.126 brouard 4574: }
1.192 brouard 4575: /* } /\* end i1 *\/ */
1.126 brouard 4576: }/* End k1 */
4577: fprintf(fichtm,"</ul>");
4578:
4579: fprintf(fichtm,"\
4580: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4581: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197 brouard 4582: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
4583: But because parameters are usually highly correlated (a higher incidence of disability \
4584: and a higher incidence of recovery can give very close observed transition) it might \
4585: be very useful to look not only at linear confidence intervals estimated from the \
4586: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4587: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4588: covariance matrix of the one-step probabilities. \
4589: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126 brouard 4590:
1.193 brouard 4591: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.126 brouard 4592: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4593: fprintf(fichtm,"\
4594: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4595: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4596:
4597: fprintf(fichtm,"\
4598: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4599: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4600: fprintf(fichtm,"\
4601: - 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): \
4602: <a href=\"%s\">%s</a> <br>\n</li>",
4603: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4604: fprintf(fichtm,"\
4605: - (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): \
4606: <a href=\"%s\">%s</a> <br>\n</li>",
4607: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4608: fprintf(fichtm,"\
1.128 brouard 4609: - 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 4610: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4611: fprintf(fichtm,"\
1.128 brouard 4612: - 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",
4613: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4614: fprintf(fichtm,"\
4615: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4616: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4617:
4618: /* if(popforecast==1) fprintf(fichtm,"\n */
4619: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4620: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4621: /* <br>",fileres,fileres,fileres,fileres); */
4622: /* else */
4623: /* 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); */
4624: fflush(fichtm);
4625: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4626:
1.145 brouard 4627: m=pow(2,cptcoveff);
1.126 brouard 4628: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4629:
4630: jj1=0;
4631: for(k1=1; k1<=m;k1++){
1.192 brouard 4632: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4633: jj1++;
4634: if (cptcovn > 0) {
4635: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4636: for (cpt=1; cpt<=cptcoveff;cpt++)
1.198 brouard 4637: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126 brouard 4638: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4639: }
4640: for(cpt=1; cpt<=nlstate;cpt++) {
4641: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199 brouard 4642: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
4643: <img src=\"%s%d_%d.svg\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4644: }
4645: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4646: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4647: true period expectancies (those weighted with period prevalences are also\
4648: drawn in addition to the population based expectancies computed using\
1.199 brouard 4649: observed and cahotic prevalences: %s%d.svg<br>\
4650: <img src=\"%s%d.svg\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
1.192 brouard 4651: /* } /\* end i1 *\/ */
1.126 brouard 4652: }/* End k1 */
4653: fprintf(fichtm,"</ul>");
4654: fflush(fichtm);
4655: }
4656:
4657: /******************* Gnuplot file **************/
4658: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4659:
4660: char dirfileres[132],optfileres[132];
1.164 brouard 4661: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4662: int ng=0;
1.126 brouard 4663: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4664: /* printf("Problem with file %s",optionfilegnuplot); */
4665: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4666: /* } */
4667:
4668: /*#ifdef windows */
4669: fprintf(ficgp,"cd \"%s\" \n",pathc);
4670: /*#endif */
4671: m=pow(2,cptcoveff);
4672:
4673: strcpy(dirfileres,optionfilefiname);
4674: strcpy(optfileres,"vpl");
4675: /* 1eme*/
1.153 brouard 4676: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4677: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4678: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.199 brouard 4679: fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4680: fprintf(ficgp,"\n#set out \"v%s%d_%d.svg\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4681: fprintf(ficgp,"set xlabel \"Age\" \n\
4682: set ylabel \"Probability\" \n\
1.199 brouard 4683: set ter svg size 640, 480\n\
1.170 brouard 4684: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4685:
4686: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4687: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4688: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4689: }
1.170 brouard 4690: 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 4691: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4692: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4693: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4694: }
1.170 brouard 4695: 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 4696: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4697: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4698: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4699: }
1.145 brouard 4700: 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 4701: }
4702: }
4703: /*2 eme*/
1.153 brouard 4704: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4705: for (k1=1; k1<= m ; k1 ++) {
1.199 brouard 4706: fprintf(ficgp,"\nset out \"%s%d.svg\" \n",subdirf2(optionfilefiname,"e"),k1);
4707: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4708:
4709: for (i=1; i<= nlstate+1 ; i ++) {
4710: k=2*i;
1.170 brouard 4711: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4712: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4713: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4714: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4715: }
4716: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4717: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4718: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4719: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4720: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4721: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4722: }
1.145 brouard 4723: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4724: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4725: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4726: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4727: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4728: }
1.145 brouard 4729: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4730: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4731: }
4732: }
4733:
4734: /*3eme*/
4735:
4736: for (k1=1; k1<= m ; k1 ++) {
4737: for (cpt=1; cpt<= nlstate ; cpt ++) {
4738: /* k=2+nlstate*(2*cpt-2); */
4739: k=2+(nlstate+1)*(cpt-1);
1.199 brouard 4740: fprintf(ficgp,"\nset out \"%s%d%d.svg\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4741: fprintf(ficgp,"set ter svg size 640, 480\n\
1.126 brouard 4742: 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);
4743: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4744: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4745: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4746: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4747: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4748: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4749:
4750: */
4751: for (i=1; i< nlstate ; i ++) {
4752: 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);
4753: /* 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);*/
4754:
4755: }
4756: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4757: }
4758: }
4759:
4760: /* CV preval stable (period) */
1.153 brouard 4761: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4762: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4763: k=3;
1.153 brouard 4764: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.199 brouard 4765: fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4766: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199 brouard 4767: set ter svg size 640, 480\n\
1.126 brouard 4768: unset log y\n\
1.153 brouard 4769: plot [%.f:%.f] ", ageminpar, agemaxpar);
4770: for (i=1; i<= nlstate ; i ++){
4771: if(i==1)
4772: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4773: else
4774: fprintf(ficgp,", '' ");
1.154 brouard 4775: l=(nlstate+ndeath)*(i-1)+1;
4776: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4777: for (j=1; j<= (nlstate-1) ; j ++)
4778: fprintf(ficgp,"+$%d",k+l+j);
4779: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4780: } /* nlstate */
4781: fprintf(ficgp,"\n");
4782: } /* end cpt state*/
4783: } /* end covariate */
1.126 brouard 4784:
4785: /* proba elementaires */
1.187 brouard 4786: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 4787: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 4788: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 4789: for(k=1; k <=(nlstate+ndeath); k++){
4790: if (k != i) {
1.187 brouard 4791: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 4792: for(j=1; j <=ncovmodel; j++){
1.187 brouard 4793: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 4794: jk++;
4795: }
1.187 brouard 4796: fprintf(ficgp,"\n");
1.126 brouard 4797: }
4798: }
4799: }
1.187 brouard 4800: fprintf(ficgp,"##############\n#\n");
4801:
1.145 brouard 4802: /*goto avoid;*/
1.200 ! brouard 4803: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187 brouard 4804: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
4805: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
4806: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
4807: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
4808: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4809: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4810: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4811: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
4812: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
4813: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
4814: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
4815: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
4816: fprintf(ficgp,"#\n");
1.126 brouard 4817: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
1.187 brouard 4818: fprintf(ficgp,"# ng=%d\n",ng);
4819: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 4820: for(jk=1; jk <=m; jk++) {
1.187 brouard 4821: fprintf(ficgp,"# jk=%d\n",jk);
1.199 brouard 4822: fprintf(ficgp,"\nset out \"%s%d_%d.svg\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4823: if (ng==2)
4824: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4825: else
1.200 ! brouard 4826: fprintf(ficgp,"\nunset title \n");
1.199 brouard 4827: fprintf(ficgp,"\nset ter svg size 640, 480\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4828: i=1;
4829: for(k2=1; k2<=nlstate; k2++) {
4830: k3=i;
4831: for(k=1; k<=(nlstate+ndeath); k++) {
4832: if (k != k2){
4833: if(ng==2)
1.187 brouard 4834: if(nagesqr==0)
4835: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4836: else /* nagesqr =1 */
4837: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
1.126 brouard 4838: else
1.187 brouard 4839: if(nagesqr==0)
4840: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4841: else /* nagesqr =1 */
4842: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
1.141 brouard 4843: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 4844: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197 brouard 4845: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
4846: if(ij <=cptcovage) { /* Bug valgrind */
4847: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200 ! brouard 4848: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
! 4849: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197 brouard 4850: ij++;
4851: }
1.186 brouard 4852: }
4853: else
1.198 brouard 4854: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 4855: }
4856: fprintf(ficgp,")/(1");
4857:
1.187 brouard 4858: for(k1=1; k1 <=nlstate; k1++){
4859: if(nagesqr==0)
4860: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4861: else /* nagesqr =1 */
4862: fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
4863:
1.126 brouard 4864: ij=1;
1.187 brouard 4865: for(j=3; j <=ncovmodel-nagesqr; j++){
1.197 brouard 4866: if(ij <=cptcovage) { /* Bug valgrind */
4867: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200 ! brouard 4868: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
! 4869: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197 brouard 4870: ij++;
4871: }
1.186 brouard 4872: }
4873: else
1.198 brouard 4874: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 4875: }
4876: fprintf(ficgp,")");
4877: }
4878: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4879: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4880: i=i+ncovmodel;
4881: }
4882: } /* end k */
4883: } /* end k2 */
4884: } /* end jk */
4885: } /* end ng */
1.164 brouard 4886: /* avoid: */
1.126 brouard 4887: fflush(ficgp);
4888: } /* end gnuplot */
4889:
4890:
4891: /*************** Moving average **************/
4892: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4893:
4894: int i, cpt, cptcod;
4895: int modcovmax =1;
4896: int mobilavrange, mob;
4897: double age;
4898:
4899: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4900: a covariate has 2 modalities */
4901: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4902:
4903: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4904: if(mobilav==1) mobilavrange=5; /* default */
4905: else mobilavrange=mobilav;
4906: for (age=bage; age<=fage; age++)
4907: for (i=1; i<=nlstate;i++)
4908: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4909: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4910: /* We keep the original values on the extreme ages bage, fage and for
4911: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4912: we use a 5 terms etc. until the borders are no more concerned.
4913: */
4914: for (mob=3;mob <=mobilavrange;mob=mob+2){
4915: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4916: for (i=1; i<=nlstate;i++){
4917: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4918: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4919: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4920: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4921: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4922: }
4923: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4924: }
4925: }
4926: }/* end age */
4927: }/* end mob */
4928: }else return -1;
4929: return 0;
4930: }/* End movingaverage */
4931:
4932:
4933: /************** Forecasting ******************/
1.169 brouard 4934: 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 4935: /* proj1, year, month, day of starting projection
4936: agemin, agemax range of age
4937: dateprev1 dateprev2 range of dates during which prevalence is computed
4938: anproj2 year of en of projection (same day and month as proj1).
4939: */
1.164 brouard 4940: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4941: double agec; /* generic age */
4942: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4943: double *popeffectif,*popcount;
4944: double ***p3mat;
4945: double ***mobaverage;
4946: char fileresf[FILENAMELENGTH];
4947:
4948: agelim=AGESUP;
4949: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4950:
4951: strcpy(fileresf,"f");
4952: strcat(fileresf,fileres);
4953: if((ficresf=fopen(fileresf,"w"))==NULL) {
4954: printf("Problem with forecast resultfile: %s\n", fileresf);
4955: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4956: }
4957: printf("Computing forecasting: result on file '%s' \n", fileresf);
4958: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4959:
4960: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4961:
4962: if (mobilav!=0) {
4963: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4964: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4965: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4966: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4967: }
4968: }
4969:
4970: stepsize=(int) (stepm+YEARM-1)/YEARM;
4971: if (stepm<=12) stepsize=1;
4972: if(estepm < stepm){
4973: printf ("Problem %d lower than %d\n",estepm, stepm);
4974: }
4975: else hstepm=estepm;
4976:
4977: hstepm=hstepm/stepm;
4978: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4979: fractional in yp1 */
4980: anprojmean=yp;
4981: yp2=modf((yp1*12),&yp);
4982: mprojmean=yp;
4983: yp1=modf((yp2*30.5),&yp);
4984: jprojmean=yp;
4985: if(jprojmean==0) jprojmean=1;
4986: if(mprojmean==0) jprojmean=1;
4987:
4988: i1=cptcoveff;
4989: if (cptcovn < 1){i1=1;}
4990:
4991: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4992:
4993: fprintf(ficresf,"#****** Routine prevforecast **\n");
4994:
4995: /* if (h==(int)(YEARM*yearp)){ */
4996: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4997: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4998: k=k+1;
4999: fprintf(ficresf,"\n#******");
5000: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5001: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5002: }
5003: fprintf(ficresf,"******\n");
5004: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
5005: for(j=1; j<=nlstate+ndeath;j++){
5006: for(i=1; i<=nlstate;i++)
5007: fprintf(ficresf," p%d%d",i,j);
5008: fprintf(ficresf," p.%d",j);
5009: }
5010: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5011: fprintf(ficresf,"\n");
5012: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5013:
5014: for (agec=fage; agec>=(ageminpar-1); agec--){
5015: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5016: nhstepm = nhstepm/hstepm;
5017: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5018: oldm=oldms;savm=savms;
5019: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5020:
5021: for (h=0; h<=nhstepm; h++){
5022: if (h*hstepm/YEARM*stepm ==yearp) {
5023: fprintf(ficresf,"\n");
5024: for(j=1;j<=cptcoveff;j++)
1.198 brouard 5025: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5026: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5027: }
5028: for(j=1; j<=nlstate+ndeath;j++) {
5029: ppij=0.;
5030: for(i=1; i<=nlstate;i++) {
5031: if (mobilav==1)
5032: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5033: else {
5034: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5035: }
5036: if (h*hstepm/YEARM*stepm== yearp) {
5037: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5038: }
5039: } /* end i */
5040: if (h*hstepm/YEARM*stepm==yearp) {
5041: fprintf(ficresf," %.3f", ppij);
5042: }
5043: }/* end j */
5044: } /* end h */
5045: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5046: } /* end agec */
5047: } /* end yearp */
5048: } /* end cptcod */
5049: } /* end cptcov */
5050:
5051: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5052:
5053: fclose(ficresf);
5054: }
5055:
5056: /************** Forecasting *****not tested NB*************/
1.169 brouard 5057: 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 5058:
5059: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5060: int *popage;
5061: double calagedatem, agelim, kk1, kk2;
5062: double *popeffectif,*popcount;
5063: double ***p3mat,***tabpop,***tabpopprev;
5064: double ***mobaverage;
5065: char filerespop[FILENAMELENGTH];
5066:
5067: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5068: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5069: agelim=AGESUP;
5070: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5071:
5072: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5073:
5074:
5075: strcpy(filerespop,"pop");
5076: strcat(filerespop,fileres);
5077: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5078: printf("Problem with forecast resultfile: %s\n", filerespop);
5079: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5080: }
5081: printf("Computing forecasting: result on file '%s' \n", filerespop);
5082: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5083:
5084: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5085:
5086: if (mobilav!=0) {
5087: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5088: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5089: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5090: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5091: }
5092: }
5093:
5094: stepsize=(int) (stepm+YEARM-1)/YEARM;
5095: if (stepm<=12) stepsize=1;
5096:
5097: agelim=AGESUP;
5098:
5099: hstepm=1;
5100: hstepm=hstepm/stepm;
5101:
5102: if (popforecast==1) {
5103: if((ficpop=fopen(popfile,"r"))==NULL) {
5104: printf("Problem with population file : %s\n",popfile);exit(0);
5105: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5106: }
5107: popage=ivector(0,AGESUP);
5108: popeffectif=vector(0,AGESUP);
5109: popcount=vector(0,AGESUP);
5110:
5111: i=1;
5112: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5113:
5114: imx=i;
5115: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5116: }
5117:
5118: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5119: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5120: k=k+1;
5121: fprintf(ficrespop,"\n#******");
5122: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5123: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5124: }
5125: fprintf(ficrespop,"******\n");
5126: fprintf(ficrespop,"# Age");
5127: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5128: if (popforecast==1) fprintf(ficrespop," [Population]");
5129:
5130: for (cpt=0; cpt<=0;cpt++) {
5131: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5132:
5133: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5134: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5135: nhstepm = nhstepm/hstepm;
5136:
5137: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5138: oldm=oldms;savm=savms;
5139: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5140:
5141: for (h=0; h<=nhstepm; h++){
5142: if (h==(int) (calagedatem+YEARM*cpt)) {
5143: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5144: }
5145: for(j=1; j<=nlstate+ndeath;j++) {
5146: kk1=0.;kk2=0;
5147: for(i=1; i<=nlstate;i++) {
5148: if (mobilav==1)
5149: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5150: else {
5151: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5152: }
5153: }
5154: if (h==(int)(calagedatem+12*cpt)){
5155: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5156: /*fprintf(ficrespop," %.3f", kk1);
5157: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5158: }
5159: }
5160: for(i=1; i<=nlstate;i++){
5161: kk1=0.;
5162: for(j=1; j<=nlstate;j++){
5163: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5164: }
5165: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5166: }
5167:
5168: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5169: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5170: }
5171: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5172: }
5173: }
5174:
5175: /******/
5176:
5177: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5178: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5179: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5180: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5181: nhstepm = nhstepm/hstepm;
5182:
5183: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5184: oldm=oldms;savm=savms;
5185: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5186: for (h=0; h<=nhstepm; h++){
5187: if (h==(int) (calagedatem+YEARM*cpt)) {
5188: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5189: }
5190: for(j=1; j<=nlstate+ndeath;j++) {
5191: kk1=0.;kk2=0;
5192: for(i=1; i<=nlstate;i++) {
5193: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5194: }
5195: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5196: }
5197: }
5198: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5199: }
5200: }
5201: }
5202: }
5203:
5204: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5205:
5206: if (popforecast==1) {
5207: free_ivector(popage,0,AGESUP);
5208: free_vector(popeffectif,0,AGESUP);
5209: free_vector(popcount,0,AGESUP);
5210: }
5211: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5212: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5213: fclose(ficrespop);
5214: } /* End of popforecast */
5215:
5216: int fileappend(FILE *fichier, char *optionfich)
5217: {
5218: if((fichier=fopen(optionfich,"a"))==NULL) {
5219: printf("Problem with file: %s\n", optionfich);
5220: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5221: return (0);
5222: }
5223: fflush(fichier);
5224: return (1);
5225: }
5226:
5227:
5228: /**************** function prwizard **********************/
5229: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5230: {
5231:
5232: /* Wizard to print covariance matrix template */
5233:
1.164 brouard 5234: char ca[32], cb[32];
5235: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5236: int numlinepar;
5237:
5238: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5239: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5240: for(i=1; i <=nlstate; i++){
5241: jj=0;
5242: for(j=1; j <=nlstate+ndeath; j++){
5243: if(j==i) continue;
5244: jj++;
5245: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5246: printf("%1d%1d",i,j);
5247: fprintf(ficparo,"%1d%1d",i,j);
5248: for(k=1; k<=ncovmodel;k++){
5249: /* printf(" %lf",param[i][j][k]); */
5250: /* fprintf(ficparo," %lf",param[i][j][k]); */
5251: printf(" 0.");
5252: fprintf(ficparo," 0.");
5253: }
5254: printf("\n");
5255: fprintf(ficparo,"\n");
5256: }
5257: }
5258: printf("# Scales (for hessian or gradient estimation)\n");
5259: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5260: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5261: for(i=1; i <=nlstate; i++){
5262: jj=0;
5263: for(j=1; j <=nlstate+ndeath; j++){
5264: if(j==i) continue;
5265: jj++;
5266: fprintf(ficparo,"%1d%1d",i,j);
5267: printf("%1d%1d",i,j);
5268: fflush(stdout);
5269: for(k=1; k<=ncovmodel;k++){
5270: /* printf(" %le",delti3[i][j][k]); */
5271: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5272: printf(" 0.");
5273: fprintf(ficparo," 0.");
5274: }
5275: numlinepar++;
5276: printf("\n");
5277: fprintf(ficparo,"\n");
5278: }
5279: }
5280: printf("# Covariance matrix\n");
5281: /* # 121 Var(a12)\n\ */
5282: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5283: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5284: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5285: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5286: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5287: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5288: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5289: fflush(stdout);
5290: fprintf(ficparo,"# Covariance matrix\n");
5291: /* # 121 Var(a12)\n\ */
5292: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5293: /* # ...\n\ */
5294: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5295:
5296: for(itimes=1;itimes<=2;itimes++){
5297: jj=0;
5298: for(i=1; i <=nlstate; i++){
5299: for(j=1; j <=nlstate+ndeath; j++){
5300: if(j==i) continue;
5301: for(k=1; k<=ncovmodel;k++){
5302: jj++;
5303: ca[0]= k+'a'-1;ca[1]='\0';
5304: if(itimes==1){
5305: printf("#%1d%1d%d",i,j,k);
5306: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5307: }else{
5308: printf("%1d%1d%d",i,j,k);
5309: fprintf(ficparo,"%1d%1d%d",i,j,k);
5310: /* printf(" %.5le",matcov[i][j]); */
5311: }
5312: ll=0;
5313: for(li=1;li <=nlstate; li++){
5314: for(lj=1;lj <=nlstate+ndeath; lj++){
5315: if(lj==li) continue;
5316: for(lk=1;lk<=ncovmodel;lk++){
5317: ll++;
5318: if(ll<=jj){
5319: cb[0]= lk +'a'-1;cb[1]='\0';
5320: if(ll<jj){
5321: if(itimes==1){
5322: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5323: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5324: }else{
5325: printf(" 0.");
5326: fprintf(ficparo," 0.");
5327: }
5328: }else{
5329: if(itimes==1){
5330: printf(" Var(%s%1d%1d)",ca,i,j);
5331: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5332: }else{
5333: printf(" 0.");
5334: fprintf(ficparo," 0.");
5335: }
5336: }
5337: }
5338: } /* end lk */
5339: } /* end lj */
5340: } /* end li */
5341: printf("\n");
5342: fprintf(ficparo,"\n");
5343: numlinepar++;
5344: } /* end k*/
5345: } /*end j */
5346: } /* end i */
5347: } /* end itimes */
5348:
5349: } /* end of prwizard */
5350: /******************* Gompertz Likelihood ******************************/
5351: double gompertz(double x[])
5352: {
5353: double A,B,L=0.0,sump=0.,num=0.;
5354: int i,n=0; /* n is the size of the sample */
5355:
5356: for (i=0;i<=imx-1 ; i++) {
5357: sump=sump+weight[i];
5358: /* sump=sump+1;*/
5359: num=num+1;
5360: }
5361:
5362:
5363: /* for (i=0; i<=imx; i++)
5364: 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]);*/
5365:
5366: for (i=1;i<=imx ; i++)
5367: {
5368: if (cens[i] == 1 && wav[i]>1)
5369: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5370:
5371: if (cens[i] == 0 && wav[i]>1)
5372: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5373: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5374:
5375: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5376: if (wav[i] > 1 ) { /* ??? */
5377: L=L+A*weight[i];
5378: /* 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]);*/
5379: }
5380: }
5381:
5382: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5383:
5384: return -2*L*num/sump;
5385: }
5386:
1.136 brouard 5387: #ifdef GSL
5388: /******************* Gompertz_f Likelihood ******************************/
5389: double gompertz_f(const gsl_vector *v, void *params)
5390: {
5391: double A,B,LL=0.0,sump=0.,num=0.;
5392: double *x= (double *) v->data;
5393: int i,n=0; /* n is the size of the sample */
5394:
5395: for (i=0;i<=imx-1 ; i++) {
5396: sump=sump+weight[i];
5397: /* sump=sump+1;*/
5398: num=num+1;
5399: }
5400:
5401:
5402: /* for (i=0; i<=imx; i++)
5403: 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]);*/
5404: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5405: for (i=1;i<=imx ; i++)
5406: {
5407: if (cens[i] == 1 && wav[i]>1)
5408: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5409:
5410: if (cens[i] == 0 && wav[i]>1)
5411: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5412: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5413:
5414: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5415: if (wav[i] > 1 ) { /* ??? */
5416: LL=LL+A*weight[i];
5417: /* 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]);*/
5418: }
5419: }
5420:
5421: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5422: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5423:
5424: return -2*LL*num/sump;
5425: }
5426: #endif
5427:
1.126 brouard 5428: /******************* Printing html file ***********/
5429: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5430: int lastpass, int stepm, int weightopt, char model[],\
5431: int imx, double p[],double **matcov,double agemortsup){
5432: int i,k;
5433:
5434: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5435: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5436: for (i=1;i<=2;i++)
5437: 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]));
1.199 brouard 5438: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126 brouard 5439: fprintf(fichtm,"</ul>");
5440:
5441: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5442:
5443: 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>");
5444:
5445: for (k=agegomp;k<(agemortsup-2);k++)
5446: 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]);
5447:
5448:
5449: fflush(fichtm);
5450: }
5451:
5452: /******************* Gnuplot file **************/
5453: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5454:
5455: char dirfileres[132],optfileres[132];
1.164 brouard 5456:
1.126 brouard 5457: int ng;
5458:
5459:
5460: /*#ifdef windows */
5461: fprintf(ficgp,"cd \"%s\" \n",pathc);
5462: /*#endif */
5463:
5464:
5465: strcpy(dirfileres,optionfilefiname);
5466: strcpy(optfileres,"vpl");
1.199 brouard 5467: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
1.126 brouard 5468: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.199 brouard 5469: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
1.145 brouard 5470: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 5471: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5472:
5473: }
5474:
1.136 brouard 5475: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5476: {
1.126 brouard 5477:
1.136 brouard 5478: /*-------- data file ----------*/
5479: FILE *fic;
5480: char dummy[]=" ";
1.164 brouard 5481: int i=0, j=0, n=0;
1.136 brouard 5482: int linei, month, year,iout;
5483: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5484: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5485: char *stratrunc;
5486: int lstra;
1.126 brouard 5487:
5488:
1.136 brouard 5489: if((fic=fopen(datafile,"r"))==NULL) {
1.195 brouard 5490: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5491: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136 brouard 5492: }
1.126 brouard 5493:
1.136 brouard 5494: i=1;
5495: linei=0;
5496: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5497: linei=linei+1;
5498: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5499: if(line[j] == '\t')
5500: line[j] = ' ';
5501: }
5502: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5503: ;
5504: };
5505: line[j+1]=0; /* Trims blanks at end of line */
5506: if(line[0]=='#'){
5507: fprintf(ficlog,"Comment line\n%s\n",line);
5508: printf("Comment line\n%s\n",line);
5509: continue;
5510: }
5511: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5512: strcpy(line, linetmp);
1.136 brouard 5513:
1.126 brouard 5514:
1.136 brouard 5515: for (j=maxwav;j>=1;j--){
1.137 brouard 5516: cutv(stra, strb, line, ' ');
1.136 brouard 5517: if(strb[0]=='.') { /* Missing status */
5518: lval=-1;
5519: }else{
5520: errno=0;
5521: lval=strtol(strb,&endptr,10);
5522: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5523: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5524: 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);
5525: 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 5526: return 1;
5527: }
5528: }
5529: s[j][i]=lval;
5530:
5531: strcpy(line,stra);
5532: cutv(stra, strb,line,' ');
1.169 brouard 5533: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5534: }
1.169 brouard 5535: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5536: month=99;
5537: year=9999;
5538: }else{
1.141 brouard 5539: 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);
5540: 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 5541: return 1;
5542: }
5543: anint[j][i]= (double) year;
5544: mint[j][i]= (double)month;
5545: strcpy(line,stra);
5546: } /* ENd Waves */
5547:
5548: cutv(stra, strb,line,' ');
1.169 brouard 5549: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5550: }
1.169 brouard 5551: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5552: month=99;
5553: year=9999;
5554: }else{
1.141 brouard 5555: 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);
5556: 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 5557: return 1;
5558: }
5559: andc[i]=(double) year;
5560: moisdc[i]=(double) month;
5561: strcpy(line,stra);
5562:
5563: cutv(stra, strb,line,' ');
1.169 brouard 5564: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5565: }
1.169 brouard 5566: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5567: month=99;
5568: year=9999;
5569: }else{
1.141 brouard 5570: 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);
5571: 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 5572: return 1;
5573: }
5574: if (year==9999) {
1.141 brouard 5575: 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);
5576: 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 5577: return 1;
1.126 brouard 5578:
1.136 brouard 5579: }
5580: annais[i]=(double)(year);
5581: moisnais[i]=(double)(month);
5582: strcpy(line,stra);
5583:
5584: cutv(stra, strb,line,' ');
5585: errno=0;
5586: dval=strtod(strb,&endptr);
5587: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5588: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5589: 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 5590: fflush(ficlog);
5591: return 1;
5592: }
5593: weight[i]=dval;
5594: strcpy(line,stra);
5595:
5596: for (j=ncovcol;j>=1;j--){
5597: cutv(stra, strb,line,' ');
5598: if(strb[0]=='.') { /* Missing status */
5599: lval=-1;
5600: }else{
5601: errno=0;
5602: lval=strtol(strb,&endptr,10);
5603: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5604: 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);
5605: 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 5606: return 1;
5607: }
5608: }
5609: if(lval <-1 || lval >1){
1.141 brouard 5610: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5611: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5612: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5613: For example, for multinomial values like 1, 2 and 3,\n \
5614: build V1=0 V2=0 for the reference value (1),\n \
5615: V1=1 V2=0 for (2) \n \
5616: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5617: output of IMaCh is often meaningless.\n \
5618: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5619: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5620: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5621: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5622: For example, for multinomial values like 1, 2 and 3,\n \
5623: build V1=0 V2=0 for the reference value (1),\n \
5624: V1=1 V2=0 for (2) \n \
5625: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5626: output of IMaCh is often meaningless.\n \
5627: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5628: return 1;
5629: }
5630: covar[j][i]=(double)(lval);
5631: strcpy(line,stra);
5632: }
5633: lstra=strlen(stra);
5634:
5635: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5636: stratrunc = &(stra[lstra-9]);
5637: num[i]=atol(stratrunc);
5638: }
5639: else
5640: num[i]=atol(stra);
5641: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5642: 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;}*/
5643:
5644: i=i+1;
5645: } /* End loop reading data */
1.126 brouard 5646:
1.136 brouard 5647: *imax=i-1; /* Number of individuals */
5648: fclose(fic);
5649:
5650: return (0);
1.164 brouard 5651: /* endread: */
1.136 brouard 5652: printf("Exiting readdata: ");
5653: fclose(fic);
5654: return (1);
1.126 brouard 5655:
5656:
5657:
1.136 brouard 5658: }
1.145 brouard 5659: void removespace(char *str) {
5660: char *p1 = str, *p2 = str;
5661: do
5662: while (*p2 == ' ')
5663: p2++;
1.169 brouard 5664: while (*p1++ == *p2++);
1.145 brouard 5665: }
5666:
5667: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 5668: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
5669: * - nagesqr = 1 if age*age in the model, otherwise 0.
5670: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
5671: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 5672: * - cptcovage number of covariates with age*products =2
5673: * - cptcovs number of simple covariates
5674: * - 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
5675: * which is a new column after the 9 (ncovcol) variables.
5676: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5677: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5678: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5679: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5680: */
1.136 brouard 5681: {
1.145 brouard 5682: int i, j, k, ks;
1.164 brouard 5683: int j1, k1, k2;
1.136 brouard 5684: char modelsav[80];
1.145 brouard 5685: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 5686: char *strpt;
1.136 brouard 5687:
1.145 brouard 5688: /*removespace(model);*/
1.136 brouard 5689: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5690: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 5691: if (strstr(model,"AGE") !=0){
1.192 brouard 5692: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
5693: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 5694: return 1;
5695: }
1.141 brouard 5696: if (strstr(model,"v") !=0){
5697: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5698: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5699: return 1;
5700: }
1.187 brouard 5701: strcpy(modelsav,model);
5702: if ((strpt=strstr(model,"age*age")) !=0){
5703: printf(" strpt=%s, model=%s\n",strpt, model);
5704: if(strpt != model){
5705: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5706: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5707: corresponding column of parameters.\n",model);
5708: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 5709: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 5710: corresponding column of parameters.\n",model); fflush(ficlog);
5711: return 1;
5712: }
5713:
5714: nagesqr=1;
5715: if (strstr(model,"+age*age") !=0)
5716: substrchaine(modelsav, model, "+age*age");
5717: else if (strstr(model,"age*age+") !=0)
5718: substrchaine(modelsav, model, "age*age+");
5719: else
5720: substrchaine(modelsav, model, "age*age");
5721: }else
5722: nagesqr=0;
5723: if (strlen(modelsav) >1){
5724: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
5725: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
5726: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
5727: cptcovt= j+1; /* Number of total covariates in the model, not including
5728: * cst, age and age*age
5729: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
5730: /* including age products which are counted in cptcovage.
5731: * but the covariates which are products must be treated
5732: * separately: ncovn=4- 2=2 (V1+V3). */
5733: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5734: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5735:
5736:
5737: /* Design
5738: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5739: * < ncovcol=8 >
5740: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5741: * k= 1 2 3 4 5 6 7 8
5742: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5743: * covar[k,i], value of kth covariate if not including age for individual i:
5744: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5745: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5746: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5747: * Tage[++cptcovage]=k
5748: * if products, new covar are created after ncovcol with k1
5749: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5750: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5751: * 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
5752: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5753: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5754: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5755: * < ncovcol=8 >
5756: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5757: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5758: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5759: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5760: * p Tprod[1]@2={ 6, 5}
5761: *p Tvard[1][1]@4= {7, 8, 5, 6}
5762: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5763: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5764: *How to reorganize?
5765: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5766: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5767: * {2, 1, 4, 8, 5, 6, 3, 7}
5768: * Struct []
5769: */
1.145 brouard 5770:
1.187 brouard 5771: /* This loop fills the array Tvar from the string 'model'.*/
5772: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5773: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5774: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5775: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5776: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5777: /* k=1 Tvar[1]=2 (from V2) */
5778: /* k=5 Tvar[5] */
5779: /* for (k=1; k<=cptcovn;k++) { */
1.198 brouard 5780: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187 brouard 5781: /* } */
1.198 brouard 5782: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187 brouard 5783: /*
5784: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5785: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 5786: Tvar[k]=0;
1.187 brouard 5787: cptcovage=0;
5788: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5789: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5790: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5791: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5792: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5793: /*scanf("%d",i);*/
5794: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5795: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5796: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5797: /* covar is not filled and then is empty */
5798: cptcovprod--;
5799: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5800: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
5801: cptcovage++; /* Sums the number of covariates which include age as a product */
5802: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
5803: /*printf("stre=%s ", stre);*/
5804: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5805: cptcovprod--;
5806: cutl(stre,strb,strc,'V');
5807: Tvar[k]=atoi(stre);
5808: cptcovage++;
5809: Tage[cptcovage]=k;
5810: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5811: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5812: cptcovn++;
5813: cptcovprodnoage++;k1++;
5814: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5815: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5816: because this model-covariate is a construction we invent a new column
5817: ncovcol + k1
5818: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5819: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5820: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5821: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5822: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5823: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5824: k2=k2+2;
5825: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5826: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5827: for (i=1; i<=lastobs;i++){
5828: /* Computes the new covariate which is a product of
5829: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5830: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5831: }
5832: } /* End age is not in the model */
5833: } /* End if model includes a product */
5834: else { /* no more sum */
5835: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5836: /* scanf("%d",i);*/
5837: cutl(strd,strc,strb,'V');
5838: ks++; /**< Number of simple covariates */
1.145 brouard 5839: cptcovn++;
1.187 brouard 5840: Tvar[k]=atoi(strd);
5841: }
5842: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5843: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5844: scanf("%d",i);*/
5845: } /* end of loop + on total covariates */
5846: } /* end if strlen(modelsave == 0) age*age might exist */
5847: } /* end if strlen(model == 0) */
1.136 brouard 5848:
5849: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5850: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5851:
5852: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5853: printf("cptcovprod=%d ", cptcovprod);
5854: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5855:
5856: scanf("%d ",i);*/
5857:
5858:
1.137 brouard 5859: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5860: /*endread:*/
1.136 brouard 5861: printf("Exiting decodemodel: ");
5862: return (1);
5863: }
5864:
1.169 brouard 5865: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5866: {
5867: int i, m;
5868:
5869: for (i=1; i<=imx; i++) {
5870: for(m=2; (m<= maxwav); m++) {
5871: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5872: anint[m][i]=9999;
5873: s[m][i]=-1;
5874: }
5875: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5876: *nberr = *nberr + 1;
5877: 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);
5878: 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 5879: s[m][i]=-1;
5880: }
5881: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5882: (*nberr)++;
1.136 brouard 5883: 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]);
5884: 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]);
5885: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5886: }
5887: }
5888: }
5889:
5890: for (i=1; i<=imx; i++) {
5891: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5892: for(m=firstpass; (m<= lastpass); m++){
5893: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5894: if (s[m][i] >= nlstate+1) {
1.169 brouard 5895: if(agedc[i]>0){
5896: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5897: agev[m][i]=agedc[i];
5898: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5899: }else {
1.136 brouard 5900: if ((int)andc[i]!=9999){
5901: nbwarn++;
5902: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5903: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5904: agev[m][i]=-1;
5905: }
5906: }
1.169 brouard 5907: } /* agedc > 0 */
1.136 brouard 5908: }
5909: else if(s[m][i] !=9){ /* Standard case, age in fractional
5910: years but with the precision of a month */
5911: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5912: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5913: agev[m][i]=1;
5914: else if(agev[m][i] < *agemin){
5915: *agemin=agev[m][i];
5916: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5917: }
5918: else if(agev[m][i] >*agemax){
5919: *agemax=agev[m][i];
1.156 brouard 5920: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5921: }
5922: /*agev[m][i]=anint[m][i]-annais[i];*/
5923: /* agev[m][i] = age[i]+2*m;*/
5924: }
5925: else { /* =9 */
5926: agev[m][i]=1;
5927: s[m][i]=-1;
5928: }
5929: }
5930: else /*= 0 Unknown */
5931: agev[m][i]=1;
5932: }
5933:
5934: }
5935: for (i=1; i<=imx; i++) {
5936: for(m=firstpass; (m<=lastpass); m++){
5937: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5938: (*nberr)++;
1.136 brouard 5939: 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);
5940: 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);
5941: return 1;
5942: }
5943: }
5944: }
5945:
5946: /*for (i=1; i<=imx; i++){
5947: for (m=firstpass; (m<lastpass); m++){
5948: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5949: }
5950:
5951: }*/
5952:
5953:
1.139 brouard 5954: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5955: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5956:
5957: return (0);
1.164 brouard 5958: /* endread:*/
1.136 brouard 5959: printf("Exiting calandcheckages: ");
5960: return (1);
5961: }
5962:
1.172 brouard 5963: #if defined(_MSC_VER)
5964: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5965: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5966: //#include "stdafx.h"
5967: //#include <stdio.h>
5968: //#include <tchar.h>
5969: //#include <windows.h>
5970: //#include <iostream>
5971: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5972:
5973: LPFN_ISWOW64PROCESS fnIsWow64Process;
5974:
5975: BOOL IsWow64()
5976: {
5977: BOOL bIsWow64 = FALSE;
5978:
5979: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5980: // (HANDLE, PBOOL);
5981:
5982: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5983:
5984: HMODULE module = GetModuleHandle(_T("kernel32"));
5985: const char funcName[] = "IsWow64Process";
5986: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5987: GetProcAddress(module, funcName);
5988:
5989: if (NULL != fnIsWow64Process)
5990: {
5991: if (!fnIsWow64Process(GetCurrentProcess(),
5992: &bIsWow64))
5993: //throw std::exception("Unknown error");
5994: printf("Unknown error\n");
5995: }
5996: return bIsWow64 != FALSE;
5997: }
5998: #endif
1.177 brouard 5999:
1.191 brouard 6000: void syscompilerinfo(int logged)
1.167 brouard 6001: {
6002: /* #include "syscompilerinfo.h"*/
1.185 brouard 6003: /* command line Intel compiler 32bit windows, XP compatible:*/
6004: /* /GS /W3 /Gy
6005: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6006: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6007: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 6008: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6009: */
6010: /* 64 bits */
1.185 brouard 6011: /*
6012: /GS /W3 /Gy
6013: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6014: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6015: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6016: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6017: /* Optimization are useless and O3 is slower than O2 */
6018: /*
6019: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6020: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6021: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6022: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6023: */
1.186 brouard 6024: /* Link is */ /* /OUT:"visual studio
1.185 brouard 6025: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6026: /PDB:"visual studio
6027: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6028: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6029: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6030: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6031: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6032: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6033: uiAccess='false'"
6034: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6035: /NOLOGO /TLBID:1
6036: */
1.177 brouard 6037: #if defined __INTEL_COMPILER
1.178 brouard 6038: #if defined(__GNUC__)
6039: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6040: #endif
1.177 brouard 6041: #elif defined(__GNUC__)
1.179 brouard 6042: #ifndef __APPLE__
1.174 brouard 6043: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 6044: #endif
1.177 brouard 6045: struct utsname sysInfo;
1.178 brouard 6046: int cross = CROSS;
6047: if (cross){
6048: printf("Cross-");
1.191 brouard 6049: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6050: }
1.174 brouard 6051: #endif
6052:
1.171 brouard 6053: #include <stdint.h>
1.178 brouard 6054:
1.191 brouard 6055: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6056: #if defined(__clang__)
1.191 brouard 6057: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6058: #endif
6059: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6060: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6061: #endif
6062: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6063: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6064: #endif
6065: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6066: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6067: #endif
6068: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6069: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6070: #endif
6071: #if defined(_MSC_VER)
1.191 brouard 6072: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6073: #endif
6074: #if defined(__PGI)
1.191 brouard 6075: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6076: #endif
6077: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6078: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6079: #endif
1.191 brouard 6080: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6081:
1.167 brouard 6082: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6083: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6084: // Windows (x64 and x86)
1.191 brouard 6085: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6086: #elif __unix__ // all unices, not all compilers
6087: // Unix
1.191 brouard 6088: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6089: #elif __linux__
6090: // linux
1.191 brouard 6091: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6092: #elif __APPLE__
1.174 brouard 6093: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6094: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6095: #endif
6096:
6097: /* __MINGW32__ */
6098: /* __CYGWIN__ */
6099: /* __MINGW64__ */
6100: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6101: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6102: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6103: /* _WIN64 // Defined for applications for Win64. */
6104: /* _M_X64 // Defined for compilations that target x64 processors. */
6105: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6106:
1.167 brouard 6107: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6108: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6109: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6110: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6111: #else
1.191 brouard 6112: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6113: #endif
6114:
1.169 brouard 6115: #if defined(__GNUC__)
6116: # if defined(__GNUC_PATCHLEVEL__)
6117: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6118: + __GNUC_MINOR__ * 100 \
6119: + __GNUC_PATCHLEVEL__)
6120: # else
6121: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6122: + __GNUC_MINOR__ * 100)
6123: # endif
1.174 brouard 6124: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6125: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6126:
6127: if (uname(&sysInfo) != -1) {
6128: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6129: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176 brouard 6130: }
6131: else
6132: perror("uname() error");
1.179 brouard 6133: //#ifndef __INTEL_COMPILER
6134: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6135: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6136: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6137: #endif
1.169 brouard 6138: #endif
1.172 brouard 6139:
6140: // void main()
6141: // {
1.169 brouard 6142: #if defined(_MSC_VER)
1.174 brouard 6143: if (IsWow64()){
1.191 brouard 6144: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6145: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6146: }
6147: else{
1.191 brouard 6148: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6149: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6150: }
1.172 brouard 6151: // printf("\nPress Enter to continue...");
6152: // getchar();
6153: // }
6154:
1.169 brouard 6155: #endif
6156:
1.167 brouard 6157:
6158: }
1.136 brouard 6159:
1.180 brouard 6160: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
6161: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6162: int i, j, k, i1 ;
6163: double ftolpl = 1.e-10;
6164: double age, agebase, agelim;
6165:
6166: strcpy(filerespl,"pl");
6167: strcat(filerespl,fileres);
6168: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6169: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6170: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6171: }
6172: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6173: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6174: pstamp(ficrespl);
6175: fprintf(ficrespl,"# Period (stable) prevalence \n");
6176: fprintf(ficrespl,"#Age ");
6177: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6178: fprintf(ficrespl,"\n");
6179:
6180: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6181:
6182: agebase=ageminpar;
6183: agelim=agemaxpar;
6184:
6185: i1=pow(2,cptcoveff);
6186: if (cptcovn < 1){i1=1;}
6187:
6188: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6189: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6190: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6191: k=k+1;
6192: /* to clean */
1.198 brouard 6193: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200 ! brouard 6194: fprintf(ficrespl,"#******");
! 6195: printf("#******");
! 6196: fprintf(ficlog,"#******");
1.180 brouard 6197: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 6198: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6199: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6200: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6201: }
6202: fprintf(ficrespl,"******\n");
6203: printf("******\n");
6204: fprintf(ficlog,"******\n");
6205:
6206: fprintf(ficrespl,"#Age ");
6207: for(j=1;j<=cptcoveff;j++) {
1.200 ! brouard 6208: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6209: }
6210: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6211: fprintf(ficrespl,"\n");
6212:
6213: for (age=agebase; age<=agelim; age++){
6214: /* for (age=agebase; age<=agebase; age++){ */
6215: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6216: fprintf(ficrespl,"%.0f ",age );
6217: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6218: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6219: for(i=1; i<=nlstate;i++)
6220: fprintf(ficrespl," %.5f", prlim[i][i]);
6221: fprintf(ficrespl,"\n");
6222: } /* Age */
6223: /* was end of cptcod */
6224: } /* cptcov */
1.184 brouard 6225: return 0;
1.180 brouard 6226: }
6227:
6228: int hPijx(double *p, int bage, int fage){
6229: /*------------- h Pij x at various ages ------------*/
6230:
6231: int stepsize;
6232: int agelim;
6233: int hstepm;
6234: int nhstepm;
6235: int h, i, i1, j, k;
6236:
6237: double agedeb;
6238: double ***p3mat;
6239:
6240: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
6241: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6242: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6243: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6244: }
6245: printf("Computing pij: result on file '%s' \n", filerespij);
6246: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6247:
6248: stepsize=(int) (stepm+YEARM-1)/YEARM;
6249: /*if (stepm<=24) stepsize=2;*/
6250:
6251: agelim=AGESUP;
6252: hstepm=stepsize*YEARM; /* Every year of age */
6253: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6254:
6255: /* hstepm=1; aff par mois*/
6256: pstamp(ficrespij);
6257: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6258: i1= pow(2,cptcoveff);
1.183 brouard 6259: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6260: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6261: /* k=k+1; */
6262: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6263: fprintf(ficrespij,"\n#****** ");
6264: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6265: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183 brouard 6266: fprintf(ficrespij,"******\n");
6267:
6268: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6269: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6270: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6271:
6272: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6273:
1.183 brouard 6274: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6275: oldm=oldms;savm=savms;
6276: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6277: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6278: for(i=1; i<=nlstate;i++)
6279: for(j=1; j<=nlstate+ndeath;j++)
6280: fprintf(ficrespij," %1d-%1d",i,j);
6281: fprintf(ficrespij,"\n");
6282: for (h=0; h<=nhstepm; h++){
6283: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6284: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6285: for(i=1; i<=nlstate;i++)
6286: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6287: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6288: fprintf(ficrespij,"\n");
6289: }
1.183 brouard 6290: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6291: fprintf(ficrespij,"\n");
6292: }
1.180 brouard 6293: /*}*/
6294: }
1.184 brouard 6295: return 0;
1.180 brouard 6296: }
6297:
6298:
1.136 brouard 6299: /***********************************************/
6300: /**************** Main Program *****************/
6301: /***********************************************/
6302:
6303: int main(int argc, char *argv[])
6304: {
6305: #ifdef GSL
6306: const gsl_multimin_fminimizer_type *T;
6307: size_t iteri = 0, it;
6308: int rval = GSL_CONTINUE;
6309: int status = GSL_SUCCESS;
6310: double ssval;
6311: #endif
6312: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6313: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6314:
6315: int jj, ll, li, lj, lk;
1.136 brouard 6316: int numlinepar=0; /* Current linenumber of parameter file */
1.197 brouard 6317: int num_filled;
1.136 brouard 6318: int itimes;
6319: int NDIM=2;
6320: int vpopbased=0;
6321:
1.164 brouard 6322: char ca[32], cb[32];
1.136 brouard 6323: /* FILE *fichtm; *//* Html File */
6324: /* FILE *ficgp;*/ /*Gnuplot File */
6325: struct stat info;
1.191 brouard 6326: double agedeb=0.;
1.194 brouard 6327:
6328: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6329:
1.165 brouard 6330: double fret;
1.191 brouard 6331: double dum=0.; /* Dummy variable */
1.136 brouard 6332: double ***p3mat;
6333: double ***mobaverage;
1.164 brouard 6334:
6335: char line[MAXLINE];
1.197 brouard 6336: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6337:
6338: char model[MAXLINE], modeltemp[MAXLINE];
1.136 brouard 6339: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6340: char *tok, *val; /* pathtot */
1.136 brouard 6341: int firstobs=1, lastobs=10;
1.195 brouard 6342: int c, h , cpt, c2;
1.191 brouard 6343: int jl=0;
6344: int i1, j1, jk, stepsize=0;
1.194 brouard 6345: int count=0;
6346:
1.164 brouard 6347: int *tab;
1.136 brouard 6348: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6349: int mobilav=0,popforecast=0;
1.191 brouard 6350: int hstepm=0, nhstepm=0;
1.136 brouard 6351: int agemortsup;
6352: float sumlpop=0.;
6353: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6354: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6355:
1.191 brouard 6356: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6357: double ftolpl=FTOL;
6358: double **prlim;
6359: double ***param; /* Matrix of parameters */
6360: double *p;
6361: double **matcov; /* Matrix of covariance */
6362: double ***delti3; /* Scale */
6363: double *delti; /* Scale */
6364: double ***eij, ***vareij;
6365: double **varpl; /* Variances of prevalence limits by age */
6366: double *epj, vepp;
1.164 brouard 6367:
1.136 brouard 6368: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6369: double **ximort;
1.145 brouard 6370: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6371: int *dcwave;
6372:
1.164 brouard 6373: char z[1]="c";
1.136 brouard 6374:
6375: /*char *strt;*/
6376: char strtend[80];
1.126 brouard 6377:
1.164 brouard 6378:
1.126 brouard 6379: /* setlocale (LC_ALL, ""); */
6380: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6381: /* textdomain (PACKAGE); */
6382: /* setlocale (LC_CTYPE, ""); */
6383: /* setlocale (LC_MESSAGES, ""); */
6384:
6385: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6386: rstart_time = time(NULL);
6387: /* (void) gettimeofday(&start_time,&tzp);*/
6388: start_time = *localtime(&rstart_time);
1.126 brouard 6389: curr_time=start_time;
1.157 brouard 6390: /*tml = *localtime(&start_time.tm_sec);*/
6391: /* strcpy(strstart,asctime(&tml)); */
6392: strcpy(strstart,asctime(&start_time));
1.126 brouard 6393:
6394: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6395: /* tp.tm_sec = tp.tm_sec +86400; */
6396: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6397: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6398: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6399: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6400: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6401: /* strt=asctime(&tmg); */
6402: /* printf("Time(after) =%s",strstart); */
6403: /* (void) time (&time_value);
6404: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6405: * tm = *localtime(&time_value);
6406: * strstart=asctime(&tm);
6407: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6408: */
6409:
6410: nberr=0; /* Number of errors and warnings */
6411: nbwarn=0;
1.184 brouard 6412: #ifdef WIN32
6413: _getcwd(pathcd, size);
6414: #else
1.126 brouard 6415: getcwd(pathcd, size);
1.184 brouard 6416: #endif
1.191 brouard 6417: syscompilerinfo(0);
1.196 brouard 6418: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126 brouard 6419: if(argc <=1){
6420: printf("\nEnter the parameter file name: ");
6421: fgets(pathr,FILENAMELENGTH,stdin);
6422: i=strlen(pathr);
6423: if(pathr[i-1]=='\n')
6424: pathr[i-1]='\0';
1.156 brouard 6425: i=strlen(pathr);
6426: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
6427: pathr[i-1]='\0';
1.126 brouard 6428: for (tok = pathr; tok != NULL; ){
6429: printf("Pathr |%s|\n",pathr);
6430: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6431: printf("val= |%s| pathr=%s\n",val,pathr);
6432: strcpy (pathtot, val);
6433: if(pathr[0] == '\0') break; /* Dirty */
6434: }
6435: }
6436: else{
6437: strcpy(pathtot,argv[1]);
6438: }
6439: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6440: /*cygwin_split_path(pathtot,path,optionfile);
6441: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6442: /* cutv(path,optionfile,pathtot,'\\');*/
6443:
6444: /* Split argv[0], imach program to get pathimach */
6445: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6446: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6447: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6448: /* strcpy(pathimach,argv[0]); */
6449: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6450: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6451: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 6452: #ifdef WIN32
6453: _chdir(path); /* Can be a relative path */
6454: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6455: #else
1.126 brouard 6456: chdir(path); /* Can be a relative path */
1.184 brouard 6457: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6458: #endif
6459: printf("Current directory %s!\n",pathcd);
1.126 brouard 6460: strcpy(command,"mkdir ");
6461: strcat(command,optionfilefiname);
6462: if((outcmd=system(command)) != 0){
1.169 brouard 6463: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 6464: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6465: /* fclose(ficlog); */
6466: /* exit(1); */
6467: }
6468: /* if((imk=mkdir(optionfilefiname))<0){ */
6469: /* perror("mkdir"); */
6470: /* } */
6471:
6472: /*-------- arguments in the command line --------*/
6473:
1.186 brouard 6474: /* Main Log file */
1.126 brouard 6475: strcat(filelog, optionfilefiname);
6476: strcat(filelog,".log"); /* */
6477: if((ficlog=fopen(filelog,"w"))==NULL) {
6478: printf("Problem with logfile %s\n",filelog);
6479: goto end;
6480: }
6481: fprintf(ficlog,"Log filename:%s\n",filelog);
1.197 brouard 6482: fprintf(ficlog,"Version %s %s",version,fullversion);
1.126 brouard 6483: fprintf(ficlog,"\nEnter the parameter file name: \n");
6484: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6485: path=%s \n\
6486: optionfile=%s\n\
6487: optionfilext=%s\n\
1.156 brouard 6488: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 6489:
1.197 brouard 6490: syscompilerinfo(1);
1.167 brouard 6491:
1.126 brouard 6492: printf("Local time (at start):%s",strstart);
6493: fprintf(ficlog,"Local time (at start): %s",strstart);
6494: fflush(ficlog);
6495: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 6496: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 6497:
6498: /* */
6499: strcpy(fileres,"r");
6500: strcat(fileres, optionfilefiname);
6501: strcat(fileres,".txt"); /* Other files have txt extension */
6502:
1.186 brouard 6503: /* Main ---------arguments file --------*/
1.126 brouard 6504:
6505: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 6506: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6507: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 6508: fflush(ficlog);
1.149 brouard 6509: /* goto end; */
6510: exit(70);
1.126 brouard 6511: }
6512:
6513:
6514:
6515: strcpy(filereso,"o");
6516: strcat(filereso,fileres);
6517: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6518: printf("Problem with Output resultfile: %s\n", filereso);
6519: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6520: fflush(ficlog);
6521: goto end;
6522: }
6523:
6524: /* Reads comments: lines beginning with '#' */
6525: numlinepar=0;
1.197 brouard 6526:
6527: /* First parameter line */
6528: while(fgets(line, MAXLINE, ficpar)) {
6529: /* If line starts with a # it is a comment */
6530: if (line[0] == '#') {
6531: numlinepar++;
6532: fputs(line,stdout);
6533: fputs(line,ficparo);
6534: fputs(line,ficlog);
6535: continue;
6536: }else
6537: break;
6538: }
6539: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6540: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6541: if (num_filled != 5) {
6542: printf("Should be 5 parameters\n");
6543: }
1.126 brouard 6544: numlinepar++;
1.197 brouard 6545: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6546: }
6547: /* Second parameter line */
6548: while(fgets(line, MAXLINE, ficpar)) {
6549: /* If line starts with a # it is a comment */
6550: if (line[0] == '#') {
6551: numlinepar++;
6552: fputs(line,stdout);
6553: fputs(line,ficparo);
6554: fputs(line,ficlog);
6555: continue;
6556: }else
6557: break;
6558: }
6559: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6560: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
6561: if (num_filled != 8) {
6562: printf("Not 8\n");
6563: }
6564: printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
1.126 brouard 6565: }
6566:
1.197 brouard 6567: /* Third parameter line */
6568: while(fgets(line, MAXLINE, ficpar)) {
6569: /* If line starts with a # it is a comment */
6570: if (line[0] == '#') {
6571: numlinepar++;
6572: fputs(line,stdout);
6573: fputs(line,ficparo);
6574: fputs(line,ficlog);
6575: continue;
6576: }else
6577: break;
6578: }
6579: if((num_filled=sscanf(line,"model=1+age%[^.\n]\n", model)) !=EOF){
6580: if (num_filled != 1) {
6581: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6582: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
6583: model[0]='\0';
6584: goto end;
6585: }
6586: else{
6587: if (model[0]=='+'){
6588: for(i=1; i<=strlen(model);i++)
6589: modeltemp[i-1]=model[i];
6590: }
6591: strcpy(model,modeltemp);
6592: }
1.199 brouard 6593: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.197 brouard 6594: }
6595: /* 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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
6596: /* numlinepar=numlinepar+3; /\* In general *\/ */
6597: /* 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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
1.187 brouard 6598: if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
6599: model[strlen(model)-1]='\0';
1.197 brouard 6600: 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=1+age%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
6601: 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=1+age%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
1.126 brouard 6602: fflush(ficlog);
1.190 brouard 6603: /* if(model[0]=='#'|| model[0]== '\0'){ */
6604: if(model[0]=='#'){
1.187 brouard 6605: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
6606: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
6607: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
6608: if(mle != -1){
6609: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
6610: exit(1);
6611: }
6612: }
1.126 brouard 6613: while((c=getc(ficpar))=='#' && c!= EOF){
6614: ungetc(c,ficpar);
6615: fgets(line, MAXLINE, ficpar);
6616: numlinepar++;
1.195 brouard 6617: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
6618: z[0]=line[1];
6619: }
6620: /* printf("****line [1] = %c \n",line[1]); */
1.141 brouard 6621: fputs(line, stdout);
6622: //puts(line);
1.126 brouard 6623: fputs(line,ficparo);
6624: fputs(line,ficlog);
6625: }
6626: ungetc(c,ficpar);
6627:
6628:
1.145 brouard 6629: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 6630: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6631: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6632: v1+v2*age+v2*v3 makes cptcovn = 3
6633: */
6634: if (strlen(model)>1)
1.187 brouard 6635: 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,age*age makes 3*/
1.145 brouard 6636: else
1.187 brouard 6637: ncovmodel=2; /* Constant and age */
1.133 brouard 6638: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6639: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 6640: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6641: 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);
6642: 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);
6643: fflush(stdout);
6644: fclose (ficlog);
6645: goto end;
6646: }
1.126 brouard 6647: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6648: delti=delti3[1][1];
6649: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6650: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6651: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 6652: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6653: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6654: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6655: fclose (ficparo);
6656: fclose (ficlog);
6657: goto end;
6658: exit(0);
6659: }
1.186 brouard 6660: else if(mle==-3) { /* Main Wizard */
1.126 brouard 6661: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 6662: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6663: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 6664: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6665: matcov=matrix(1,npar,1,npar);
6666: }
6667: else{
1.145 brouard 6668: /* Read guessed parameters */
1.126 brouard 6669: /* Reads comments: lines beginning with '#' */
6670: while((c=getc(ficpar))=='#' && c!= EOF){
6671: ungetc(c,ficpar);
6672: fgets(line, MAXLINE, ficpar);
6673: numlinepar++;
1.141 brouard 6674: fputs(line,stdout);
1.126 brouard 6675: fputs(line,ficparo);
6676: fputs(line,ficlog);
6677: }
6678: ungetc(c,ficpar);
6679:
6680: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6681: for(i=1; i <=nlstate; i++){
6682: j=0;
6683: for(jj=1; jj <=nlstate+ndeath; jj++){
6684: if(jj==i) continue;
6685: j++;
6686: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 6687: if ((i1 != i) || (j1 != jj)){
1.126 brouard 6688: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6689: It might be a problem of design; if ncovcol and the model are correct\n \
6690: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6691: exit(1);
6692: }
6693: fprintf(ficparo,"%1d%1d",i1,j1);
6694: if(mle==1)
1.193 brouard 6695: printf("%1d%1d",i,jj);
6696: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 6697: for(k=1; k<=ncovmodel;k++){
6698: fscanf(ficpar," %lf",¶m[i][j][k]);
6699: if(mle==1){
6700: printf(" %lf",param[i][j][k]);
6701: fprintf(ficlog," %lf",param[i][j][k]);
6702: }
6703: else
6704: fprintf(ficlog," %lf",param[i][j][k]);
6705: fprintf(ficparo," %lf",param[i][j][k]);
6706: }
6707: fscanf(ficpar,"\n");
6708: numlinepar++;
6709: if(mle==1)
6710: printf("\n");
6711: fprintf(ficlog,"\n");
6712: fprintf(ficparo,"\n");
6713: }
6714: }
6715: fflush(ficlog);
6716:
1.145 brouard 6717: /* Reads scales values */
1.126 brouard 6718: p=param[1][1];
6719:
6720: /* Reads comments: lines beginning with '#' */
6721: while((c=getc(ficpar))=='#' && c!= EOF){
6722: ungetc(c,ficpar);
6723: fgets(line, MAXLINE, ficpar);
6724: numlinepar++;
1.141 brouard 6725: fputs(line,stdout);
1.126 brouard 6726: fputs(line,ficparo);
6727: fputs(line,ficlog);
6728: }
6729: ungetc(c,ficpar);
6730:
6731: for(i=1; i <=nlstate; i++){
6732: for(j=1; j <=nlstate+ndeath-1; j++){
6733: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 6734: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 6735: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6736: exit(1);
6737: }
6738: printf("%1d%1d",i,j);
6739: fprintf(ficparo,"%1d%1d",i1,j1);
6740: fprintf(ficlog,"%1d%1d",i1,j1);
6741: for(k=1; k<=ncovmodel;k++){
6742: fscanf(ficpar,"%le",&delti3[i][j][k]);
6743: printf(" %le",delti3[i][j][k]);
6744: fprintf(ficparo," %le",delti3[i][j][k]);
6745: fprintf(ficlog," %le",delti3[i][j][k]);
6746: }
6747: fscanf(ficpar,"\n");
6748: numlinepar++;
6749: printf("\n");
6750: fprintf(ficparo,"\n");
6751: fprintf(ficlog,"\n");
6752: }
6753: }
6754: fflush(ficlog);
6755:
1.145 brouard 6756: /* Reads covariance matrix */
1.126 brouard 6757: delti=delti3[1][1];
6758:
6759:
6760: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6761:
6762: /* Reads comments: lines beginning with '#' */
6763: while((c=getc(ficpar))=='#' && c!= EOF){
6764: ungetc(c,ficpar);
6765: fgets(line, MAXLINE, ficpar);
6766: numlinepar++;
1.141 brouard 6767: fputs(line,stdout);
1.126 brouard 6768: fputs(line,ficparo);
6769: fputs(line,ficlog);
6770: }
6771: ungetc(c,ficpar);
6772:
6773: matcov=matrix(1,npar,1,npar);
1.131 brouard 6774: for(i=1; i <=npar; i++)
6775: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6776:
1.194 brouard 6777: /* Scans npar lines */
1.126 brouard 6778: for(i=1; i <=npar; i++){
1.194 brouard 6779: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
6780: if(count != 3){
6781: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
6782: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
6783: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
6784: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
6785: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
6786: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
6787: exit(1);
6788: }else
1.126 brouard 6789: if(mle==1)
1.194 brouard 6790: printf("%1d%1d%1d",i1,j1,jk);
6791: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
6792: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 6793: for(j=1; j <=i; j++){
6794: fscanf(ficpar," %le",&matcov[i][j]);
6795: if(mle==1){
6796: printf(" %.5le",matcov[i][j]);
6797: }
6798: fprintf(ficlog," %.5le",matcov[i][j]);
6799: fprintf(ficparo," %.5le",matcov[i][j]);
6800: }
6801: fscanf(ficpar,"\n");
6802: numlinepar++;
6803: if(mle==1)
6804: printf("\n");
6805: fprintf(ficlog,"\n");
6806: fprintf(ficparo,"\n");
6807: }
1.194 brouard 6808: /* End of read covariance matrix npar lines */
1.126 brouard 6809: for(i=1; i <=npar; i++)
6810: for(j=i+1;j<=npar;j++)
6811: matcov[i][j]=matcov[j][i];
6812:
6813: if(mle==1)
6814: printf("\n");
6815: fprintf(ficlog,"\n");
6816:
6817: fflush(ficlog);
6818:
6819: /*-------- Rewriting parameter file ----------*/
6820: strcpy(rfileres,"r"); /* "Rparameterfile */
6821: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6822: strcat(rfileres,"."); /* */
6823: strcat(rfileres,optionfilext); /* Other files have txt extension */
6824: if((ficres =fopen(rfileres,"w"))==NULL) {
6825: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6826: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6827: }
6828: fprintf(ficres,"#%s\n",version);
6829: } /* End of mle != -3 */
6830:
1.186 brouard 6831: /* Main data
6832: */
1.126 brouard 6833: n= lastobs;
6834: num=lvector(1,n);
6835: moisnais=vector(1,n);
6836: annais=vector(1,n);
6837: moisdc=vector(1,n);
6838: andc=vector(1,n);
6839: agedc=vector(1,n);
6840: cod=ivector(1,n);
6841: weight=vector(1,n);
6842: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6843: mint=matrix(1,maxwav,1,n);
6844: anint=matrix(1,maxwav,1,n);
1.131 brouard 6845: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6846: tab=ivector(1,NCOVMAX);
1.144 brouard 6847: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 6848: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6849:
1.136 brouard 6850: /* Reads data from file datafile */
6851: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6852: goto end;
6853:
6854: /* Calculation of the number of parameters from char model */
1.137 brouard 6855: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6856: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6857: k=3 V4 Tvar[k=3]= 4 (from V4)
6858: k=2 V1 Tvar[k=2]= 1 (from V1)
6859: k=1 Tvar[1]=2 (from V2)
6860: */
6861: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6862: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6863: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6864: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6865: */
6866: /* For model-covariate k tells which data-covariate to use but
6867: because this model-covariate is a construction we invent a new column
6868: ncovcol + k1
6869: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6870: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6871: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6872: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6873: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6874: */
1.145 brouard 6875: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6876: 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 6877: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6878: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6879: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6880: 4 covariates (3 plus signs)
6881: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6882: */
1.136 brouard 6883:
1.186 brouard 6884: /* Main decodemodel */
6885:
1.187 brouard 6886:
1.136 brouard 6887: if(decodemodel(model, lastobs) == 1)
6888: goto end;
6889:
1.137 brouard 6890: if((double)(lastobs-imx)/(double)imx > 1.10){
6891: nbwarn++;
6892: 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);
6893: 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);
6894: }
1.136 brouard 6895: /* if(mle==1){*/
1.137 brouard 6896: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6897: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6898: }
6899:
6900: /*-calculation of age at interview from date of interview and age at death -*/
6901: agev=matrix(1,maxwav,1,imx);
6902:
6903: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6904: goto end;
6905:
1.126 brouard 6906:
1.136 brouard 6907: agegomp=(int)agemin;
6908: free_vector(moisnais,1,n);
6909: free_vector(annais,1,n);
1.126 brouard 6910: /* free_matrix(mint,1,maxwav,1,n);
6911: free_matrix(anint,1,maxwav,1,n);*/
6912: free_vector(moisdc,1,n);
6913: free_vector(andc,1,n);
1.145 brouard 6914: /* */
6915:
1.126 brouard 6916: wav=ivector(1,imx);
6917: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6918: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6919: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6920:
6921: /* Concatenates waves */
6922: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6923: /* */
6924:
1.126 brouard 6925: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6926:
6927: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6928: ncodemax[1]=1;
1.145 brouard 6929: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 6930: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 6931: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186 brouard 6932: /* Nbcode gives the value of the lth modality of jth covariate, in
6933: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
6934: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145 brouard 6935:
1.200 ! brouard 6936: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198 brouard 6937: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186 brouard 6938: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145 brouard 6939: h=0;
6940:
6941:
6942: /*if (cptcovn > 0) */
1.126 brouard 6943:
1.145 brouard 6944:
1.126 brouard 6945: m=pow(2,cptcoveff);
6946:
1.144 brouard 6947: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186 brouard 6948: * For k=4 covariates, h goes from 1 to 2**k
6949: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
6950: * h\k 1 2 3 4
1.143 brouard 6951: *______________________________
6952: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6953: * 2 2 1 1 1
6954: * 3 i=2 1 2 1 1
6955: * 4 2 2 1 1
6956: * 5 i=3 1 i=2 1 2 1
6957: * 6 2 1 2 1
6958: * 7 i=4 1 2 2 1
6959: * 8 2 2 2 1
1.197 brouard 6960: * 9 i=5 1 i=3 1 i=2 1 2
6961: * 10 2 1 1 2
6962: * 11 i=6 1 2 1 2
6963: * 12 2 2 1 2
6964: * 13 i=7 1 i=4 1 2 2
6965: * 14 2 1 2 2
6966: * 15 i=8 1 2 2 2
6967: * 16 2 2 2 2
1.143 brouard 6968: */
1.197 brouard 6969: for(h=1; h <=100 ;h++){
6970: /* printf("h=%2d ", h); */
1.200 ! brouard 6971: /* for(k=1; k <=10; k++){ */
1.197 brouard 6972: /* printf("k=%d %d ",k,codtabm(h,k)); */
1.200 ! brouard 6973: /* codtab[h][k]=codtabm(h,k); */
! 6974: /* } */
1.197 brouard 6975: /* printf("\n"); */
6976: }
6977: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
6978: /* 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 *\/ */
6979: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
6980: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
6981: /* h++; */
6982: /* if (h>m) */
6983: /* h=1; */
6984: /* codtab[h][k]=j; */
6985: /* /\* codtab[12][3]=1; *\/ */
6986: /* /\*codtab[h][Tvar[k]]=j;*\/ */
6987: /* /\* 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]]); *\/ */
6988: /* } */
6989: /* } */
6990: /* } */
6991: /* } */
1.126 brouard 6992: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6993: codtab[1][2]=1;codtab[2][2]=2; */
1.197 brouard 6994: /* for(i=1; i <=m ;i++){ */
6995: /* for(k=1; k <=cptcovn; k++){ */
6996: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
6997: /* } */
6998: /* printf("\n"); */
6999: /* } */
7000: /* scanf("%d",i);*/
1.145 brouard 7001:
7002: free_ivector(Ndum,-1,NCOVMAX);
7003:
7004:
1.126 brouard 7005:
1.186 brouard 7006: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 7007: strcpy(optionfilegnuplot,optionfilefiname);
7008: if(mle==-3)
7009: strcat(optionfilegnuplot,"-mort");
7010: strcat(optionfilegnuplot,".gp");
7011:
7012: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7013: printf("Problem with file %s",optionfilegnuplot);
7014: }
7015: else{
7016: fprintf(ficgp,"\n# %s\n", version);
7017: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 7018: //fprintf(ficgp,"set missing 'NaNq'\n");
7019: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 7020: }
7021: /* fclose(ficgp);*/
1.186 brouard 7022:
7023:
7024: /* Initialisation of --------- index.htm --------*/
1.126 brouard 7025:
7026: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7027: if(mle==-3)
7028: strcat(optionfilehtm,"-mort");
7029: strcat(optionfilehtm,".htm");
7030: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 7031: printf("Problem with %s \n",optionfilehtm);
7032: exit(0);
1.126 brouard 7033: }
7034:
7035: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7036: strcat(optionfilehtmcov,"-cov.htm");
7037: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7038: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7039: }
7040: else{
7041: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7042: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7043: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
7044: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7045: }
7046:
7047: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7048: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7049: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
7050: \n\
7051: <hr size=\"2\" color=\"#EC5E5E\">\
7052: <ul><li><h4>Parameter files</h4>\n\
7053: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7054: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7055: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7056: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7057: - Date and time at start: %s</ul>\n",\
7058: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7059: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7060: fileres,fileres,\
7061: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7062: fflush(fichtm);
7063:
7064: strcpy(pathr,path);
7065: strcat(pathr,optionfilefiname);
1.184 brouard 7066: #ifdef WIN32
7067: _chdir(optionfilefiname); /* Move to directory named optionfile */
7068: #else
1.126 brouard 7069: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 7070: #endif
7071:
1.126 brouard 7072:
7073: /* Calculates basic frequencies. Computes observed prevalence at single age
7074: and prints on file fileres'p'. */
7075: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7076:
7077: fprintf(fichtm,"\n");
7078: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7079: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7080: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7081: imx,agemin,agemax,jmin,jmax,jmean);
7082: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7083: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7084: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7085: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7086: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7087:
7088:
7089: /* For Powell, parameters are in a vector p[] starting at p[1]
7090: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7091: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7092:
7093: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 7094: /* For mortality only */
1.126 brouard 7095: if (mle==-3){
1.136 brouard 7096: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 7097: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 7098: cens=ivector(1,n);
7099: ageexmed=vector(1,n);
7100: agecens=vector(1,n);
7101: dcwave=ivector(1,n);
7102:
7103: for (i=1; i<=imx; i++){
7104: dcwave[i]=-1;
7105: for (m=firstpass; m<=lastpass; m++)
7106: if (s[m][i]>nlstate) {
7107: dcwave[i]=m;
7108: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7109: break;
7110: }
7111: }
7112:
7113: for (i=1; i<=imx; i++) {
7114: if (wav[i]>0){
7115: ageexmed[i]=agev[mw[1][i]][i];
7116: j=wav[i];
7117: agecens[i]=1.;
7118:
7119: if (ageexmed[i]> 1 && wav[i] > 0){
7120: agecens[i]=agev[mw[j][i]][i];
7121: cens[i]= 1;
7122: }else if (ageexmed[i]< 1)
7123: cens[i]= -1;
7124: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7125: cens[i]=0 ;
7126: }
7127: else cens[i]=-1;
7128: }
7129:
7130: for (i=1;i<=NDIM;i++) {
7131: for (j=1;j<=NDIM;j++)
7132: ximort[i][j]=(i == j ? 1.0 : 0.0);
7133: }
7134:
1.145 brouard 7135: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7136: /*printf("%lf %lf", p[1], p[2]);*/
7137:
7138:
1.136 brouard 7139: #ifdef GSL
7140: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7141: #else
1.126 brouard 7142: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7143: #endif
1.126 brouard 7144: strcpy(filerespow,"pow-mort");
7145: strcat(filerespow,fileres);
7146: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7147: printf("Problem with resultfile: %s\n", filerespow);
7148: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7149: }
1.136 brouard 7150: #ifdef GSL
7151: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7152: #else
1.126 brouard 7153: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7154: #endif
1.126 brouard 7155: /* for (i=1;i<=nlstate;i++)
7156: for(j=1;j<=nlstate+ndeath;j++)
7157: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7158: */
7159: fprintf(ficrespow,"\n");
1.136 brouard 7160: #ifdef GSL
7161: /* gsl starts here */
7162: T = gsl_multimin_fminimizer_nmsimplex;
7163: gsl_multimin_fminimizer *sfm = NULL;
7164: gsl_vector *ss, *x;
7165: gsl_multimin_function minex_func;
7166:
7167: /* Initial vertex size vector */
7168: ss = gsl_vector_alloc (NDIM);
7169:
7170: if (ss == NULL){
7171: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7172: }
7173: /* Set all step sizes to 1 */
7174: gsl_vector_set_all (ss, 0.001);
7175:
7176: /* Starting point */
1.126 brouard 7177:
1.136 brouard 7178: x = gsl_vector_alloc (NDIM);
7179:
7180: if (x == NULL){
7181: gsl_vector_free(ss);
7182: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7183: }
7184:
7185: /* Initialize method and iterate */
7186: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7187: /* gsl_vector_set(x, 0, 0.0268); */
7188: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7189: gsl_vector_set(x, 0, p[1]);
7190: gsl_vector_set(x, 1, p[2]);
7191:
7192: minex_func.f = &gompertz_f;
7193: minex_func.n = NDIM;
7194: minex_func.params = (void *)&p; /* ??? */
7195:
7196: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7197: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7198:
7199: printf("Iterations beginning .....\n\n");
7200: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7201:
7202: iteri=0;
7203: while (rval == GSL_CONTINUE){
7204: iteri++;
7205: status = gsl_multimin_fminimizer_iterate(sfm);
7206:
7207: if (status) printf("error: %s\n", gsl_strerror (status));
7208: fflush(0);
7209:
7210: if (status)
7211: break;
7212:
7213: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7214: ssval = gsl_multimin_fminimizer_size (sfm);
7215:
7216: if (rval == GSL_SUCCESS)
7217: printf ("converged to a local maximum at\n");
7218:
7219: printf("%5d ", iteri);
7220: for (it = 0; it < NDIM; it++){
7221: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7222: }
7223: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7224: }
7225:
7226: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7227:
7228: gsl_vector_free(x); /* initial values */
7229: gsl_vector_free(ss); /* inital step size */
7230: for (it=0; it<NDIM; it++){
7231: p[it+1]=gsl_vector_get(sfm->x,it);
7232: fprintf(ficrespow," %.12lf", p[it]);
7233: }
7234: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7235: #endif
7236: #ifdef POWELL
7237: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7238: #endif
1.126 brouard 7239: fclose(ficrespow);
7240:
7241: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
7242:
7243: for(i=1; i <=NDIM; i++)
7244: for(j=i+1;j<=NDIM;j++)
7245: matcov[i][j]=matcov[j][i];
7246:
7247: printf("\nCovariance matrix\n ");
7248: for(i=1; i <=NDIM; i++) {
7249: for(j=1;j<=NDIM;j++){
7250: printf("%f ",matcov[i][j]);
7251: }
7252: printf("\n ");
7253: }
7254:
7255: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7256: for (i=1;i<=NDIM;i++) {
1.126 brouard 7257: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7258: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7259: }
1.126 brouard 7260: lsurv=vector(1,AGESUP);
7261: lpop=vector(1,AGESUP);
7262: tpop=vector(1,AGESUP);
7263: lsurv[agegomp]=100000;
7264:
7265: for (k=agegomp;k<=AGESUP;k++) {
7266: agemortsup=k;
7267: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7268: }
7269:
7270: for (k=agegomp;k<agemortsup;k++)
7271: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7272:
7273: for (k=agegomp;k<agemortsup;k++){
7274: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7275: sumlpop=sumlpop+lpop[k];
7276: }
7277:
7278: tpop[agegomp]=sumlpop;
7279: for (k=agegomp;k<(agemortsup-3);k++){
7280: /* tpop[k+1]=2;*/
7281: tpop[k+1]=tpop[k]-lpop[k];
7282: }
7283:
7284:
7285: printf("\nAge lx qx dx Lx Tx e(x)\n");
7286: for (k=agegomp;k<(agemortsup-2);k++)
7287: 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]);
7288:
7289:
7290: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7291: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7292: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7293: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7294: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7295: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7296: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7297: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7298: }else
7299: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7300: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
7301: stepm, weightopt,\
7302: model,imx,p,matcov,agemortsup);
7303:
7304: free_vector(lsurv,1,AGESUP);
7305: free_vector(lpop,1,AGESUP);
7306: free_vector(tpop,1,AGESUP);
1.136 brouard 7307: #ifdef GSL
7308: free_ivector(cens,1,n);
7309: free_vector(agecens,1,n);
7310: free_ivector(dcwave,1,n);
7311: free_matrix(ximort,1,NDIM,1,NDIM);
7312: #endif
1.186 brouard 7313: } /* Endof if mle==-3 mortality only */
7314: /* Standard maximisation */
1.126 brouard 7315: else{ /* For mle >=1 */
1.132 brouard 7316: globpr=0;/* debug */
1.186 brouard 7317: /* Computes likelihood for initial parameters */
1.132 brouard 7318: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7319: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7320: for (k=1; k<=npar;k++)
7321: printf(" %d %8.5f",k,p[k]);
7322: printf("\n");
1.186 brouard 7323: globpr=1; /* again, to print the contributions */
1.126 brouard 7324: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7325: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7326: for (k=1; k<=npar;k++)
7327: printf(" %d %8.5f",k,p[k]);
7328: printf("\n");
1.186 brouard 7329: if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126 brouard 7330: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7331: }
7332:
7333: /*--------- results files --------------*/
1.192 brouard 7334: 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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
1.126 brouard 7335:
7336:
7337: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7338: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7339: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7340: for(i=1,jk=1; i <=nlstate; i++){
7341: for(k=1; k <=(nlstate+ndeath); k++){
7342: if (k != i) {
7343: printf("%d%d ",i,k);
7344: fprintf(ficlog,"%d%d ",i,k);
7345: fprintf(ficres,"%1d%1d ",i,k);
7346: for(j=1; j <=ncovmodel; j++){
1.190 brouard 7347: printf("%12.7f ",p[jk]);
7348: fprintf(ficlog,"%12.7f ",p[jk]);
7349: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 7350: jk++;
7351: }
7352: printf("\n");
7353: fprintf(ficlog,"\n");
7354: fprintf(ficres,"\n");
7355: }
7356: }
7357: }
7358: if(mle!=0){
7359: /* Computing hessian and covariance matrix */
7360: ftolhess=ftol; /* Usually correct */
7361: hesscov(matcov, p, npar, delti, ftolhess, func);
7362: }
1.197 brouard 7363: printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
7364: fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
1.193 brouard 7365: for(i=1,jk=1; i <=nlstate; i++){
7366: for(k=1; k <=(nlstate+ndeath); k++){
7367: if (k != i) {
7368: printf("%d%d ",i,k);
7369: fprintf(ficlog,"%d%d ",i,k);
7370: for(j=1; j <=ncovmodel; j++){
1.197 brouard 7371: printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
7372: fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.193 brouard 7373: jk++;
7374: }
7375: printf("\n");
7376: fprintf(ficlog,"\n");
7377: }
7378: }
7379: }
7380:
1.126 brouard 7381: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7382: printf("# Scales (for hessian or gradient estimation)\n");
7383: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7384: for(i=1,jk=1; i <=nlstate; i++){
7385: for(j=1; j <=nlstate+ndeath; j++){
7386: if (j!=i) {
7387: fprintf(ficres,"%1d%1d",i,j);
7388: printf("%1d%1d",i,j);
7389: fprintf(ficlog,"%1d%1d",i,j);
7390: for(k=1; k<=ncovmodel;k++){
7391: printf(" %.5e",delti[jk]);
7392: fprintf(ficlog," %.5e",delti[jk]);
7393: fprintf(ficres," %.5e",delti[jk]);
7394: jk++;
7395: }
7396: printf("\n");
7397: fprintf(ficlog,"\n");
7398: fprintf(ficres,"\n");
7399: }
7400: }
7401: }
7402:
7403: 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");
7404: if(mle>=1)
7405: 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");
7406: 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");
7407: /* # 121 Var(a12)\n\ */
7408: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7409: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7410: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7411: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7412: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7413: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7414: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7415:
7416:
7417: /* Just to have a covariance matrix which will be more understandable
7418: even is we still don't want to manage dictionary of variables
7419: */
7420: for(itimes=1;itimes<=2;itimes++){
7421: jj=0;
7422: for(i=1; i <=nlstate; i++){
7423: for(j=1; j <=nlstate+ndeath; j++){
7424: if(j==i) continue;
7425: for(k=1; k<=ncovmodel;k++){
7426: jj++;
7427: ca[0]= k+'a'-1;ca[1]='\0';
7428: if(itimes==1){
7429: if(mle>=1)
7430: printf("#%1d%1d%d",i,j,k);
7431: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7432: fprintf(ficres,"#%1d%1d%d",i,j,k);
7433: }else{
7434: if(mle>=1)
7435: printf("%1d%1d%d",i,j,k);
7436: fprintf(ficlog,"%1d%1d%d",i,j,k);
7437: fprintf(ficres,"%1d%1d%d",i,j,k);
7438: }
7439: ll=0;
7440: for(li=1;li <=nlstate; li++){
7441: for(lj=1;lj <=nlstate+ndeath; lj++){
7442: if(lj==li) continue;
7443: for(lk=1;lk<=ncovmodel;lk++){
7444: ll++;
7445: if(ll<=jj){
7446: cb[0]= lk +'a'-1;cb[1]='\0';
7447: if(ll<jj){
7448: if(itimes==1){
7449: if(mle>=1)
7450: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7451: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7452: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7453: }else{
7454: if(mle>=1)
7455: printf(" %.5e",matcov[jj][ll]);
7456: fprintf(ficlog," %.5e",matcov[jj][ll]);
7457: fprintf(ficres," %.5e",matcov[jj][ll]);
7458: }
7459: }else{
7460: if(itimes==1){
7461: if(mle>=1)
7462: printf(" Var(%s%1d%1d)",ca,i,j);
7463: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7464: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7465: }else{
7466: if(mle>=1)
7467: printf(" %.5e",matcov[jj][ll]);
7468: fprintf(ficlog," %.5e",matcov[jj][ll]);
7469: fprintf(ficres," %.5e",matcov[jj][ll]);
7470: }
7471: }
7472: }
7473: } /* end lk */
7474: } /* end lj */
7475: } /* end li */
7476: if(mle>=1)
7477: printf("\n");
7478: fprintf(ficlog,"\n");
7479: fprintf(ficres,"\n");
7480: numlinepar++;
7481: } /* end k*/
7482: } /*end j */
7483: } /* end i */
7484: } /* end itimes */
7485:
7486: fflush(ficlog);
7487: fflush(ficres);
7488:
7489: while((c=getc(ficpar))=='#' && c!= EOF){
7490: ungetc(c,ficpar);
7491: fgets(line, MAXLINE, ficpar);
1.141 brouard 7492: fputs(line,stdout);
1.126 brouard 7493: fputs(line,ficparo);
7494: }
7495: ungetc(c,ficpar);
7496:
7497: estepm=0;
7498: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
7499: if (estepm==0 || estepm < stepm) estepm=stepm;
7500: if (fage <= 2) {
7501: bage = ageminpar;
7502: fage = agemaxpar;
7503: }
7504:
7505: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7506: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7507: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186 brouard 7508:
7509: /* Other stuffs, more or less useful */
1.126 brouard 7510: while((c=getc(ficpar))=='#' && c!= EOF){
7511: ungetc(c,ficpar);
7512: fgets(line, MAXLINE, ficpar);
1.141 brouard 7513: fputs(line,stdout);
1.126 brouard 7514: fputs(line,ficparo);
7515: }
7516: ungetc(c,ficpar);
7517:
7518: 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);
7519: 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);
7520: 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);
7521: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
7522: 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);
7523:
7524: while((c=getc(ficpar))=='#' && c!= EOF){
7525: ungetc(c,ficpar);
7526: fgets(line, MAXLINE, ficpar);
1.141 brouard 7527: fputs(line,stdout);
1.126 brouard 7528: fputs(line,ficparo);
7529: }
7530: ungetc(c,ficpar);
7531:
7532:
7533: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
7534: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
7535:
7536: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 7537: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 7538: fprintf(ficparo,"pop_based=%d\n",popbased);
7539: fprintf(ficres,"pop_based=%d\n",popbased);
7540:
7541: while((c=getc(ficpar))=='#' && c!= EOF){
7542: ungetc(c,ficpar);
7543: fgets(line, MAXLINE, ficpar);
1.141 brouard 7544: fputs(line,stdout);
1.126 brouard 7545: fputs(line,ficparo);
7546: }
7547: ungetc(c,ficpar);
7548:
7549: 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);
7550: 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);
7551: 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);
7552: 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);
7553: 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);
7554: /* day and month of proj2 are not used but only year anproj2.*/
7555:
7556:
7557:
1.145 brouard 7558: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
7559: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 7560:
7561: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7562: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
7563: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7564: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7565: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7566: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7567: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7568: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7569: }else
7570: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126 brouard 7571:
7572: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
7573: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
7574: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
7575:
7576: /*------------ free_vector -------------*/
7577: /* chdir(path); */
7578:
7579: free_ivector(wav,1,imx);
7580: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
7581: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
7582: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
7583: free_lvector(num,1,n);
7584: free_vector(agedc,1,n);
7585: /*free_matrix(covar,0,NCOVMAX,1,n);*/
7586: /*free_matrix(covar,1,NCOVMAX,1,n);*/
7587: fclose(ficparo);
7588: fclose(ficres);
7589:
7590:
1.186 brouard 7591: /* Other results (useful)*/
7592:
7593:
1.126 brouard 7594: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 7595: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
7596: prlim=matrix(1,nlstate,1,nlstate);
7597: prevalence_limit(p, prlim, ageminpar, agemaxpar);
1.126 brouard 7598: fclose(ficrespl);
7599:
1.145 brouard 7600: #ifdef FREEEXIT2
7601: #include "freeexit2.h"
7602: #endif
7603:
1.126 brouard 7604: /*------------- h Pij x at various ages ------------*/
1.180 brouard 7605: /*#include "hpijx.h"*/
7606: hPijx(p, bage, fage);
1.145 brouard 7607: fclose(ficrespij);
1.126 brouard 7608:
1.145 brouard 7609: /*-------------- Variance of one-step probabilities---*/
7610: k=1;
1.126 brouard 7611: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
7612:
7613:
7614: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7615: for(i=1;i<=AGESUP;i++)
7616: for(j=1;j<=NCOVMAX;j++)
7617: for(k=1;k<=NCOVMAX;k++)
7618: probs[i][j][k]=0.;
7619:
7620: /*---------- Forecasting ------------------*/
7621: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
7622: if(prevfcast==1){
7623: /* if(stepm ==1){*/
7624: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
7625: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
7626: /* } */
7627: /* else{ */
7628: /* erreur=108; */
7629: /* 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); */
7630: /* 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); */
7631: /* } */
7632: }
1.186 brouard 7633:
7634: /* ------ Other prevalence ratios------------ */
1.126 brouard 7635:
1.127 brouard 7636: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
7637:
7638: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
7639: /* 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",\
7640: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
7641: */
1.126 brouard 7642:
1.127 brouard 7643: if (mobilav!=0) {
7644: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7645: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
7646: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
7647: printf(" Error in movingaverage mobilav=%d\n",mobilav);
7648: }
1.126 brouard 7649: }
7650:
7651:
1.127 brouard 7652: /*---------- Health expectancies, no variances ------------*/
7653:
1.126 brouard 7654: strcpy(filerese,"e");
7655: strcat(filerese,fileres);
7656: if((ficreseij=fopen(filerese,"w"))==NULL) {
7657: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7658: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7659: }
7660: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7661: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 7662: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7663: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7664:
7665: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 7666: fprintf(ficreseij,"\n#****** ");
7667: for(j=1;j<=cptcoveff;j++) {
1.200 ! brouard 7668: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127 brouard 7669: }
7670: fprintf(ficreseij,"******\n");
7671:
7672: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7673: oldm=oldms;savm=savms;
7674: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7675:
7676: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7677: /*}*/
1.127 brouard 7678: }
7679: fclose(ficreseij);
7680:
7681:
7682: /*---------- Health expectancies and variances ------------*/
7683:
7684:
7685: strcpy(filerest,"t");
7686: strcat(filerest,fileres);
7687: if((ficrest=fopen(filerest,"w"))==NULL) {
7688: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7689: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7690: }
7691: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7692: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7693:
1.126 brouard 7694:
7695: strcpy(fileresstde,"stde");
7696: strcat(fileresstde,fileres);
7697: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7698: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7699: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7700: }
7701: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7702: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7703:
7704: strcpy(filerescve,"cve");
7705: strcat(filerescve,fileres);
7706: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7707: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7708: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7709: }
7710: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7711: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7712:
7713: strcpy(fileresv,"v");
7714: strcat(fileresv,fileres);
7715: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7716: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7717: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7718: }
7719: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7720: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7721:
1.145 brouard 7722: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7723: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7724:
7725: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7726: fprintf(ficrest,"\n#****** ");
1.126 brouard 7727: for(j=1;j<=cptcoveff;j++)
1.200 ! brouard 7728: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 7729: fprintf(ficrest,"******\n");
7730:
7731: fprintf(ficresstdeij,"\n#****** ");
7732: fprintf(ficrescveij,"\n#****** ");
7733: for(j=1;j<=cptcoveff;j++) {
1.200 ! brouard 7734: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
! 7735: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 7736: }
7737: fprintf(ficresstdeij,"******\n");
7738: fprintf(ficrescveij,"******\n");
7739:
7740: fprintf(ficresvij,"\n#****** ");
7741: for(j=1;j<=cptcoveff;j++)
1.200 ! brouard 7742: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 7743: fprintf(ficresvij,"******\n");
7744:
7745: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7746: oldm=oldms;savm=savms;
1.127 brouard 7747: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 7748: /*
7749: */
7750: /* goto endfree; */
1.126 brouard 7751:
7752: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7753: pstamp(ficrest);
1.145 brouard 7754:
7755:
1.128 brouard 7756: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199 brouard 7757: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161 brouard 7758: cptcod= 0; /* To be deleted */
7759: 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 7760: 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 7761: if(vpopbased==1)
7762: 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);
7763: else
7764: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7765: fprintf(ficrest,"# Age e.. (std) ");
7766: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7767: fprintf(ficrest,"\n");
1.199 brouard 7768: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128 brouard 7769: epj=vector(1,nlstate+1);
7770: for(age=bage; age <=fage ;age++){
1.199 brouard 7771: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k); /*ZZ Is it the correct prevalim */
1.128 brouard 7772: if (vpopbased==1) {
7773: if(mobilav ==0){
7774: for(i=1; i<=nlstate;i++)
7775: prlim[i][i]=probs[(int)age][i][k];
7776: }else{ /* mobilav */
7777: for(i=1; i<=nlstate;i++)
7778: prlim[i][i]=mobaverage[(int)age][i][k];
7779: }
1.126 brouard 7780: }
7781:
1.128 brouard 7782: fprintf(ficrest," %4.0f",age);
1.199 brouard 7783: /* printf(" age %4.0f ",age); */
1.128 brouard 7784: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7785: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7786: epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199 brouard 7787: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7788: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128 brouard 7789: }
7790: epj[nlstate+1] +=epj[j];
1.126 brouard 7791: }
1.199 brouard 7792: /* printf(" age %4.0f \n",age); */
1.126 brouard 7793:
1.128 brouard 7794: for(i=1, vepp=0.;i <=nlstate;i++)
7795: for(j=1;j <=nlstate;j++)
7796: vepp += vareij[i][j][(int)age];
7797: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7798: for(j=1;j <=nlstate;j++){
7799: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7800: }
7801: fprintf(ficrest,"\n");
1.126 brouard 7802: }
7803: }
7804: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7805: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7806: free_vector(epj,1,nlstate+1);
1.145 brouard 7807: /*}*/
1.126 brouard 7808: }
7809: free_vector(weight,1,n);
1.145 brouard 7810: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 7811: free_imatrix(s,1,maxwav+1,1,n);
7812: free_matrix(anint,1,maxwav,1,n);
7813: free_matrix(mint,1,maxwav,1,n);
7814: free_ivector(cod,1,n);
7815: free_ivector(tab,1,NCOVMAX);
7816: fclose(ficresstdeij);
7817: fclose(ficrescveij);
7818: fclose(ficresvij);
7819: fclose(ficrest);
7820: fclose(ficpar);
7821:
7822: /*------- Variance of period (stable) prevalence------*/
7823:
7824: strcpy(fileresvpl,"vpl");
7825: strcat(fileresvpl,fileres);
7826: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7827: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7828: exit(0);
7829: }
7830: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7831:
1.145 brouard 7832: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7833: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7834:
7835: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7836: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 7837: for(j=1;j<=cptcoveff;j++)
1.200 ! brouard 7838: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 7839: fprintf(ficresvpl,"******\n");
7840:
7841: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7842: oldm=oldms;savm=savms;
7843: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7844: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 7845: /*}*/
1.126 brouard 7846: }
7847:
7848: fclose(ficresvpl);
7849:
7850: /*---------- End : free ----------------*/
7851: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7852: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7853: } /* mle==-3 arrives here for freeing */
1.164 brouard 7854: /* endfree:*/
1.141 brouard 7855: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 7856: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7857: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7858: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7859: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7860: free_matrix(covar,0,NCOVMAX,1,n);
7861: free_matrix(matcov,1,npar,1,npar);
7862: /*free_vector(delti,1,npar);*/
7863: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7864: free_matrix(agev,1,maxwav,1,imx);
7865: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7866:
1.145 brouard 7867: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 7868: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 7869: free_ivector(Tvar,1,NCOVMAX);
7870: free_ivector(Tprod,1,NCOVMAX);
7871: free_ivector(Tvaraff,1,NCOVMAX);
7872: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 7873:
7874: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200 ! brouard 7875: /* free_imatrix(codtab,1,100,1,10); */
1.126 brouard 7876: fflush(fichtm);
7877: fflush(ficgp);
7878:
7879:
7880: if((nberr >0) || (nbwarn>0)){
7881: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7882: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7883: }else{
7884: printf("End of Imach\n");
7885: fprintf(ficlog,"End of Imach\n");
7886: }
7887: printf("See log file on %s\n",filelog);
7888: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7889: /*(void) gettimeofday(&end_time,&tzp);*/
7890: rend_time = time(NULL);
7891: end_time = *localtime(&rend_time);
7892: /* tml = *localtime(&end_time.tm_sec); */
7893: strcpy(strtend,asctime(&end_time));
1.126 brouard 7894: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7895: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7896: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7897:
1.157 brouard 7898: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7899: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7900: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7901: /* printf("Total time was %d uSec.\n", total_usecs);*/
7902: /* if(fileappend(fichtm,optionfilehtm)){ */
7903: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7904: fclose(fichtm);
7905: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7906: fclose(fichtmcov);
7907: fclose(ficgp);
7908: fclose(ficlog);
7909: /*------ End -----------*/
7910:
7911:
7912: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 7913: #ifdef WIN32
7914: if (_chdir(pathcd) != 0)
7915: printf("Can't move to directory %s!\n",path);
7916: if(_getcwd(pathcd,MAXLINE) > 0)
7917: #else
1.126 brouard 7918: if(chdir(pathcd) != 0)
1.184 brouard 7919: printf("Can't move to directory %s!\n", path);
7920: if (getcwd(pathcd, MAXLINE) > 0)
7921: #endif
1.126 brouard 7922: printf("Current directory %s!\n",pathcd);
7923: /*strcat(plotcmd,CHARSEPARATOR);*/
7924: sprintf(plotcmd,"gnuplot");
1.157 brouard 7925: #ifdef _WIN32
1.126 brouard 7926: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7927: #endif
7928: if(!stat(plotcmd,&info)){
1.158 brouard 7929: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7930: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7931: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7932: }else
7933: strcpy(pplotcmd,plotcmd);
1.157 brouard 7934: #ifdef __unix
1.126 brouard 7935: strcpy(plotcmd,GNUPLOTPROGRAM);
7936: if(!stat(plotcmd,&info)){
1.158 brouard 7937: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7938: }else
7939: strcpy(pplotcmd,plotcmd);
7940: #endif
7941: }else
7942: strcpy(pplotcmd,plotcmd);
7943:
7944: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7945: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7946:
7947: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7948: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7949: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7950: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7951: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7952: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7953: }
1.158 brouard 7954: printf(" Successful, please wait...");
1.126 brouard 7955: while (z[0] != 'q') {
7956: /* chdir(path); */
1.154 brouard 7957: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7958: scanf("%s",z);
7959: /* if (z[0] == 'c') system("./imach"); */
7960: if (z[0] == 'e') {
1.158 brouard 7961: #ifdef __APPLE__
1.152 brouard 7962: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7963: #elif __linux
7964: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7965: #else
1.152 brouard 7966: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7967: #endif
7968: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7969: system(pplotcmd);
1.126 brouard 7970: }
7971: else if (z[0] == 'g') system(plotcmd);
7972: else if (z[0] == 'q') exit(0);
7973: }
7974: end:
7975: while (z[0] != 'q') {
1.195 brouard 7976: printf("\nType q for exiting: "); fflush(stdout);
1.126 brouard 7977: scanf("%s",z);
7978: }
7979: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>