Annotation of imach/src/imach.c, revision 1.213
1.213 ! brouard 1: /* $Id: imach.c,v 1.212 2015/11/21 12:47:24 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.213 ! brouard 4: Revision 1.212 2015/11/21 12:47:24 brouard
! 5: Summary: minor typo
! 6:
1.212 brouard 7: Revision 1.211 2015/11/21 12:41:11 brouard
8: Summary: 0.98r3 with some graph of projected cross-sectional
9:
10: Author: Nicolas Brouard
11:
1.211 brouard 12: Revision 1.210 2015/11/18 17:41:20 brouard
13: Summary: Start working on projected prevalences
14:
1.210 brouard 15: Revision 1.209 2015/11/17 22:12:03 brouard
16: Summary: Adding ftolpl parameter
17: Author: N Brouard
18:
19: We had difficulties to get smoothed confidence intervals. It was due
20: to the period prevalence which wasn't computed accurately. The inner
21: parameter ftolpl is now an outer parameter of the .imach parameter
22: file after estepm. If ftolpl is small 1.e-4 and estepm too,
23: computation are long.
24:
1.209 brouard 25: Revision 1.208 2015/11/17 14:31:57 brouard
26: Summary: temporary
27:
1.208 brouard 28: Revision 1.207 2015/10/27 17:36:57 brouard
29: *** empty log message ***
30:
1.207 brouard 31: Revision 1.206 2015/10/24 07:14:11 brouard
32: *** empty log message ***
33:
1.206 brouard 34: Revision 1.205 2015/10/23 15:50:53 brouard
35: Summary: 0.98r3 some clarification for graphs on likelihood contributions
36:
1.205 brouard 37: Revision 1.204 2015/10/01 16:20:26 brouard
38: Summary: Some new graphs of contribution to likelihood
39:
1.204 brouard 40: Revision 1.203 2015/09/30 17:45:14 brouard
41: Summary: looking at better estimation of the hessian
42:
43: Also a better criteria for convergence to the period prevalence And
44: therefore adding the number of years needed to converge. (The
45: prevalence in any alive state shold sum to one
46:
1.203 brouard 47: Revision 1.202 2015/09/22 19:45:16 brouard
48: Summary: Adding some overall graph on contribution to likelihood. Might change
49:
1.202 brouard 50: Revision 1.201 2015/09/15 17:34:58 brouard
51: Summary: 0.98r0
52:
53: - Some new graphs like suvival functions
54: - Some bugs fixed like model=1+age+V2.
55:
1.201 brouard 56: Revision 1.200 2015/09/09 16:53:55 brouard
57: Summary: Big bug thanks to Flavia
58:
59: Even model=1+age+V2. did not work anymore
60:
1.200 brouard 61: Revision 1.199 2015/09/07 14:09:23 brouard
62: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
63:
1.199 brouard 64: Revision 1.198 2015/09/03 07:14:39 brouard
65: Summary: 0.98q5 Flavia
66:
1.198 brouard 67: Revision 1.197 2015/09/01 18:24:39 brouard
68: *** empty log message ***
69:
1.197 brouard 70: Revision 1.196 2015/08/18 23:17:52 brouard
71: Summary: 0.98q5
72:
1.196 brouard 73: Revision 1.195 2015/08/18 16:28:39 brouard
74: Summary: Adding a hack for testing purpose
75:
76: After reading the title, ftol and model lines, if the comment line has
77: a q, starting with #q, the answer at the end of the run is quit. It
78: permits to run test files in batch with ctest. The former workaround was
79: $ echo q | imach foo.imach
80:
1.195 brouard 81: Revision 1.194 2015/08/18 13:32:00 brouard
82: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
83:
1.194 brouard 84: Revision 1.193 2015/08/04 07:17:42 brouard
85: Summary: 0.98q4
86:
1.193 brouard 87: Revision 1.192 2015/07/16 16:49:02 brouard
88: Summary: Fixing some outputs
89:
1.192 brouard 90: Revision 1.191 2015/07/14 10:00:33 brouard
91: Summary: Some fixes
92:
1.191 brouard 93: Revision 1.190 2015/05/05 08:51:13 brouard
94: Summary: Adding digits in output parameters (7 digits instead of 6)
95:
96: Fix 1+age+.
97:
1.190 brouard 98: Revision 1.189 2015/04/30 14:45:16 brouard
99: Summary: 0.98q2
100:
1.189 brouard 101: Revision 1.188 2015/04/30 08:27:53 brouard
102: *** empty log message ***
103:
1.188 brouard 104: Revision 1.187 2015/04/29 09:11:15 brouard
105: *** empty log message ***
106:
1.187 brouard 107: Revision 1.186 2015/04/23 12:01:52 brouard
108: Summary: V1*age is working now, version 0.98q1
109:
110: Some codes had been disabled in order to simplify and Vn*age was
111: working in the optimization phase, ie, giving correct MLE parameters,
112: but, as usual, outputs were not correct and program core dumped.
113:
1.186 brouard 114: Revision 1.185 2015/03/11 13:26:42 brouard
115: Summary: Inclusion of compile and links command line for Intel Compiler
116:
1.185 brouard 117: Revision 1.184 2015/03/11 11:52:39 brouard
118: Summary: Back from Windows 8. Intel Compiler
119:
1.184 brouard 120: Revision 1.183 2015/03/10 20:34:32 brouard
121: Summary: 0.98q0, trying with directest, mnbrak fixed
122:
123: We use directest instead of original Powell test; probably no
124: incidence on the results, but better justifications;
125: We fixed Numerical Recipes mnbrak routine which was wrong and gave
126: wrong results.
127:
1.183 brouard 128: Revision 1.182 2015/02/12 08:19:57 brouard
129: Summary: Trying to keep directest which seems simpler and more general
130: Author: Nicolas Brouard
131:
1.182 brouard 132: Revision 1.181 2015/02/11 23:22:24 brouard
133: Summary: Comments on Powell added
134:
135: Author:
136:
1.181 brouard 137: Revision 1.180 2015/02/11 17:33:45 brouard
138: Summary: Finishing move from main to function (hpijx and prevalence_limit)
139:
1.180 brouard 140: Revision 1.179 2015/01/04 09:57:06 brouard
141: Summary: back to OS/X
142:
1.179 brouard 143: Revision 1.178 2015/01/04 09:35:48 brouard
144: *** empty log message ***
145:
1.178 brouard 146: Revision 1.177 2015/01/03 18:40:56 brouard
147: Summary: Still testing ilc32 on OSX
148:
1.177 brouard 149: Revision 1.176 2015/01/03 16:45:04 brouard
150: *** empty log message ***
151:
1.176 brouard 152: Revision 1.175 2015/01/03 16:33:42 brouard
153: *** empty log message ***
154:
1.175 brouard 155: Revision 1.174 2015/01/03 16:15:49 brouard
156: Summary: Still in cross-compilation
157:
1.174 brouard 158: Revision 1.173 2015/01/03 12:06:26 brouard
159: Summary: trying to detect cross-compilation
160:
1.173 brouard 161: Revision 1.172 2014/12/27 12:07:47 brouard
162: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
163:
1.172 brouard 164: Revision 1.171 2014/12/23 13:26:59 brouard
165: Summary: Back from Visual C
166:
167: Still problem with utsname.h on Windows
168:
1.171 brouard 169: Revision 1.170 2014/12/23 11:17:12 brouard
170: Summary: Cleaning some \%% back to %%
171:
172: The escape was mandatory for a specific compiler (which one?), but too many warnings.
173:
1.170 brouard 174: Revision 1.169 2014/12/22 23:08:31 brouard
175: Summary: 0.98p
176:
177: Outputs some informations on compiler used, OS etc. Testing on different platforms.
178:
1.169 brouard 179: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 180: Summary: update
1.169 brouard 181:
1.168 brouard 182: Revision 1.167 2014/12/22 13:50:56 brouard
183: Summary: Testing uname and compiler version and if compiled 32 or 64
184:
185: Testing on Linux 64
186:
1.167 brouard 187: Revision 1.166 2014/12/22 11:40:47 brouard
188: *** empty log message ***
189:
1.166 brouard 190: Revision 1.165 2014/12/16 11:20:36 brouard
191: Summary: After compiling on Visual C
192:
193: * imach.c (Module): Merging 1.61 to 1.162
194:
1.165 brouard 195: Revision 1.164 2014/12/16 10:52:11 brouard
196: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
197:
198: * imach.c (Module): Merging 1.61 to 1.162
199:
1.164 brouard 200: Revision 1.163 2014/12/16 10:30:11 brouard
201: * imach.c (Module): Merging 1.61 to 1.162
202:
1.163 brouard 203: Revision 1.162 2014/09/25 11:43:39 brouard
204: Summary: temporary backup 0.99!
205:
1.162 brouard 206: Revision 1.1 2014/09/16 11:06:58 brouard
207: Summary: With some code (wrong) for nlopt
208:
209: Author:
210:
211: Revision 1.161 2014/09/15 20:41:41 brouard
212: Summary: Problem with macro SQR on Intel compiler
213:
1.161 brouard 214: Revision 1.160 2014/09/02 09:24:05 brouard
215: *** empty log message ***
216:
1.160 brouard 217: Revision 1.159 2014/09/01 10:34:10 brouard
218: Summary: WIN32
219: Author: Brouard
220:
1.159 brouard 221: Revision 1.158 2014/08/27 17:11:51 brouard
222: *** empty log message ***
223:
1.158 brouard 224: Revision 1.157 2014/08/27 16:26:55 brouard
225: Summary: Preparing windows Visual studio version
226: Author: Brouard
227:
228: In order to compile on Visual studio, time.h is now correct and time_t
229: and tm struct should be used. difftime should be used but sometimes I
230: just make the differences in raw time format (time(&now).
231: Trying to suppress #ifdef LINUX
232: Add xdg-open for __linux in order to open default browser.
233:
1.157 brouard 234: Revision 1.156 2014/08/25 20:10:10 brouard
235: *** empty log message ***
236:
1.156 brouard 237: Revision 1.155 2014/08/25 18:32:34 brouard
238: Summary: New compile, minor changes
239: Author: Brouard
240:
1.155 brouard 241: Revision 1.154 2014/06/20 17:32:08 brouard
242: Summary: Outputs now all graphs of convergence to period prevalence
243:
1.154 brouard 244: Revision 1.153 2014/06/20 16:45:46 brouard
245: Summary: If 3 live state, convergence to period prevalence on same graph
246: Author: Brouard
247:
1.153 brouard 248: Revision 1.152 2014/06/18 17:54:09 brouard
249: Summary: open browser, use gnuplot on same dir than imach if not found in the path
250:
1.152 brouard 251: Revision 1.151 2014/06/18 16:43:30 brouard
252: *** empty log message ***
253:
1.151 brouard 254: Revision 1.150 2014/06/18 16:42:35 brouard
255: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
256: Author: brouard
257:
1.150 brouard 258: Revision 1.149 2014/06/18 15:51:14 brouard
259: Summary: Some fixes in parameter files errors
260: Author: Nicolas Brouard
261:
1.149 brouard 262: Revision 1.148 2014/06/17 17:38:48 brouard
263: Summary: Nothing new
264: Author: Brouard
265:
266: Just a new packaging for OS/X version 0.98nS
267:
1.148 brouard 268: Revision 1.147 2014/06/16 10:33:11 brouard
269: *** empty log message ***
270:
1.147 brouard 271: Revision 1.146 2014/06/16 10:20:28 brouard
272: Summary: Merge
273: Author: Brouard
274:
275: Merge, before building revised version.
276:
1.146 brouard 277: Revision 1.145 2014/06/10 21:23:15 brouard
278: Summary: Debugging with valgrind
279: Author: Nicolas Brouard
280:
281: Lot of changes in order to output the results with some covariates
282: After the Edimburgh REVES conference 2014, it seems mandatory to
283: improve the code.
284: No more memory valgrind error but a lot has to be done in order to
285: continue the work of splitting the code into subroutines.
286: Also, decodemodel has been improved. Tricode is still not
287: optimal. nbcode should be improved. Documentation has been added in
288: the source code.
289:
1.144 brouard 290: Revision 1.143 2014/01/26 09:45:38 brouard
291: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
292:
293: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
294: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
295:
1.143 brouard 296: Revision 1.142 2014/01/26 03:57:36 brouard
297: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
298:
299: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
300:
1.142 brouard 301: Revision 1.141 2014/01/26 02:42:01 brouard
302: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
303:
1.141 brouard 304: Revision 1.140 2011/09/02 10:37:54 brouard
305: Summary: times.h is ok with mingw32 now.
306:
1.140 brouard 307: Revision 1.139 2010/06/14 07:50:17 brouard
308: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
309: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
310:
1.139 brouard 311: Revision 1.138 2010/04/30 18:19:40 brouard
312: *** empty log message ***
313:
1.138 brouard 314: Revision 1.137 2010/04/29 18:11:38 brouard
315: (Module): Checking covariates for more complex models
316: than V1+V2. A lot of change to be done. Unstable.
317:
1.137 brouard 318: Revision 1.136 2010/04/26 20:30:53 brouard
319: (Module): merging some libgsl code. Fixing computation
320: of likelione (using inter/intrapolation if mle = 0) in order to
321: get same likelihood as if mle=1.
322: Some cleaning of code and comments added.
323:
1.136 brouard 324: Revision 1.135 2009/10/29 15:33:14 brouard
325: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
326:
1.135 brouard 327: Revision 1.134 2009/10/29 13:18:53 brouard
328: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
329:
1.134 brouard 330: Revision 1.133 2009/07/06 10:21:25 brouard
331: just nforces
332:
1.133 brouard 333: Revision 1.132 2009/07/06 08:22:05 brouard
334: Many tings
335:
1.132 brouard 336: Revision 1.131 2009/06/20 16:22:47 brouard
337: Some dimensions resccaled
338:
1.131 brouard 339: Revision 1.130 2009/05/26 06:44:34 brouard
340: (Module): Max Covariate is now set to 20 instead of 8. A
341: lot of cleaning with variables initialized to 0. Trying to make
342: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
343:
1.130 brouard 344: Revision 1.129 2007/08/31 13:49:27 lievre
345: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
346:
1.129 lievre 347: Revision 1.128 2006/06/30 13:02:05 brouard
348: (Module): Clarifications on computing e.j
349:
1.128 brouard 350: Revision 1.127 2006/04/28 18:11:50 brouard
351: (Module): Yes the sum of survivors was wrong since
352: imach-114 because nhstepm was no more computed in the age
353: loop. Now we define nhstepma in the age loop.
354: (Module): In order to speed up (in case of numerous covariates) we
355: compute health expectancies (without variances) in a first step
356: and then all the health expectancies with variances or standard
357: deviation (needs data from the Hessian matrices) which slows the
358: computation.
359: In the future we should be able to stop the program is only health
360: expectancies and graph are needed without standard deviations.
361:
1.127 brouard 362: Revision 1.126 2006/04/28 17:23:28 brouard
363: (Module): Yes the sum of survivors was wrong since
364: imach-114 because nhstepm was no more computed in the age
365: loop. Now we define nhstepma in the age loop.
366: Version 0.98h
367:
1.126 brouard 368: Revision 1.125 2006/04/04 15:20:31 lievre
369: Errors in calculation of health expectancies. Age was not initialized.
370: Forecasting file added.
371:
372: Revision 1.124 2006/03/22 17:13:53 lievre
373: Parameters are printed with %lf instead of %f (more numbers after the comma).
374: The log-likelihood is printed in the log file
375:
376: Revision 1.123 2006/03/20 10:52:43 brouard
377: * imach.c (Module): <title> changed, corresponds to .htm file
378: name. <head> headers where missing.
379:
380: * imach.c (Module): Weights can have a decimal point as for
381: English (a comma might work with a correct LC_NUMERIC environment,
382: otherwise the weight is truncated).
383: Modification of warning when the covariates values are not 0 or
384: 1.
385: Version 0.98g
386:
387: Revision 1.122 2006/03/20 09:45:41 brouard
388: (Module): Weights can have a decimal point as for
389: English (a comma might work with a correct LC_NUMERIC environment,
390: otherwise the weight is truncated).
391: Modification of warning when the covariates values are not 0 or
392: 1.
393: Version 0.98g
394:
395: Revision 1.121 2006/03/16 17:45:01 lievre
396: * imach.c (Module): Comments concerning covariates added
397:
398: * imach.c (Module): refinements in the computation of lli if
399: status=-2 in order to have more reliable computation if stepm is
400: not 1 month. Version 0.98f
401:
402: Revision 1.120 2006/03/16 15:10:38 lievre
403: (Module): refinements in the computation of lli if
404: status=-2 in order to have more reliable computation if stepm is
405: not 1 month. Version 0.98f
406:
407: Revision 1.119 2006/03/15 17:42:26 brouard
408: (Module): Bug if status = -2, the loglikelihood was
409: computed as likelihood omitting the logarithm. Version O.98e
410:
411: Revision 1.118 2006/03/14 18:20:07 brouard
412: (Module): varevsij Comments added explaining the second
413: table of variances if popbased=1 .
414: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
415: (Module): Function pstamp added
416: (Module): Version 0.98d
417:
418: Revision 1.117 2006/03/14 17:16:22 brouard
419: (Module): varevsij Comments added explaining the second
420: table of variances if popbased=1 .
421: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
422: (Module): Function pstamp added
423: (Module): Version 0.98d
424:
425: Revision 1.116 2006/03/06 10:29:27 brouard
426: (Module): Variance-covariance wrong links and
427: varian-covariance of ej. is needed (Saito).
428:
429: Revision 1.115 2006/02/27 12:17:45 brouard
430: (Module): One freematrix added in mlikeli! 0.98c
431:
432: Revision 1.114 2006/02/26 12:57:58 brouard
433: (Module): Some improvements in processing parameter
434: filename with strsep.
435:
436: Revision 1.113 2006/02/24 14:20:24 brouard
437: (Module): Memory leaks checks with valgrind and:
438: datafile was not closed, some imatrix were not freed and on matrix
439: allocation too.
440:
441: Revision 1.112 2006/01/30 09:55:26 brouard
442: (Module): Back to gnuplot.exe instead of wgnuplot.exe
443:
444: Revision 1.111 2006/01/25 20:38:18 brouard
445: (Module): Lots of cleaning and bugs added (Gompertz)
446: (Module): Comments can be added in data file. Missing date values
447: can be a simple dot '.'.
448:
449: Revision 1.110 2006/01/25 00:51:50 brouard
450: (Module): Lots of cleaning and bugs added (Gompertz)
451:
452: Revision 1.109 2006/01/24 19:37:15 brouard
453: (Module): Comments (lines starting with a #) are allowed in data.
454:
455: Revision 1.108 2006/01/19 18:05:42 lievre
456: Gnuplot problem appeared...
457: To be fixed
458:
459: Revision 1.107 2006/01/19 16:20:37 brouard
460: Test existence of gnuplot in imach path
461:
462: Revision 1.106 2006/01/19 13:24:36 brouard
463: Some cleaning and links added in html output
464:
465: Revision 1.105 2006/01/05 20:23:19 lievre
466: *** empty log message ***
467:
468: Revision 1.104 2005/09/30 16:11:43 lievre
469: (Module): sump fixed, loop imx fixed, and simplifications.
470: (Module): If the status is missing at the last wave but we know
471: that the person is alive, then we can code his/her status as -2
472: (instead of missing=-1 in earlier versions) and his/her
473: contributions to the likelihood is 1 - Prob of dying from last
474: health status (= 1-p13= p11+p12 in the easiest case of somebody in
475: the healthy state at last known wave). Version is 0.98
476:
477: Revision 1.103 2005/09/30 15:54:49 lievre
478: (Module): sump fixed, loop imx fixed, and simplifications.
479:
480: Revision 1.102 2004/09/15 17:31:30 brouard
481: Add the possibility to read data file including tab characters.
482:
483: Revision 1.101 2004/09/15 10:38:38 brouard
484: Fix on curr_time
485:
486: Revision 1.100 2004/07/12 18:29:06 brouard
487: Add version for Mac OS X. Just define UNIX in Makefile
488:
489: Revision 1.99 2004/06/05 08:57:40 brouard
490: *** empty log message ***
491:
492: Revision 1.98 2004/05/16 15:05:56 brouard
493: New version 0.97 . First attempt to estimate force of mortality
494: directly from the data i.e. without the need of knowing the health
495: state at each age, but using a Gompertz model: log u =a + b*age .
496: This is the basic analysis of mortality and should be done before any
497: other analysis, in order to test if the mortality estimated from the
498: cross-longitudinal survey is different from the mortality estimated
499: from other sources like vital statistic data.
500:
501: The same imach parameter file can be used but the option for mle should be -3.
502:
1.133 brouard 503: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 504: former routines in order to include the new code within the former code.
505:
506: The output is very simple: only an estimate of the intercept and of
507: the slope with 95% confident intervals.
508:
509: Current limitations:
510: A) Even if you enter covariates, i.e. with the
511: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
512: B) There is no computation of Life Expectancy nor Life Table.
513:
514: Revision 1.97 2004/02/20 13:25:42 lievre
515: Version 0.96d. Population forecasting command line is (temporarily)
516: suppressed.
517:
518: Revision 1.96 2003/07/15 15:38:55 brouard
519: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
520: rewritten within the same printf. Workaround: many printfs.
521:
522: Revision 1.95 2003/07/08 07:54:34 brouard
523: * imach.c (Repository):
524: (Repository): Using imachwizard code to output a more meaningful covariance
525: matrix (cov(a12,c31) instead of numbers.
526:
527: Revision 1.94 2003/06/27 13:00:02 brouard
528: Just cleaning
529:
530: Revision 1.93 2003/06/25 16:33:55 brouard
531: (Module): On windows (cygwin) function asctime_r doesn't
532: exist so I changed back to asctime which exists.
533: (Module): Version 0.96b
534:
535: Revision 1.92 2003/06/25 16:30:45 brouard
536: (Module): On windows (cygwin) function asctime_r doesn't
537: exist so I changed back to asctime which exists.
538:
539: Revision 1.91 2003/06/25 15:30:29 brouard
540: * imach.c (Repository): Duplicated warning errors corrected.
541: (Repository): Elapsed time after each iteration is now output. It
542: helps to forecast when convergence will be reached. Elapsed time
543: is stamped in powell. We created a new html file for the graphs
544: concerning matrix of covariance. It has extension -cov.htm.
545:
546: Revision 1.90 2003/06/24 12:34:15 brouard
547: (Module): Some bugs corrected for windows. Also, when
548: mle=-1 a template is output in file "or"mypar.txt with the design
549: of the covariance matrix to be input.
550:
551: Revision 1.89 2003/06/24 12:30:52 brouard
552: (Module): Some bugs corrected for windows. Also, when
553: mle=-1 a template is output in file "or"mypar.txt with the design
554: of the covariance matrix to be input.
555:
556: Revision 1.88 2003/06/23 17:54:56 brouard
557: * 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.
558:
559: Revision 1.87 2003/06/18 12:26:01 brouard
560: Version 0.96
561:
562: Revision 1.86 2003/06/17 20:04:08 brouard
563: (Module): Change position of html and gnuplot routines and added
564: routine fileappend.
565:
566: Revision 1.85 2003/06/17 13:12:43 brouard
567: * imach.c (Repository): Check when date of death was earlier that
568: current date of interview. It may happen when the death was just
569: prior to the death. In this case, dh was negative and likelihood
570: was wrong (infinity). We still send an "Error" but patch by
571: assuming that the date of death was just one stepm after the
572: interview.
573: (Repository): Because some people have very long ID (first column)
574: we changed int to long in num[] and we added a new lvector for
575: memory allocation. But we also truncated to 8 characters (left
576: truncation)
577: (Repository): No more line truncation errors.
578:
579: Revision 1.84 2003/06/13 21:44:43 brouard
580: * imach.c (Repository): Replace "freqsummary" at a correct
581: place. It differs from routine "prevalence" which may be called
582: many times. Probs is memory consuming and must be used with
583: parcimony.
584: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
585:
586: Revision 1.83 2003/06/10 13:39:11 lievre
587: *** empty log message ***
588:
589: Revision 1.82 2003/06/05 15:57:20 brouard
590: Add log in imach.c and fullversion number is now printed.
591:
592: */
593: /*
594: Interpolated Markov Chain
595:
596: Short summary of the programme:
597:
598: This program computes Healthy Life Expectancies from
599: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
600: first survey ("cross") where individuals from different ages are
601: interviewed on their health status or degree of disability (in the
602: case of a health survey which is our main interest) -2- at least a
603: second wave of interviews ("longitudinal") which measure each change
604: (if any) in individual health status. Health expectancies are
605: computed from the time spent in each health state according to a
606: model. More health states you consider, more time is necessary to reach the
607: Maximum Likelihood of the parameters involved in the model. The
608: simplest model is the multinomial logistic model where pij is the
609: probability to be observed in state j at the second wave
610: conditional to be observed in state i at the first wave. Therefore
611: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
612: 'age' is age and 'sex' is a covariate. If you want to have a more
613: complex model than "constant and age", you should modify the program
614: where the markup *Covariates have to be included here again* invites
615: you to do it. More covariates you add, slower the
616: convergence.
617:
618: The advantage of this computer programme, compared to a simple
619: multinomial logistic model, is clear when the delay between waves is not
620: identical for each individual. Also, if a individual missed an
621: intermediate interview, the information is lost, but taken into
622: account using an interpolation or extrapolation.
623:
624: hPijx is the probability to be observed in state i at age x+h
625: conditional to the observed state i at age x. The delay 'h' can be
626: split into an exact number (nh*stepm) of unobserved intermediate
627: states. This elementary transition (by month, quarter,
628: semester or year) is modelled as a multinomial logistic. The hPx
629: matrix is simply the matrix product of nh*stepm elementary matrices
630: and the contribution of each individual to the likelihood is simply
631: hPijx.
632:
633: Also this programme outputs the covariance matrix of the parameters but also
634: of the life expectancies. It also computes the period (stable) prevalence.
635:
1.133 brouard 636: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
637: Institut national d'études démographiques, Paris.
1.126 brouard 638: This software have been partly granted by Euro-REVES, a concerted action
639: from the European Union.
640: It is copyrighted identically to a GNU software product, ie programme and
641: software can be distributed freely for non commercial use. Latest version
642: can be accessed at http://euroreves.ined.fr/imach .
643:
644: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
645: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
646:
647: **********************************************************************/
648: /*
649: main
650: read parameterfile
651: read datafile
652: concatwav
653: freqsummary
654: if (mle >= 1)
655: mlikeli
656: print results files
657: if mle==1
658: computes hessian
659: read end of parameter file: agemin, agemax, bage, fage, estepm
660: begin-prev-date,...
661: open gnuplot file
662: open html file
1.145 brouard 663: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
664: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
665: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
666: freexexit2 possible for memory heap.
667:
668: h Pij x | pij_nom ficrestpij
669: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
670: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
671: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
672:
673: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
674: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
675: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
676: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
677: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
678:
1.126 brouard 679: forecasting if prevfcast==1 prevforecast call prevalence()
680: health expectancies
681: Variance-covariance of DFLE
682: prevalence()
683: movingaverage()
684: varevsij()
685: if popbased==1 varevsij(,popbased)
686: total life expectancies
687: Variance of period (stable) prevalence
688: end
689: */
690:
1.187 brouard 691: /* #define DEBUG */
692: /* #define DEBUGBRENT */
1.203 brouard 693: /* #define DEBUGLINMIN */
694: /* #define DEBUGHESS */
695: #define DEBUGHESSIJ
696: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165 brouard 697: #define POWELL /* Instead of NLOPT */
1.192 brouard 698: #define POWELLF1F3 /* Skip test */
1.186 brouard 699: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
700: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 701:
702: #include <math.h>
703: #include <stdio.h>
704: #include <stdlib.h>
705: #include <string.h>
1.159 brouard 706:
707: #ifdef _WIN32
708: #include <io.h>
1.172 brouard 709: #include <windows.h>
710: #include <tchar.h>
1.159 brouard 711: #else
1.126 brouard 712: #include <unistd.h>
1.159 brouard 713: #endif
1.126 brouard 714:
715: #include <limits.h>
716: #include <sys/types.h>
1.171 brouard 717:
718: #if defined(__GNUC__)
719: #include <sys/utsname.h> /* Doesn't work on Windows */
720: #endif
721:
1.126 brouard 722: #include <sys/stat.h>
723: #include <errno.h>
1.159 brouard 724: /* extern int errno; */
1.126 brouard 725:
1.157 brouard 726: /* #ifdef LINUX */
727: /* #include <time.h> */
728: /* #include "timeval.h" */
729: /* #else */
730: /* #include <sys/time.h> */
731: /* #endif */
732:
1.126 brouard 733: #include <time.h>
734:
1.136 brouard 735: #ifdef GSL
736: #include <gsl/gsl_errno.h>
737: #include <gsl/gsl_multimin.h>
738: #endif
739:
1.167 brouard 740:
1.162 brouard 741: #ifdef NLOPT
742: #include <nlopt.h>
743: typedef struct {
744: double (* function)(double [] );
745: } myfunc_data ;
746: #endif
747:
1.126 brouard 748: /* #include <libintl.h> */
749: /* #define _(String) gettext (String) */
750:
1.141 brouard 751: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 752:
753: #define GNUPLOTPROGRAM "gnuplot"
754: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
755: #define FILENAMELENGTH 132
756:
757: #define GLOCK_ERROR_NOPATH -1 /* empty path */
758: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
759:
1.144 brouard 760: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
761: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 762:
763: #define NINTERVMAX 8
1.144 brouard 764: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
765: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
766: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197 brouard 767: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.211 brouard 768: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
769: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
1.126 brouard 770: #define MAXN 20000
1.144 brouard 771: #define YEARM 12. /**< Number of months per year */
1.126 brouard 772: #define AGESUP 130
773: #define AGEBASE 40
1.194 brouard 774: #define AGEOVERFLOW 1.e20
1.164 brouard 775: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 776: #ifdef _WIN32
777: #define DIRSEPARATOR '\\'
778: #define CHARSEPARATOR "\\"
779: #define ODIRSEPARATOR '/'
780: #else
1.126 brouard 781: #define DIRSEPARATOR '/'
782: #define CHARSEPARATOR "/"
783: #define ODIRSEPARATOR '\\'
784: #endif
785:
1.213 ! brouard 786: /* $Id: imach.c,v 1.212 2015/11/21 12:47:24 brouard Exp $ */
1.126 brouard 787: /* $State: Exp $ */
1.196 brouard 788: #include "version.h"
789: char version[]=__IMACH_VERSION__;
1.204 brouard 790: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.213 ! brouard 791: char fullversion[]="$Revision: 1.212 $ $Date: 2015/11/21 12:47:24 $";
1.126 brouard 792: char strstart[80];
793: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 794: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 795: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 796: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
797: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
798: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
799: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
800: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
801: int cptcovprodnoage=0; /**< Number of covariate products without age */
802: int cptcoveff=0; /* Total number of covariates to vary for printing results */
803: int cptcov=0; /* Working variable */
1.126 brouard 804: int npar=NPARMAX;
805: int nlstate=2; /* Number of live states */
806: int ndeath=1; /* Number of dead states */
1.130 brouard 807: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 808: int popbased=0;
809:
810: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 811: int maxwav=0; /* Maxim number of waves */
812: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
813: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
814: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 815: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 816: int mle=1, weightopt=0;
1.126 brouard 817: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
818: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
819: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
820: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 821: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 822: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 823: double **matprod2(); /* test */
1.126 brouard 824: double **oldm, **newm, **savm; /* Working pointers to matrices */
825: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 826: /*FILE *fic ; */ /* Used in readdata only */
1.213 ! brouard 827: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 828: FILE *ficlog, *ficrespow;
1.130 brouard 829: int globpr=0; /* Global variable for printing or not */
1.126 brouard 830: double fretone; /* Only one call to likelihood */
1.130 brouard 831: long ipmx=0; /* Number of contributions */
1.126 brouard 832: double sw; /* Sum of weights */
833: char filerespow[FILENAMELENGTH];
834: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
835: FILE *ficresilk;
836: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
837: FILE *ficresprobmorprev;
838: FILE *fichtm, *fichtmcov; /* Html File */
839: FILE *ficreseij;
840: char filerese[FILENAMELENGTH];
841: FILE *ficresstdeij;
842: char fileresstde[FILENAMELENGTH];
843: FILE *ficrescveij;
844: char filerescve[FILENAMELENGTH];
845: FILE *ficresvij;
846: char fileresv[FILENAMELENGTH];
847: FILE *ficresvpl;
848: char fileresvpl[FILENAMELENGTH];
849: char title[MAXLINE];
850: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
851: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
852: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
853: char command[FILENAMELENGTH];
854: int outcmd=0;
855:
856: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202 brouard 857: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126 brouard 858: char filelog[FILENAMELENGTH]; /* Log file */
859: char filerest[FILENAMELENGTH];
860: char fileregp[FILENAMELENGTH];
861: char popfile[FILENAMELENGTH];
862:
863: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
864:
1.157 brouard 865: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
866: /* struct timezone tzp; */
867: /* extern int gettimeofday(); */
868: struct tm tml, *gmtime(), *localtime();
869:
870: extern time_t time();
871:
872: struct tm start_time, end_time, curr_time, last_time, forecast_time;
873: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
874: struct tm tm;
875:
1.126 brouard 876: char strcurr[80], strfor[80];
877:
878: char *endptr;
879: long lval;
880: double dval;
881:
882: #define NR_END 1
883: #define FREE_ARG char*
884: #define FTOL 1.0e-10
885:
886: #define NRANSI
887: #define ITMAX 200
888:
889: #define TOL 2.0e-4
890:
891: #define CGOLD 0.3819660
892: #define ZEPS 1.0e-10
893: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
894:
895: #define GOLD 1.618034
896: #define GLIMIT 100.0
897: #define TINY 1.0e-20
898:
899: static double maxarg1,maxarg2;
900: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
901: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
902:
903: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
904: #define rint(a) floor(a+0.5)
1.166 brouard 905: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 906: #define mytinydouble 1.0e-16
1.166 brouard 907: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
908: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
909: /* static double dsqrarg; */
910: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 911: static double sqrarg;
912: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
913: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
914: int agegomp= AGEGOMP;
915:
916: int imx;
917: int stepm=1;
918: /* Stepm, step in month: minimum step interpolation*/
919:
920: int estepm;
921: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
922:
923: int m,nb;
924: long *num;
1.197 brouard 925: int firstpass=0, lastpass=4,*cod, *cens;
1.192 brouard 926: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
927: covariate for which somebody answered excluding
928: undefined. Usually 2: 0 and 1. */
929: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
930: covariate for which somebody answered including
931: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 932: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
933: double **pmmij, ***probs;
934: double *ageexmed,*agecens;
935: double dateintmean=0;
936:
937: double *weight;
938: int **s; /* Status */
1.141 brouard 939: double *agedc;
1.145 brouard 940: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 941: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 942: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 943: double idx;
944: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197 brouard 945: int *Tage;
1.145 brouard 946: int *Ndum; /** Freq of modality (tricode */
1.200 brouard 947: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141 brouard 948: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 949: double *lsurv, *lpop, *tpop;
950:
1.143 brouard 951: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
952: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 953:
954: /**************** split *************************/
955: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
956: {
957: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
958: the name of the file (name), its extension only (ext) and its first part of the name (finame)
959: */
960: char *ss; /* pointer */
1.186 brouard 961: int l1=0, l2=0; /* length counters */
1.126 brouard 962:
963: l1 = strlen(path ); /* length of path */
964: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
965: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
966: if ( ss == NULL ) { /* no directory, so determine current directory */
967: strcpy( name, path ); /* we got the fullname name because no directory */
968: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
969: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
970: /* get current working directory */
971: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 972: #ifdef WIN32
973: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
974: #else
975: if (getcwd(dirc, FILENAME_MAX) == NULL) {
976: #endif
1.126 brouard 977: return( GLOCK_ERROR_GETCWD );
978: }
979: /* got dirc from getcwd*/
980: printf(" DIRC = %s \n",dirc);
1.205 brouard 981: } else { /* strip directory from path */
1.126 brouard 982: ss++; /* after this, the filename */
983: l2 = strlen( ss ); /* length of filename */
984: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
985: strcpy( name, ss ); /* save file name */
986: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 987: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 988: printf(" DIRC2 = %s \n",dirc);
989: }
990: /* We add a separator at the end of dirc if not exists */
991: l1 = strlen( dirc ); /* length of directory */
992: if( dirc[l1-1] != DIRSEPARATOR ){
993: dirc[l1] = DIRSEPARATOR;
994: dirc[l1+1] = 0;
995: printf(" DIRC3 = %s \n",dirc);
996: }
997: ss = strrchr( name, '.' ); /* find last / */
998: if (ss >0){
999: ss++;
1000: strcpy(ext,ss); /* save extension */
1001: l1= strlen( name);
1002: l2= strlen(ss)+1;
1003: strncpy( finame, name, l1-l2);
1004: finame[l1-l2]= 0;
1005: }
1006:
1007: return( 0 ); /* we're done */
1008: }
1009:
1010:
1011: /******************************************/
1012:
1013: void replace_back_to_slash(char *s, char*t)
1014: {
1015: int i;
1016: int lg=0;
1017: i=0;
1018: lg=strlen(t);
1019: for(i=0; i<= lg; i++) {
1020: (s[i] = t[i]);
1021: if (t[i]== '\\') s[i]='/';
1022: }
1023: }
1024:
1.132 brouard 1025: char *trimbb(char *out, char *in)
1.137 brouard 1026: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 1027: char *s;
1028: s=out;
1029: while (*in != '\0'){
1.137 brouard 1030: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 1031: in++;
1032: }
1033: *out++ = *in++;
1034: }
1035: *out='\0';
1036: return s;
1037: }
1038:
1.187 brouard 1039: /* char *substrchaine(char *out, char *in, char *chain) */
1040: /* { */
1041: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1042: /* char *s, *t; */
1043: /* t=in;s=out; */
1044: /* while ((*in != *chain) && (*in != '\0')){ */
1045: /* *out++ = *in++; */
1046: /* } */
1047:
1048: /* /\* *in matches *chain *\/ */
1049: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1050: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1051: /* } */
1052: /* in--; chain--; */
1053: /* while ( (*in != '\0')){ */
1054: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1055: /* *out++ = *in++; */
1056: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1057: /* } */
1058: /* *out='\0'; */
1059: /* out=s; */
1060: /* return out; */
1061: /* } */
1062: char *substrchaine(char *out, char *in, char *chain)
1063: {
1064: /* Substract chain 'chain' from 'in', return and output 'out' */
1065: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1066:
1067: char *strloc;
1068:
1069: strcpy (out, in);
1070: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1071: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1072: if(strloc != NULL){
1073: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1074: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1075: /* strcpy (strloc, strloc +strlen(chain));*/
1076: }
1077: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1078: return out;
1079: }
1080:
1081:
1.145 brouard 1082: char *cutl(char *blocc, char *alocc, char *in, char occ)
1083: {
1.187 brouard 1084: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 1085: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 1086: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 1087: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1088: */
1.160 brouard 1089: char *s, *t;
1.145 brouard 1090: t=in;s=in;
1091: while ((*in != occ) && (*in != '\0')){
1092: *alocc++ = *in++;
1093: }
1094: if( *in == occ){
1095: *(alocc)='\0';
1096: s=++in;
1097: }
1098:
1099: if (s == t) {/* occ not found */
1100: *(alocc-(in-s))='\0';
1101: in=s;
1102: }
1103: while ( *in != '\0'){
1104: *blocc++ = *in++;
1105: }
1106:
1107: *blocc='\0';
1108: return t;
1109: }
1.137 brouard 1110: char *cutv(char *blocc, char *alocc, char *in, char occ)
1111: {
1.187 brouard 1112: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1113: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1114: gives blocc="abcdef2ghi" and alocc="j".
1115: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1116: */
1117: char *s, *t;
1118: t=in;s=in;
1119: while (*in != '\0'){
1120: while( *in == occ){
1121: *blocc++ = *in++;
1122: s=in;
1123: }
1124: *blocc++ = *in++;
1125: }
1126: if (s == t) /* occ not found */
1127: *(blocc-(in-s))='\0';
1128: else
1129: *(blocc-(in-s)-1)='\0';
1130: in=s;
1131: while ( *in != '\0'){
1132: *alocc++ = *in++;
1133: }
1134:
1135: *alocc='\0';
1136: return s;
1137: }
1138:
1.126 brouard 1139: int nbocc(char *s, char occ)
1140: {
1141: int i,j=0;
1142: int lg=20;
1143: i=0;
1144: lg=strlen(s);
1145: for(i=0; i<= lg; i++) {
1146: if (s[i] == occ ) j++;
1147: }
1148: return j;
1149: }
1150:
1.137 brouard 1151: /* void cutv(char *u,char *v, char*t, char occ) */
1152: /* { */
1153: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1154: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1155: /* gives u="abcdef2ghi" and v="j" *\/ */
1156: /* int i,lg,j,p=0; */
1157: /* i=0; */
1158: /* lg=strlen(t); */
1159: /* for(j=0; j<=lg-1; j++) { */
1160: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1161: /* } */
1.126 brouard 1162:
1.137 brouard 1163: /* for(j=0; j<p; j++) { */
1164: /* (u[j] = t[j]); */
1165: /* } */
1166: /* u[p]='\0'; */
1.126 brouard 1167:
1.137 brouard 1168: /* for(j=0; j<= lg; j++) { */
1169: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1170: /* } */
1171: /* } */
1.126 brouard 1172:
1.160 brouard 1173: #ifdef _WIN32
1174: char * strsep(char **pp, const char *delim)
1175: {
1176: char *p, *q;
1177:
1178: if ((p = *pp) == NULL)
1179: return 0;
1180: if ((q = strpbrk (p, delim)) != NULL)
1181: {
1182: *pp = q + 1;
1183: *q = '\0';
1184: }
1185: else
1186: *pp = 0;
1187: return p;
1188: }
1189: #endif
1190:
1.126 brouard 1191: /********************** nrerror ********************/
1192:
1193: void nrerror(char error_text[])
1194: {
1195: fprintf(stderr,"ERREUR ...\n");
1196: fprintf(stderr,"%s\n",error_text);
1197: exit(EXIT_FAILURE);
1198: }
1199: /*********************** vector *******************/
1200: double *vector(int nl, int nh)
1201: {
1202: double *v;
1203: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1204: if (!v) nrerror("allocation failure in vector");
1205: return v-nl+NR_END;
1206: }
1207:
1208: /************************ free vector ******************/
1209: void free_vector(double*v, int nl, int nh)
1210: {
1211: free((FREE_ARG)(v+nl-NR_END));
1212: }
1213:
1214: /************************ivector *******************************/
1215: int *ivector(long nl,long nh)
1216: {
1217: int *v;
1218: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1219: if (!v) nrerror("allocation failure in ivector");
1220: return v-nl+NR_END;
1221: }
1222:
1223: /******************free ivector **************************/
1224: void free_ivector(int *v, long nl, long nh)
1225: {
1226: free((FREE_ARG)(v+nl-NR_END));
1227: }
1228:
1229: /************************lvector *******************************/
1230: long *lvector(long nl,long nh)
1231: {
1232: long *v;
1233: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1234: if (!v) nrerror("allocation failure in ivector");
1235: return v-nl+NR_END;
1236: }
1237:
1238: /******************free lvector **************************/
1239: void free_lvector(long *v, long nl, long nh)
1240: {
1241: free((FREE_ARG)(v+nl-NR_END));
1242: }
1243:
1244: /******************* imatrix *******************************/
1245: int **imatrix(long nrl, long nrh, long ncl, long nch)
1246: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1247: {
1248: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1249: int **m;
1250:
1251: /* allocate pointers to rows */
1252: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1253: if (!m) nrerror("allocation failure 1 in matrix()");
1254: m += NR_END;
1255: m -= nrl;
1256:
1257:
1258: /* allocate rows and set pointers to them */
1259: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
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: /* return pointer to array of pointers to rows */
1267: return m;
1268: }
1269:
1270: /****************** free_imatrix *************************/
1271: void free_imatrix(m,nrl,nrh,ncl,nch)
1272: int **m;
1273: long nch,ncl,nrh,nrl;
1274: /* free an int matrix allocated by imatrix() */
1275: {
1276: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1277: free((FREE_ARG) (m+nrl-NR_END));
1278: }
1279:
1280: /******************* matrix *******************************/
1281: double **matrix(long nrl, long nrh, long ncl, long nch)
1282: {
1283: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1284: double **m;
1285:
1286: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1287: if (!m) nrerror("allocation failure 1 in matrix()");
1288: m += NR_END;
1289: m -= nrl;
1290:
1291: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1292: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1293: m[nrl] += NR_END;
1294: m[nrl] -= ncl;
1295:
1296: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1297: return m;
1.145 brouard 1298: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1299: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1300: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1301: */
1302: }
1303:
1304: /*************************free matrix ************************/
1305: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1306: {
1307: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1308: free((FREE_ARG)(m+nrl-NR_END));
1309: }
1310:
1311: /******************* ma3x *******************************/
1312: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1313: {
1314: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1315: double ***m;
1316:
1317: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1318: if (!m) nrerror("allocation failure 1 in matrix()");
1319: m += NR_END;
1320: m -= nrl;
1321:
1322: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1323: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1324: m[nrl] += NR_END;
1325: m[nrl] -= ncl;
1326:
1327: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1328:
1329: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1330: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1331: m[nrl][ncl] += NR_END;
1332: m[nrl][ncl] -= nll;
1333: for (j=ncl+1; j<=nch; j++)
1334: m[nrl][j]=m[nrl][j-1]+nlay;
1335:
1336: for (i=nrl+1; i<=nrh; i++) {
1337: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1338: for (j=ncl+1; j<=nch; j++)
1339: m[i][j]=m[i][j-1]+nlay;
1340: }
1341: return m;
1342: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1343: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1344: */
1345: }
1346:
1347: /*************************free ma3x ************************/
1348: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1349: {
1350: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1351: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1352: free((FREE_ARG)(m+nrl-NR_END));
1353: }
1354:
1355: /*************** function subdirf ***********/
1356: char *subdirf(char fileres[])
1357: {
1358: /* Caution optionfilefiname is hidden */
1359: strcpy(tmpout,optionfilefiname);
1360: strcat(tmpout,"/"); /* Add to the right */
1361: strcat(tmpout,fileres);
1362: return tmpout;
1363: }
1364:
1365: /*************** function subdirf2 ***********/
1366: char *subdirf2(char fileres[], char *preop)
1367: {
1368:
1369: /* Caution optionfilefiname is hidden */
1370: strcpy(tmpout,optionfilefiname);
1371: strcat(tmpout,"/");
1372: strcat(tmpout,preop);
1373: strcat(tmpout,fileres);
1374: return tmpout;
1375: }
1376:
1377: /*************** function subdirf3 ***********/
1378: char *subdirf3(char fileres[], char *preop, char *preop2)
1379: {
1380:
1381: /* Caution optionfilefiname is hidden */
1382: strcpy(tmpout,optionfilefiname);
1383: strcat(tmpout,"/");
1384: strcat(tmpout,preop);
1385: strcat(tmpout,preop2);
1386: strcat(tmpout,fileres);
1387: return tmpout;
1388: }
1.213 ! brouard 1389:
! 1390: /*************** function subdirfext ***********/
! 1391: char *subdirfext(char fileres[], char *preop, char *postop)
! 1392: {
! 1393:
! 1394: strcpy(tmpout,preop);
! 1395: strcat(tmpout,fileres);
! 1396: strcat(tmpout,postop);
! 1397: return tmpout;
! 1398: }
1.126 brouard 1399:
1.213 ! brouard 1400: /*************** function subdirfext3 ***********/
! 1401: char *subdirfext3(char fileres[], char *preop, char *postop)
! 1402: {
! 1403:
! 1404: /* Caution optionfilefiname is hidden */
! 1405: strcpy(tmpout,optionfilefiname);
! 1406: strcat(tmpout,"/");
! 1407: strcat(tmpout,preop);
! 1408: strcat(tmpout,fileres);
! 1409: strcat(tmpout,postop);
! 1410: return tmpout;
! 1411: }
! 1412:
1.162 brouard 1413: char *asc_diff_time(long time_sec, char ascdiff[])
1414: {
1415: long sec_left, days, hours, minutes;
1416: days = (time_sec) / (60*60*24);
1417: sec_left = (time_sec) % (60*60*24);
1418: hours = (sec_left) / (60*60) ;
1419: sec_left = (sec_left) %(60*60);
1420: minutes = (sec_left) /60;
1421: sec_left = (sec_left) % (60);
1422: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1423: return ascdiff;
1424: }
1425:
1.126 brouard 1426: /***************** f1dim *************************/
1427: extern int ncom;
1428: extern double *pcom,*xicom;
1429: extern double (*nrfunc)(double []);
1430:
1431: double f1dim(double x)
1432: {
1433: int j;
1434: double f;
1435: double *xt;
1436:
1437: xt=vector(1,ncom);
1438: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1439: f=(*nrfunc)(xt);
1440: free_vector(xt,1,ncom);
1441: return f;
1442: }
1443:
1444: /*****************brent *************************/
1445: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1446: {
1447: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1448: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1449: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1450: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1451: * returned function value.
1452: */
1.126 brouard 1453: int iter;
1454: double a,b,d,etemp;
1.159 brouard 1455: double fu=0,fv,fw,fx;
1.164 brouard 1456: double ftemp=0.;
1.126 brouard 1457: double p,q,r,tol1,tol2,u,v,w,x,xm;
1458: double e=0.0;
1459:
1460: a=(ax < cx ? ax : cx);
1461: b=(ax > cx ? ax : cx);
1462: x=w=v=bx;
1463: fw=fv=fx=(*f)(x);
1464: for (iter=1;iter<=ITMAX;iter++) {
1465: xm=0.5*(a+b);
1466: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1467: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1468: printf(".");fflush(stdout);
1469: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1470: #ifdef DEBUGBRENT
1.126 brouard 1471: 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);
1472: 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);
1473: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1474: #endif
1475: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1476: *xmin=x;
1477: return fx;
1478: }
1479: ftemp=fu;
1480: if (fabs(e) > tol1) {
1481: r=(x-w)*(fx-fv);
1482: q=(x-v)*(fx-fw);
1483: p=(x-v)*q-(x-w)*r;
1484: q=2.0*(q-r);
1485: if (q > 0.0) p = -p;
1486: q=fabs(q);
1487: etemp=e;
1488: e=d;
1489: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1490: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1491: else {
1492: d=p/q;
1493: u=x+d;
1494: if (u-a < tol2 || b-u < tol2)
1495: d=SIGN(tol1,xm-x);
1496: }
1497: } else {
1498: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1499: }
1500: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1501: fu=(*f)(u);
1502: if (fu <= fx) {
1503: if (u >= x) a=x; else b=x;
1504: SHFT(v,w,x,u)
1.183 brouard 1505: SHFT(fv,fw,fx,fu)
1506: } else {
1507: if (u < x) a=u; else b=u;
1508: if (fu <= fw || w == x) {
1509: v=w;
1510: w=u;
1511: fv=fw;
1512: fw=fu;
1513: } else if (fu <= fv || v == x || v == w) {
1514: v=u;
1515: fv=fu;
1516: }
1517: }
1.126 brouard 1518: }
1519: nrerror("Too many iterations in brent");
1520: *xmin=x;
1521: return fx;
1522: }
1523:
1524: /****************** mnbrak ***********************/
1525:
1526: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1527: double (*func)(double))
1.183 brouard 1528: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1529: the downhill direction (defined by the function as evaluated at the initial points) and returns
1530: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1531: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1532: */
1.126 brouard 1533: double ulim,u,r,q, dum;
1534: double fu;
1.187 brouard 1535:
1536: double scale=10.;
1537: int iterscale=0;
1538:
1539: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1540: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1541:
1542:
1543: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1544: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1545: /* *bx = *ax - (*ax - *bx)/scale; */
1546: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1547: /* } */
1548:
1.126 brouard 1549: if (*fb > *fa) {
1550: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1551: SHFT(dum,*fb,*fa,dum)
1552: }
1.126 brouard 1553: *cx=(*bx)+GOLD*(*bx-*ax);
1554: *fc=(*func)(*cx);
1.183 brouard 1555: #ifdef DEBUG
1556: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1557: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1558: #endif
1559: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1560: r=(*bx-*ax)*(*fb-*fc);
1561: q=(*bx-*cx)*(*fb-*fa);
1562: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1563: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1564: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1565: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1566: fu=(*func)(u);
1.163 brouard 1567: #ifdef DEBUG
1568: /* f(x)=A(x-u)**2+f(u) */
1569: double A, fparabu;
1570: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1571: fparabu= *fa - A*(*ax-u)*(*ax-u);
1572: 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);
1573: 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 1574: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1575: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1576: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1577: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1578: #endif
1.184 brouard 1579: #ifdef MNBRAKORIGINAL
1.183 brouard 1580: #else
1.191 brouard 1581: /* if (fu > *fc) { */
1582: /* #ifdef DEBUG */
1583: /* printf("mnbrak4 fu > fc \n"); */
1584: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1585: /* #endif */
1586: /* /\* 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 *\\/ *\/ */
1587: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1588: /* dum=u; /\* Shifting c and u *\/ */
1589: /* u = *cx; */
1590: /* *cx = dum; */
1591: /* dum = fu; */
1592: /* fu = *fc; */
1593: /* *fc =dum; */
1594: /* } else { /\* end *\/ */
1595: /* #ifdef DEBUG */
1596: /* printf("mnbrak3 fu < fc \n"); */
1597: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1598: /* #endif */
1599: /* dum=u; /\* Shifting c and u *\/ */
1600: /* u = *cx; */
1601: /* *cx = dum; */
1602: /* dum = fu; */
1603: /* fu = *fc; */
1604: /* *fc =dum; */
1605: /* } */
1.183 brouard 1606: #ifdef DEBUG
1.191 brouard 1607: printf("mnbrak34 fu < or >= fc \n");
1608: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1609: #endif
1.191 brouard 1610: dum=u; /* Shifting c and u */
1611: u = *cx;
1612: *cx = dum;
1613: dum = fu;
1614: fu = *fc;
1615: *fc =dum;
1.183 brouard 1616: #endif
1.162 brouard 1617: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1618: #ifdef DEBUG
1619: printf("mnbrak2 u after c but before ulim\n");
1620: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1621: #endif
1.126 brouard 1622: fu=(*func)(u);
1623: if (fu < *fc) {
1.183 brouard 1624: #ifdef DEBUG
1625: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1626: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1627: #endif
1.126 brouard 1628: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1629: SHFT(*fb,*fc,fu,(*func)(u))
1630: }
1.162 brouard 1631: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1632: #ifdef DEBUG
1633: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1634: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1635: #endif
1.126 brouard 1636: u=ulim;
1637: fu=(*func)(u);
1.183 brouard 1638: } else { /* u could be left to b (if r > q parabola has a maximum) */
1639: #ifdef DEBUG
1640: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1641: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1642: #endif
1.126 brouard 1643: u=(*cx)+GOLD*(*cx-*bx);
1644: fu=(*func)(u);
1.183 brouard 1645: } /* end tests */
1.126 brouard 1646: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1647: SHFT(*fa,*fb,*fc,fu)
1648: #ifdef DEBUG
1649: 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);
1650: 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);
1651: #endif
1652: } /* 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 1653: }
1654:
1655: /*************** linmin ************************/
1.162 brouard 1656: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1657: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1658: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1659: the value of func at the returned location p . This is actually all accomplished by calling the
1660: routines mnbrak and brent .*/
1.126 brouard 1661: int ncom;
1662: double *pcom,*xicom;
1663: double (*nrfunc)(double []);
1664:
1665: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1666: {
1667: double brent(double ax, double bx, double cx,
1668: double (*f)(double), double tol, double *xmin);
1669: double f1dim(double x);
1670: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1671: double *fc, double (*func)(double));
1672: int j;
1673: double xx,xmin,bx,ax;
1674: double fx,fb,fa;
1.187 brouard 1675:
1.203 brouard 1676: #ifdef LINMINORIGINAL
1677: #else
1678: double scale=10., axs, xxs; /* Scale added for infinity */
1679: #endif
1680:
1.126 brouard 1681: ncom=n;
1682: pcom=vector(1,n);
1683: xicom=vector(1,n);
1684: nrfunc=func;
1685: for (j=1;j<=n;j++) {
1686: pcom[j]=p[j];
1.202 brouard 1687: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126 brouard 1688: }
1.187 brouard 1689:
1.203 brouard 1690: #ifdef LINMINORIGINAL
1691: xx=1.;
1692: #else
1693: axs=0.0;
1694: xxs=1.;
1695: do{
1696: xx= xxs;
1697: #endif
1.187 brouard 1698: ax=0.;
1699: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1700: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1701: /* 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)) */
1702: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1703: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1704: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1705: /* 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.203 brouard 1706: #ifdef LINMINORIGINAL
1707: #else
1708: if (fx != fx){
1709: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1710: printf("|");
1711: fprintf(ficlog,"|");
1712: #ifdef DEBUGLINMIN
1713: 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);
1714: #endif
1715: }
1716: }while(fx != fx);
1717: #endif
1718:
1.191 brouard 1719: #ifdef DEBUGLINMIN
1720: 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);
1.202 brouard 1721: fprintf(ficlog,"\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);
1.191 brouard 1722: #endif
1.187 brouard 1723: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1724: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1725: /* fmin = f(p[j] + xmin * xi[j]) */
1726: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1727: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1728: #ifdef DEBUG
1729: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1730: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1731: #endif
1.191 brouard 1732: #ifdef DEBUGLINMIN
1733: printf("linmin end ");
1.202 brouard 1734: fprintf(ficlog,"linmin end ");
1.191 brouard 1735: #endif
1.126 brouard 1736: for (j=1;j<=n;j++) {
1.203 brouard 1737: #ifdef LINMINORIGINAL
1738: xi[j] *= xmin;
1739: #else
1740: #ifdef DEBUGLINMIN
1741: if(xxs <1.0)
1742: printf(" before xi[%d]=%12.8f", j,xi[j]);
1743: #endif
1744: xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1745: #ifdef DEBUGLINMIN
1746: if(xxs <1.0)
1747: 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 );
1748: #endif
1749: #endif
1.187 brouard 1750: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1751: }
1.191 brouard 1752: #ifdef DEBUGLINMIN
1.203 brouard 1753: printf("\n");
1.191 brouard 1754: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202 brouard 1755: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191 brouard 1756: for (j=1;j<=n;j++) {
1.202 brouard 1757: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1758: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1759: if(j % ncovmodel == 0){
1.191 brouard 1760: printf("\n");
1.202 brouard 1761: fprintf(ficlog,"\n");
1762: }
1.191 brouard 1763: }
1.203 brouard 1764: #else
1.191 brouard 1765: #endif
1.126 brouard 1766: free_vector(xicom,1,n);
1767: free_vector(pcom,1,n);
1768: }
1769:
1770:
1771: /*************** powell ************************/
1.162 brouard 1772: /*
1773: Minimization of a function func of n variables. Input consists of an initial starting point
1774: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1775: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1776: such that failure to decrease by more than this amount on one iteration signals doneness. On
1777: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1778: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1779: */
1.126 brouard 1780: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1781: double (*func)(double []))
1782: {
1783: void linmin(double p[], double xi[], int n, double *fret,
1784: double (*func)(double []));
1785: int i,ibig,j;
1786: double del,t,*pt,*ptt,*xit;
1.181 brouard 1787: double directest;
1.126 brouard 1788: double fp,fptt;
1789: double *xits;
1790: int niterf, itmp;
1791:
1792: pt=vector(1,n);
1793: ptt=vector(1,n);
1794: xit=vector(1,n);
1795: xits=vector(1,n);
1796: *fret=(*func)(p);
1797: for (j=1;j<=n;j++) pt[j]=p[j];
1.202 brouard 1798: rcurr_time = time(NULL);
1.126 brouard 1799: for (*iter=1;;++(*iter)) {
1.187 brouard 1800: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1801: ibig=0;
1802: del=0.0;
1.157 brouard 1803: rlast_time=rcurr_time;
1804: /* (void) gettimeofday(&curr_time,&tzp); */
1805: rcurr_time = time(NULL);
1806: curr_time = *localtime(&rcurr_time);
1807: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1808: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1809: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1810: for (i=1;i<=n;i++) {
1.126 brouard 1811: printf(" %d %.12f",i, p[i]);
1812: fprintf(ficlog," %d %.12lf",i, p[i]);
1813: fprintf(ficrespow," %.12lf", p[i]);
1814: }
1815: printf("\n");
1816: fprintf(ficlog,"\n");
1817: fprintf(ficrespow,"\n");fflush(ficrespow);
1818: if(*iter <=3){
1.157 brouard 1819: tml = *localtime(&rcurr_time);
1820: strcpy(strcurr,asctime(&tml));
1821: rforecast_time=rcurr_time;
1.126 brouard 1822: itmp = strlen(strcurr);
1823: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1824: strcurr[itmp-1]='\0';
1.162 brouard 1825: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1826: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1827: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1828: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1829: forecast_time = *localtime(&rforecast_time);
1830: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1831: itmp = strlen(strfor);
1832: if(strfor[itmp-1]=='\n')
1833: strfor[itmp-1]='\0';
1.157 brouard 1834: 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);
1835: 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 1836: }
1837: }
1.187 brouard 1838: for (i=1;i<=n;i++) { /* For each direction i */
1839: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1840: fptt=(*fret);
1841: #ifdef DEBUG
1.203 brouard 1842: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1843: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1844: #endif
1.203 brouard 1845: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1846: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1847: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1848: /* Outputs are fret(new point p) p is updated and xit rescaled */
1849: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1850: /* because that direction will be replaced unless the gain del is small */
1851: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1852: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1853: /* with the new direction. */
1.126 brouard 1854: del=fabs(fptt-(*fret));
1855: ibig=i;
1856: }
1857: #ifdef DEBUG
1858: printf("%d %.12e",i,(*fret));
1859: fprintf(ficlog,"%d %.12e",i,(*fret));
1860: for (j=1;j<=n;j++) {
1861: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1862: printf(" x(%d)=%.12e",j,xit[j]);
1863: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1864: }
1865: for(j=1;j<=n;j++) {
1.162 brouard 1866: printf(" p(%d)=%.12e",j,p[j]);
1867: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1868: }
1869: printf("\n");
1870: fprintf(ficlog,"\n");
1871: #endif
1.187 brouard 1872: } /* end loop on each direction i */
1873: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1874: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1875: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1876: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1877: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1878: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1879: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1880: /* decreased of more than 3.84 */
1881: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1882: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1883: /* By adding 10 parameters more the gain should be 18.31 */
1884:
1885: /* Starting the program with initial values given by a former maximization will simply change */
1886: /* the scales of the directions and the directions, because the are reset to canonical directions */
1887: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1888: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1889: #ifdef DEBUG
1890: int k[2],l;
1891: k[0]=1;
1892: k[1]=-1;
1893: printf("Max: %.12e",(*func)(p));
1894: fprintf(ficlog,"Max: %.12e",(*func)(p));
1895: for (j=1;j<=n;j++) {
1896: printf(" %.12e",p[j]);
1897: fprintf(ficlog," %.12e",p[j]);
1898: }
1899: printf("\n");
1900: fprintf(ficlog,"\n");
1901: for(l=0;l<=1;l++) {
1902: for (j=1;j<=n;j++) {
1903: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1904: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1905: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1906: }
1907: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1908: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1909: }
1910: #endif
1911:
1912:
1913: free_vector(xit,1,n);
1914: free_vector(xits,1,n);
1915: free_vector(ptt,1,n);
1916: free_vector(pt,1,n);
1917: return;
1.192 brouard 1918: } /* enough precision */
1.126 brouard 1919: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1920: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1921: ptt[j]=2.0*p[j]-pt[j];
1922: xit[j]=p[j]-pt[j];
1923: pt[j]=p[j];
1924: }
1.181 brouard 1925: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1926: #ifdef POWELLF1F3
1927: #else
1.161 brouard 1928: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1929: #endif
1.162 brouard 1930: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1931: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1932: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1933: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1934: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1935: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1936: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1937: #ifdef NRCORIGINAL
1938: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1939: #else
1940: 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 1941: t= t- del*SQR(fp-fptt);
1.183 brouard 1942: #endif
1.202 brouard 1943: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161 brouard 1944: #ifdef DEBUG
1.181 brouard 1945: 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);
1946: 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 1947: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1948: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1949: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1950: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1951: 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);
1952: 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);
1953: #endif
1.183 brouard 1954: #ifdef POWELLORIGINAL
1955: if (t < 0.0) { /* Then we use it for new direction */
1956: #else
1.182 brouard 1957: if (directest*t < 0.0) { /* Contradiction between both tests */
1.202 brouard 1958: printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.192 brouard 1959: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202 brouard 1960: fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.192 brouard 1961: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1962: }
1.181 brouard 1963: if (directest < 0.0) { /* Then we use it for new direction */
1964: #endif
1.191 brouard 1965: #ifdef DEBUGLINMIN
1966: printf("Before linmin in direction P%d-P0\n",n);
1967: for (j=1;j<=n;j++) {
1.202 brouard 1968: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1969: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1970: if(j % ncovmodel == 0){
1.191 brouard 1971: printf("\n");
1.202 brouard 1972: fprintf(ficlog,"\n");
1973: }
1.191 brouard 1974: }
1975: #endif
1.187 brouard 1976: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1977: #ifdef DEBUGLINMIN
1978: for (j=1;j<=n;j++) {
1979: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202 brouard 1980: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1981: if(j % ncovmodel == 0){
1.191 brouard 1982: printf("\n");
1.202 brouard 1983: fprintf(ficlog,"\n");
1984: }
1.191 brouard 1985: }
1986: #endif
1.126 brouard 1987: for (j=1;j<=n;j++) {
1.181 brouard 1988: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1989: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1990: }
1.181 brouard 1991: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1992: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1993:
1.126 brouard 1994: #ifdef DEBUG
1.164 brouard 1995: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1996: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1997: for(j=1;j<=n;j++){
1998: printf(" %.12e",xit[j]);
1999: fprintf(ficlog," %.12e",xit[j]);
2000: }
2001: printf("\n");
2002: fprintf(ficlog,"\n");
2003: #endif
1.192 brouard 2004: } /* end of t or directest negative */
2005: #ifdef POWELLF1F3
2006: #else
1.162 brouard 2007: } /* end if (fptt < fp) */
1.192 brouard 2008: #endif
2009: } /* loop iteration */
1.126 brouard 2010: }
2011:
2012: /**** Prevalence limit (stable or period prevalence) ****************/
2013:
1.203 brouard 2014: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126 brouard 2015: {
2016: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203 brouard 2017: matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206 brouard 2018: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2019: /* Wx is row vector: population in state 1, population in state 2, population dead */
2020: /* or prevalence in state 1, prevalence in state 2, 0 */
2021: /* newm is the matrix after multiplications, its rows are identical at a factor */
2022: /* Initial matrix pimij */
2023: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2024: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2025: /* 0, 0 , 1} */
2026: /*
2027: * and after some iteration: */
2028: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2029: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2030: /* 0, 0 , 1} */
2031: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2032: /* {0.51571254859325999, 0.4842874514067399, */
2033: /* 0.51326036147820708, 0.48673963852179264} */
2034: /* If we start from prlim again, prlim tends to a constant matrix */
2035:
1.126 brouard 2036: int i, ii,j,k;
1.209 brouard 2037: double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145 brouard 2038: /* double **matprod2(); */ /* test */
1.131 brouard 2039: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 2040: double **newm;
1.209 brouard 2041: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203 brouard 2042: int ncvloop=0;
1.169 brouard 2043:
1.209 brouard 2044: min=vector(1,nlstate);
2045: max=vector(1,nlstate);
2046: meandiff=vector(1,nlstate);
2047:
1.126 brouard 2048: for (ii=1;ii<=nlstate+ndeath;ii++)
2049: for (j=1;j<=nlstate+ndeath;j++){
2050: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2051: }
1.169 brouard 2052:
2053: cov[1]=1.;
2054:
2055: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202 brouard 2056: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126 brouard 2057: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202 brouard 2058: ncvloop++;
1.126 brouard 2059: newm=savm;
2060: /* Covariates have to be included here again */
1.138 brouard 2061: cov[2]=agefin;
1.187 brouard 2062: if(nagesqr==1)
2063: cov[3]= agefin*agefin;;
1.138 brouard 2064: for (k=1; k<=cptcovn;k++) {
1.200 brouard 2065: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2066: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198 brouard 2067: /* 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 2068: }
1.186 brouard 2069: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 2070: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2071: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186 brouard 2072: for (k=1; k<=cptcovprod;k++) /* Useless */
1.200 brouard 2073: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2074: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138 brouard 2075:
2076: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2077: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2078: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 2079: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2080: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 2081: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 2082:
1.126 brouard 2083: savm=oldm;
2084: oldm=newm;
1.209 brouard 2085:
2086: for(j=1; j<=nlstate; j++){
2087: max[j]=0.;
2088: min[j]=1.;
2089: }
2090: for(i=1;i<=nlstate;i++){
2091: sumnew=0;
2092: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2093: for(j=1; j<=nlstate; j++){
2094: prlim[i][j]= newm[i][j]/(1-sumnew);
2095: max[j]=FMAX(max[j],prlim[i][j]);
2096: min[j]=FMIN(min[j],prlim[i][j]);
2097: }
2098: }
2099:
1.126 brouard 2100: maxmax=0.;
1.209 brouard 2101: for(j=1; j<=nlstate; j++){
2102: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2103: maxmax=FMAX(maxmax,meandiff[j]);
2104: /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
1.169 brouard 2105: } /* j loop */
1.203 brouard 2106: *ncvyear= (int)age- (int)agefin;
1.208 brouard 2107: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126 brouard 2108: if(maxmax < ftolpl){
1.209 brouard 2109: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2110: free_vector(min,1,nlstate);
2111: free_vector(max,1,nlstate);
2112: free_vector(meandiff,1,nlstate);
1.126 brouard 2113: return prlim;
2114: }
1.169 brouard 2115: } /* age loop */
1.208 brouard 2116: /* After some age loop it doesn't converge */
1.209 brouard 2117: printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.208 brouard 2118: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
1.209 brouard 2119: /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
2120: free_vector(min,1,nlstate);
2121: free_vector(max,1,nlstate);
2122: free_vector(meandiff,1,nlstate);
1.208 brouard 2123:
1.169 brouard 2124: return prlim; /* should not reach here */
1.126 brouard 2125: }
2126:
2127: /*************** transition probabilities ***************/
2128:
2129: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2130: {
1.138 brouard 2131: /* According to parameters values stored in x and the covariate's values stored in cov,
2132: computes the probability to be observed in state j being in state i by appying the
2133: model to the ncovmodel covariates (including constant and age).
2134: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2135: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2136: ncth covariate in the global vector x is given by the formula:
2137: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2138: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2139: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2140: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2141: Outputs ps[i][j] the probability to be observed in j being in j according to
2142: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2143: */
2144: double s1, lnpijopii;
1.126 brouard 2145: /*double t34;*/
1.164 brouard 2146: int i,j, nc, ii, jj;
1.126 brouard 2147:
2148: for(i=1; i<= nlstate; i++){
2149: for(j=1; j<i;j++){
1.138 brouard 2150: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2151: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2152: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2153: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2154: }
1.138 brouard 2155: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2156: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2157: }
2158: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 2159: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2160: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2161: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2162: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 2163: }
1.138 brouard 2164: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 2165: }
2166: }
2167:
2168: for(i=1; i<= nlstate; i++){
2169: s1=0;
1.131 brouard 2170: for(j=1; j<i; j++){
1.138 brouard 2171: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2172: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2173: }
2174: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 2175: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2176: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2177: }
1.138 brouard 2178: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 2179: ps[i][i]=1./(s1+1.);
1.138 brouard 2180: /* Computing other pijs */
1.126 brouard 2181: for(j=1; j<i; j++)
2182: ps[i][j]= exp(ps[i][j])*ps[i][i];
2183: for(j=i+1; j<=nlstate+ndeath; j++)
2184: ps[i][j]= exp(ps[i][j])*ps[i][i];
2185: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2186: } /* end i */
2187:
2188: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2189: for(jj=1; jj<= nlstate+ndeath; jj++){
2190: ps[ii][jj]=0;
2191: ps[ii][ii]=1;
2192: }
2193: }
2194:
1.145 brouard 2195:
2196: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2197: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2198: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2199: /* } */
2200: /* printf("\n "); */
2201: /* } */
2202: /* printf("\n ");printf("%lf ",cov[2]);*/
2203: /*
1.126 brouard 2204: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2205: goto end;*/
2206: return ps;
2207: }
2208:
2209: /**************** Product of 2 matrices ******************/
2210:
1.145 brouard 2211: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2212: {
2213: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2214: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2215: /* in, b, out are matrice of pointers which should have been initialized
2216: before: only the contents of out is modified. The function returns
2217: a pointer to pointers identical to out */
1.145 brouard 2218: int i, j, k;
1.126 brouard 2219: for(i=nrl; i<= nrh; i++)
1.145 brouard 2220: for(k=ncolol; k<=ncoloh; k++){
2221: out[i][k]=0.;
2222: for(j=ncl; j<=nch; j++)
2223: out[i][k] +=in[i][j]*b[j][k];
2224: }
1.126 brouard 2225: return out;
2226: }
2227:
2228:
2229: /************* Higher Matrix Product ***************/
2230:
2231: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2232: {
2233: /* Computes the transition matrix starting at age 'age' over
2234: 'nhstepm*hstepm*stepm' months (i.e. until
2235: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2236: nhstepm*hstepm matrices.
2237: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2238: (typically every 2 years instead of every month which is too big
2239: for the memory).
2240: Model is determined by parameters x and covariates have to be
2241: included manually here.
2242:
2243: */
2244:
2245: int i, j, d, h, k;
1.131 brouard 2246: double **out, cov[NCOVMAX+1];
1.126 brouard 2247: double **newm;
1.187 brouard 2248: double agexact;
1.126 brouard 2249:
2250: /* Hstepm could be zero and should return the unit matrix */
2251: for (i=1;i<=nlstate+ndeath;i++)
2252: for (j=1;j<=nlstate+ndeath;j++){
2253: oldm[i][j]=(i==j ? 1.0 : 0.0);
2254: po[i][j][0]=(i==j ? 1.0 : 0.0);
2255: }
2256: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2257: for(h=1; h <=nhstepm; h++){
2258: for(d=1; d <=hstepm; d++){
2259: newm=savm;
2260: /* Covariates have to be included here again */
2261: cov[1]=1.;
1.187 brouard 2262: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2263: cov[2]=agexact;
2264: if(nagesqr==1)
2265: cov[3]= agexact*agexact;
1.131 brouard 2266: for (k=1; k<=cptcovn;k++)
1.200 brouard 2267: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2268: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186 brouard 2269: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2270: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 2271: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2272: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145 brouard 2273: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200 brouard 2274: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2275: /* 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 2276:
2277:
2278: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2279: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2280: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2281: pmij(pmmij,cov,ncovmodel,x,nlstate));
2282: savm=oldm;
2283: oldm=newm;
2284: }
2285: for(i=1; i<=nlstate+ndeath; i++)
2286: for(j=1;j<=nlstate+ndeath;j++) {
2287: po[i][j][h]=newm[i][j];
1.128 brouard 2288: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2289: }
1.128 brouard 2290: /*printf("h=%d ",h);*/
1.126 brouard 2291: } /* end h */
1.128 brouard 2292: /* printf("\n H=%d \n",h); */
1.126 brouard 2293: return po;
2294: }
2295:
1.162 brouard 2296: #ifdef NLOPT
2297: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2298: double fret;
2299: double *xt;
2300: int j;
2301: myfunc_data *d2 = (myfunc_data *) pd;
2302: /* xt = (p1-1); */
2303: xt=vector(1,n);
2304: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2305:
2306: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2307: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2308: printf("Function = %.12lf ",fret);
2309: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2310: printf("\n");
2311: free_vector(xt,1,n);
2312: return fret;
2313: }
2314: #endif
1.126 brouard 2315:
2316: /*************** log-likelihood *************/
2317: double func( double *x)
2318: {
2319: int i, ii, j, k, mi, d, kk;
1.131 brouard 2320: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2321: double **out;
2322: double sw; /* Sum of weights */
2323: double lli; /* Individual log likelihood */
2324: int s1, s2;
2325: double bbh, survp;
2326: long ipmx;
1.187 brouard 2327: double agexact;
1.126 brouard 2328: /*extern weight */
2329: /* We are differentiating ll according to initial status */
2330: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2331: /*for(i=1;i<imx;i++)
2332: printf(" %d\n",s[4][i]);
2333: */
1.162 brouard 2334:
2335: ++countcallfunc;
2336:
1.126 brouard 2337: cov[1]=1.;
2338:
2339: for(k=1; k<=nlstate; k++) ll[k]=0.;
2340:
2341: if(mle==1){
2342: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2343: /* Computes the values of the ncovmodel covariates of the model
2344: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2345: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2346: to be observed in j being in i according to the model.
2347: */
1.145 brouard 2348: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2349: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2350: }
1.137 brouard 2351: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2352: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2353: has been calculated etc */
1.126 brouard 2354: for(mi=1; mi<= wav[i]-1; mi++){
2355: for (ii=1;ii<=nlstate+ndeath;ii++)
2356: for (j=1;j<=nlstate+ndeath;j++){
2357: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2358: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2359: }
2360: for(d=0; d<dh[mi][i]; d++){
2361: newm=savm;
1.187 brouard 2362: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2363: cov[2]=agexact;
2364: if(nagesqr==1)
2365: cov[3]= agexact*agexact;
1.126 brouard 2366: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2367: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2368: }
2369: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2370: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2371: savm=oldm;
2372: oldm=newm;
2373: } /* end mult */
2374:
2375: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2376: /* But now since version 0.9 we anticipate for bias at large stepm.
2377: * If stepm is larger than one month (smallest stepm) and if the exact delay
2378: * (in months) between two waves is not a multiple of stepm, we rounded to
2379: * the nearest (and in case of equal distance, to the lowest) interval but now
2380: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2381: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2382: * probability in order to take into account the bias as a fraction of the way
2383: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2384: * -stepm/2 to stepm/2 .
2385: * For stepm=1 the results are the same as for previous versions of Imach.
2386: * For stepm > 1 the results are less biased than in previous versions.
2387: */
2388: s1=s[mw[mi][i]][i];
2389: s2=s[mw[mi+1][i]][i];
2390: bbh=(double)bh[mi][i]/(double)stepm;
2391: /* bias bh is positive if real duration
2392: * is higher than the multiple of stepm and negative otherwise.
2393: */
2394: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2395: if( s2 > nlstate){
2396: /* i.e. if s2 is a death state and if the date of death is known
2397: then the contribution to the likelihood is the probability to
2398: die between last step unit time and current step unit time,
2399: which is also equal to probability to die before dh
2400: minus probability to die before dh-stepm .
2401: In version up to 0.92 likelihood was computed
2402: as if date of death was unknown. Death was treated as any other
2403: health state: the date of the interview describes the actual state
2404: and not the date of a change in health state. The former idea was
2405: to consider that at each interview the state was recorded
2406: (healthy, disable or death) and IMaCh was corrected; but when we
2407: introduced the exact date of death then we should have modified
2408: the contribution of an exact death to the likelihood. This new
2409: contribution is smaller and very dependent of the step unit
2410: stepm. It is no more the probability to die between last interview
2411: and month of death but the probability to survive from last
2412: interview up to one month before death multiplied by the
2413: probability to die within a month. Thanks to Chris
2414: Jackson for correcting this bug. Former versions increased
2415: mortality artificially. The bad side is that we add another loop
2416: which slows down the processing. The difference can be up to 10%
2417: lower mortality.
2418: */
1.183 brouard 2419: /* If, at the beginning of the maximization mostly, the
2420: cumulative probability or probability to be dead is
2421: constant (ie = 1) over time d, the difference is equal to
2422: 0. out[s1][3] = savm[s1][3]: probability, being at state
2423: s1 at precedent wave, to be dead a month before current
2424: wave is equal to probability, being at state s1 at
2425: precedent wave, to be dead at mont of the current
2426: wave. Then the observed probability (that this person died)
2427: is null according to current estimated parameter. In fact,
2428: it should be very low but not zero otherwise the log go to
2429: infinity.
2430: */
2431: /* #ifdef INFINITYORIGINAL */
2432: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2433: /* #else */
2434: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2435: /* lli=log(mytinydouble); */
2436: /* else */
2437: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2438: /* #endif */
2439: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2440:
2441: } else if (s2==-2) {
2442: for (j=1,survp=0. ; j<=nlstate; j++)
2443: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2444: /*survp += out[s1][j]; */
2445: lli= log(survp);
2446: }
2447:
2448: else if (s2==-4) {
2449: for (j=3,survp=0. ; j<=nlstate; j++)
2450: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2451: lli= log(survp);
2452: }
2453:
2454: else if (s2==-5) {
2455: for (j=1,survp=0. ; j<=2; j++)
2456: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2457: lli= log(survp);
2458: }
2459:
2460: else{
2461: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2462: /* 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 */
2463: }
2464: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2465: /*if(lli ==000.0)*/
2466: /*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); */
2467: ipmx +=1;
2468: sw += weight[i];
2469: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2470: /* if (lli < log(mytinydouble)){ */
2471: /* 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); */
2472: /* 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]); */
2473: /* } */
1.126 brouard 2474: } /* end of wave */
2475: } /* end of individual */
2476: } else if(mle==2){
2477: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2478: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2479: for(mi=1; mi<= wav[i]-1; mi++){
2480: for (ii=1;ii<=nlstate+ndeath;ii++)
2481: for (j=1;j<=nlstate+ndeath;j++){
2482: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2483: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2484: }
2485: for(d=0; d<=dh[mi][i]; d++){
2486: newm=savm;
1.187 brouard 2487: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2488: cov[2]=agexact;
2489: if(nagesqr==1)
2490: cov[3]= agexact*agexact;
1.126 brouard 2491: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2492: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2493: }
2494: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2495: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2496: savm=oldm;
2497: oldm=newm;
2498: } /* end mult */
2499:
2500: s1=s[mw[mi][i]][i];
2501: s2=s[mw[mi+1][i]][i];
2502: bbh=(double)bh[mi][i]/(double)stepm;
2503: 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 */
2504: ipmx +=1;
2505: sw += weight[i];
2506: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2507: } /* end of wave */
2508: } /* end of individual */
2509: } else if(mle==3){ /* exponential inter-extrapolation */
2510: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2511: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2512: for(mi=1; mi<= wav[i]-1; mi++){
2513: for (ii=1;ii<=nlstate+ndeath;ii++)
2514: for (j=1;j<=nlstate+ndeath;j++){
2515: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2516: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2517: }
2518: for(d=0; d<dh[mi][i]; d++){
2519: newm=savm;
1.187 brouard 2520: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2521: cov[2]=agexact;
2522: if(nagesqr==1)
2523: cov[3]= agexact*agexact;
1.126 brouard 2524: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2525: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2526: }
2527: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2528: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2529: savm=oldm;
2530: oldm=newm;
2531: } /* end mult */
2532:
2533: s1=s[mw[mi][i]][i];
2534: s2=s[mw[mi+1][i]][i];
2535: bbh=(double)bh[mi][i]/(double)stepm;
2536: 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 */
2537: ipmx +=1;
2538: sw += weight[i];
2539: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2540: } /* end of wave */
2541: } /* end of individual */
2542: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2543: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2544: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2545: for(mi=1; mi<= wav[i]-1; mi++){
2546: for (ii=1;ii<=nlstate+ndeath;ii++)
2547: for (j=1;j<=nlstate+ndeath;j++){
2548: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2549: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2550: }
2551: for(d=0; d<dh[mi][i]; d++){
2552: newm=savm;
1.187 brouard 2553: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2554: cov[2]=agexact;
2555: if(nagesqr==1)
2556: cov[3]= agexact*agexact;
1.126 brouard 2557: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2558: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2559: }
2560:
2561: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2562: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2563: savm=oldm;
2564: oldm=newm;
2565: } /* end mult */
2566:
2567: s1=s[mw[mi][i]][i];
2568: s2=s[mw[mi+1][i]][i];
2569: if( s2 > nlstate){
2570: lli=log(out[s1][s2] - savm[s1][s2]);
2571: }else{
2572: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2573: }
2574: ipmx +=1;
2575: sw += weight[i];
2576: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2577: /* 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]); */
2578: } /* end of wave */
2579: } /* end of individual */
2580: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2581: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2582: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2583: for(mi=1; mi<= wav[i]-1; mi++){
2584: for (ii=1;ii<=nlstate+ndeath;ii++)
2585: for (j=1;j<=nlstate+ndeath;j++){
2586: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2587: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2588: }
2589: for(d=0; d<dh[mi][i]; d++){
2590: newm=savm;
1.187 brouard 2591: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2592: cov[2]=agexact;
2593: if(nagesqr==1)
2594: cov[3]= agexact*agexact;
1.126 brouard 2595: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2596: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2597: }
2598:
2599: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2600: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2601: savm=oldm;
2602: oldm=newm;
2603: } /* end mult */
2604:
2605: s1=s[mw[mi][i]][i];
2606: s2=s[mw[mi+1][i]][i];
2607: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2608: ipmx +=1;
2609: sw += weight[i];
2610: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2611: /*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]);*/
2612: } /* end of wave */
2613: } /* end of individual */
2614: } /* End of if */
2615: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2616: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2617: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2618: return -l;
2619: }
2620:
2621: /*************** log-likelihood *************/
2622: double funcone( double *x)
2623: {
2624: /* Same as likeli but slower because of a lot of printf and if */
2625: int i, ii, j, k, mi, d, kk;
1.131 brouard 2626: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2627: double **out;
2628: double lli; /* Individual log likelihood */
2629: double llt;
2630: int s1, s2;
2631: double bbh, survp;
1.187 brouard 2632: double agexact;
1.126 brouard 2633: /*extern weight */
2634: /* We are differentiating ll according to initial status */
2635: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2636: /*for(i=1;i<imx;i++)
2637: printf(" %d\n",s[4][i]);
2638: */
2639: cov[1]=1.;
2640:
2641: for(k=1; k<=nlstate; k++) ll[k]=0.;
2642:
2643: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2644: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2645: for(mi=1; mi<= wav[i]-1; mi++){
2646: for (ii=1;ii<=nlstate+ndeath;ii++)
2647: for (j=1;j<=nlstate+ndeath;j++){
2648: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2649: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2650: }
2651: for(d=0; d<dh[mi][i]; d++){
2652: newm=savm;
1.187 brouard 2653: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2654: cov[2]=agexact;
2655: if(nagesqr==1)
2656: cov[3]= agexact*agexact;
1.126 brouard 2657: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2658: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2659: }
1.187 brouard 2660:
1.145 brouard 2661: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2662: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2663: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2664: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2665: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2666: savm=oldm;
2667: oldm=newm;
2668: } /* end mult */
2669:
2670: s1=s[mw[mi][i]][i];
2671: s2=s[mw[mi+1][i]][i];
2672: bbh=(double)bh[mi][i]/(double)stepm;
2673: /* bias is positive if real duration
2674: * is higher than the multiple of stepm and negative otherwise.
2675: */
2676: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2677: lli=log(out[s1][s2] - savm[s1][s2]);
2678: } else if (s2==-2) {
2679: for (j=1,survp=0. ; j<=nlstate; j++)
2680: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2681: lli= log(survp);
2682: }else if (mle==1){
2683: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2684: } else if(mle==2){
2685: 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 */
2686: } else if(mle==3){ /* exponential inter-extrapolation */
2687: 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 */
2688: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2689: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2690: } else{ /* mle=0 back to 1 */
2691: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2692: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2693: } /* End of if */
2694: ipmx +=1;
2695: sw += weight[i];
2696: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2697: /*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 2698: if(globpr){
1.205 brouard 2699: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126 brouard 2700: %11.6f %11.6f %11.6f ", \
1.205 brouard 2701: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126 brouard 2702: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2703: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2704: llt +=ll[k]*gipmx/gsw;
2705: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2706: }
2707: fprintf(ficresilk," %10.6f\n", -llt);
2708: }
2709: } /* end of wave */
2710: } /* end of individual */
2711: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2712: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2713: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2714: if(globpr==0){ /* First time we count the contributions and weights */
2715: gipmx=ipmx;
2716: gsw=sw;
2717: }
2718: return -l;
2719: }
2720:
2721:
2722: /*************** function likelione ***********/
2723: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2724: {
2725: /* This routine should help understanding what is done with
2726: the selection of individuals/waves and
2727: to check the exact contribution to the likelihood.
2728: Plotting could be done.
2729: */
2730: int k;
2731:
2732: if(*globpri !=0){ /* Just counts and sums, no printings */
1.201 brouard 2733: strcpy(fileresilk,"ILK_");
1.202 brouard 2734: strcat(fileresilk,fileresu);
1.126 brouard 2735: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2736: printf("Problem with resultfile: %s\n", fileresilk);
2737: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2738: }
1.205 brouard 2739: fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
1.207 brouard 2740: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126 brouard 2741: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2742: for(k=1; k<=nlstate; k++)
2743: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2744: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2745: }
2746:
2747: *fretone=(*funcone)(p);
2748: if(*globpri !=0){
2749: fclose(ficresilk);
1.205 brouard 2750: if (mle ==0)
2751: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2752: else if(mle >=1)
2753: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2754: fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.207 brouard 2755:
1.208 brouard 2756:
2757: for (k=1; k<= nlstate ; k++) {
1.211 brouard 2758: fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.208 brouard 2759: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2760: }
1.207 brouard 2761: fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.204 brouard 2762: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207 brouard 2763: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204 brouard 2764: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207 brouard 2765: fflush(fichtm);
1.205 brouard 2766: }
1.126 brouard 2767: return;
2768: }
2769:
2770:
2771: /*********** Maximum Likelihood Estimation ***************/
2772:
2773: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2774: {
1.165 brouard 2775: int i,j, iter=0;
1.126 brouard 2776: double **xi;
2777: double fret;
2778: double fretone; /* Only one call to likelihood */
2779: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2780:
2781: #ifdef NLOPT
2782: int creturn;
2783: nlopt_opt opt;
2784: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2785: double *lb;
2786: double minf; /* the minimum objective value, upon return */
2787: double * p1; /* Shifted parameters from 0 instead of 1 */
2788: myfunc_data dinst, *d = &dinst;
2789: #endif
2790:
2791:
1.126 brouard 2792: xi=matrix(1,npar,1,npar);
2793: for (i=1;i<=npar;i++)
2794: for (j=1;j<=npar;j++)
2795: xi[i][j]=(i==j ? 1.0 : 0.0);
2796: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.201 brouard 2797: strcpy(filerespow,"POW_");
1.126 brouard 2798: strcat(filerespow,fileres);
2799: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2800: printf("Problem with resultfile: %s\n", filerespow);
2801: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2802: }
2803: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2804: for (i=1;i<=nlstate;i++)
2805: for(j=1;j<=nlstate+ndeath;j++)
2806: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2807: fprintf(ficrespow,"\n");
1.162 brouard 2808: #ifdef POWELL
1.126 brouard 2809: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2810: #endif
1.126 brouard 2811:
1.162 brouard 2812: #ifdef NLOPT
2813: #ifdef NEWUOA
2814: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2815: #else
2816: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2817: #endif
2818: lb=vector(0,npar-1);
2819: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2820: nlopt_set_lower_bounds(opt, lb);
2821: nlopt_set_initial_step1(opt, 0.1);
2822:
2823: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2824: d->function = func;
2825: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2826: nlopt_set_min_objective(opt, myfunc, d);
2827: nlopt_set_xtol_rel(opt, ftol);
2828: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2829: printf("nlopt failed! %d\n",creturn);
2830: }
2831: else {
2832: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2833: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2834: iter=1; /* not equal */
2835: }
2836: nlopt_destroy(opt);
2837: #endif
1.126 brouard 2838: free_matrix(xi,1,npar,1,npar);
2839: fclose(ficrespow);
1.203 brouard 2840: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2841: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180 brouard 2842: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2843:
2844: }
2845:
2846: /**** Computes Hessian and covariance matrix ***/
1.203 brouard 2847: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126 brouard 2848: {
2849: double **a,**y,*x,pd;
1.203 brouard 2850: /* double **hess; */
1.164 brouard 2851: int i, j;
1.126 brouard 2852: int *indx;
2853:
2854: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203 brouard 2855: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126 brouard 2856: void lubksb(double **a, int npar, int *indx, double b[]) ;
2857: void ludcmp(double **a, int npar, int *indx, double *d) ;
2858: double gompertz(double p[]);
1.203 brouard 2859: /* hess=matrix(1,npar,1,npar); */
1.126 brouard 2860:
2861: printf("\nCalculation of the hessian matrix. Wait...\n");
2862: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2863: for (i=1;i<=npar;i++){
1.203 brouard 2864: printf("%d-",i);fflush(stdout);
2865: fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126 brouard 2866:
2867: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2868:
2869: /* printf(" %f ",p[i]);
2870: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2871: }
2872:
2873: for (i=1;i<=npar;i++) {
2874: for (j=1;j<=npar;j++) {
2875: if (j>i) {
1.203 brouard 2876: printf(".%d-%d",i,j);fflush(stdout);
2877: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2878: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126 brouard 2879:
2880: hess[j][i]=hess[i][j];
2881: /*printf(" %lf ",hess[i][j]);*/
2882: }
2883: }
2884: }
2885: printf("\n");
2886: fprintf(ficlog,"\n");
2887:
2888: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2889: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2890:
2891: a=matrix(1,npar,1,npar);
2892: y=matrix(1,npar,1,npar);
2893: x=vector(1,npar);
2894: indx=ivector(1,npar);
2895: for (i=1;i<=npar;i++)
2896: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2897: ludcmp(a,npar,indx,&pd);
2898:
2899: for (j=1;j<=npar;j++) {
2900: for (i=1;i<=npar;i++) x[i]=0;
2901: x[j]=1;
2902: lubksb(a,npar,indx,x);
2903: for (i=1;i<=npar;i++){
2904: matcov[i][j]=x[i];
2905: }
2906: }
2907:
2908: printf("\n#Hessian matrix#\n");
2909: fprintf(ficlog,"\n#Hessian matrix#\n");
2910: for (i=1;i<=npar;i++) {
2911: for (j=1;j<=npar;j++) {
1.203 brouard 2912: printf("%.6e ",hess[i][j]);
2913: fprintf(ficlog,"%.6e ",hess[i][j]);
1.126 brouard 2914: }
2915: printf("\n");
2916: fprintf(ficlog,"\n");
2917: }
2918:
1.203 brouard 2919: /* printf("\n#Covariance matrix#\n"); */
2920: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2921: /* for (i=1;i<=npar;i++) { */
2922: /* for (j=1;j<=npar;j++) { */
2923: /* printf("%.6e ",matcov[i][j]); */
2924: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2925: /* } */
2926: /* printf("\n"); */
2927: /* fprintf(ficlog,"\n"); */
2928: /* } */
2929:
1.126 brouard 2930: /* Recompute Inverse */
1.203 brouard 2931: /* for (i=1;i<=npar;i++) */
2932: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2933: /* ludcmp(a,npar,indx,&pd); */
2934:
2935: /* printf("\n#Hessian matrix recomputed#\n"); */
2936:
2937: /* for (j=1;j<=npar;j++) { */
2938: /* for (i=1;i<=npar;i++) x[i]=0; */
2939: /* x[j]=1; */
2940: /* lubksb(a,npar,indx,x); */
2941: /* for (i=1;i<=npar;i++){ */
2942: /* y[i][j]=x[i]; */
2943: /* printf("%.3e ",y[i][j]); */
2944: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2945: /* } */
2946: /* printf("\n"); */
2947: /* fprintf(ficlog,"\n"); */
2948: /* } */
2949:
2950: /* Verifying the inverse matrix */
2951: #ifdef DEBUGHESS
2952: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126 brouard 2953:
1.203 brouard 2954: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2955: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126 brouard 2956:
2957: for (j=1;j<=npar;j++) {
2958: for (i=1;i<=npar;i++){
1.203 brouard 2959: printf("%.2f ",y[i][j]);
2960: fprintf(ficlog,"%.2f ",y[i][j]);
1.126 brouard 2961: }
2962: printf("\n");
2963: fprintf(ficlog,"\n");
2964: }
1.203 brouard 2965: #endif
1.126 brouard 2966:
2967: free_matrix(a,1,npar,1,npar);
2968: free_matrix(y,1,npar,1,npar);
2969: free_vector(x,1,npar);
2970: free_ivector(indx,1,npar);
1.203 brouard 2971: /* free_matrix(hess,1,npar,1,npar); */
1.126 brouard 2972:
2973:
2974: }
2975:
2976: /*************** hessian matrix ****************/
2977: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203 brouard 2978: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126 brouard 2979: int i;
2980: int l=1, lmax=20;
1.203 brouard 2981: double k1,k2, res, fx;
1.132 brouard 2982: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2983: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2984: int k=0,kmax=10;
2985: double l1;
2986:
2987: fx=func(x);
2988: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2989: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2990: l1=pow(10,l);
2991: delts=delt;
2992: for(k=1 ; k <kmax; k=k+1){
2993: delt = delta*(l1*k);
2994: p2[theta]=x[theta] +delt;
1.145 brouard 2995: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2996: p2[theta]=x[theta]-delt;
2997: k2=func(p2)-fx;
2998: /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203 brouard 2999: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126 brouard 3000:
1.203 brouard 3001: #ifdef DEBUGHESSII
1.126 brouard 3002: 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);
3003: 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);
3004: #endif
3005: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3006: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3007: k=kmax;
3008: }
3009: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 3010: k=kmax; l=lmax*10;
1.126 brouard 3011: }
3012: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3013: delts=delt;
3014: }
1.203 brouard 3015: } /* End loop k */
1.126 brouard 3016: }
3017: delti[theta]=delts;
3018: return res;
3019:
3020: }
3021:
1.203 brouard 3022: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126 brouard 3023: {
3024: int i;
1.164 brouard 3025: int l=1, lmax=20;
1.126 brouard 3026: double k1,k2,k3,k4,res,fx;
1.132 brouard 3027: double p2[MAXPARM+1];
1.203 brouard 3028: int k, kmax=1;
3029: double v1, v2, cv12, lc1, lc2;
1.208 brouard 3030:
3031: int firstime=0;
1.203 brouard 3032:
1.126 brouard 3033: fx=func(x);
1.203 brouard 3034: for (k=1; k<=kmax; k=k+10) {
1.126 brouard 3035: for (i=1;i<=npar;i++) p2[i]=x[i];
1.203 brouard 3036: p2[thetai]=x[thetai]+delti[thetai]*k;
3037: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 3038: k1=func(p2)-fx;
3039:
1.203 brouard 3040: p2[thetai]=x[thetai]+delti[thetai]*k;
3041: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 3042: k2=func(p2)-fx;
3043:
1.203 brouard 3044: p2[thetai]=x[thetai]-delti[thetai]*k;
3045: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 3046: k3=func(p2)-fx;
3047:
1.203 brouard 3048: p2[thetai]=x[thetai]-delti[thetai]*k;
3049: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 3050: k4=func(p2)-fx;
1.203 brouard 3051: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3052: if(k1*k2*k3*k4 <0.){
1.208 brouard 3053: firstime=1;
1.203 brouard 3054: kmax=kmax+10;
1.208 brouard 3055: }
3056: if(kmax >=10 || firstime ==1){
1.203 brouard 3057: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3058: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3059: 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);
3060: 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);
3061: }
3062: #ifdef DEBUGHESSIJ
3063: v1=hess[thetai][thetai];
3064: v2=hess[thetaj][thetaj];
3065: cv12=res;
3066: /* Computing eigen value of Hessian matrix */
3067: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3068: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3069: if ((lc2 <0) || (lc1 <0) ){
3070: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3071: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3072: 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);
3073: 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);
3074: }
1.126 brouard 3075: #endif
3076: }
3077: return res;
3078: }
3079:
1.203 brouard 3080: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3081: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3082: /* { */
3083: /* int i; */
3084: /* int l=1, lmax=20; */
3085: /* double k1,k2,k3,k4,res,fx; */
3086: /* double p2[MAXPARM+1]; */
3087: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3088: /* int k=0,kmax=10; */
3089: /* double l1; */
3090:
3091: /* fx=func(x); */
3092: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3093: /* l1=pow(10,l); */
3094: /* delts=delt; */
3095: /* for(k=1 ; k <kmax; k=k+1){ */
3096: /* delt = delti*(l1*k); */
3097: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3098: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3099: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3100: /* k1=func(p2)-fx; */
3101:
3102: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3103: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3104: /* k2=func(p2)-fx; */
3105:
3106: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3107: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3108: /* k3=func(p2)-fx; */
3109:
3110: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3111: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3112: /* k4=func(p2)-fx; */
3113: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3114: /* #ifdef DEBUGHESSIJ */
3115: /* 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); */
3116: /* 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); */
3117: /* #endif */
3118: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3119: /* k=kmax; */
3120: /* } */
3121: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3122: /* k=kmax; l=lmax*10; */
3123: /* } */
3124: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3125: /* delts=delt; */
3126: /* } */
3127: /* } /\* End loop k *\/ */
3128: /* } */
3129: /* delti[theta]=delts; */
3130: /* return res; */
3131: /* } */
3132:
3133:
1.126 brouard 3134: /************** Inverse of matrix **************/
3135: void ludcmp(double **a, int n, int *indx, double *d)
3136: {
3137: int i,imax,j,k;
3138: double big,dum,sum,temp;
3139: double *vv;
3140:
3141: vv=vector(1,n);
3142: *d=1.0;
3143: for (i=1;i<=n;i++) {
3144: big=0.0;
3145: for (j=1;j<=n;j++)
3146: if ((temp=fabs(a[i][j])) > big) big=temp;
3147: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3148: vv[i]=1.0/big;
3149: }
3150: for (j=1;j<=n;j++) {
3151: for (i=1;i<j;i++) {
3152: sum=a[i][j];
3153: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3154: a[i][j]=sum;
3155: }
3156: big=0.0;
3157: for (i=j;i<=n;i++) {
3158: sum=a[i][j];
3159: for (k=1;k<j;k++)
3160: sum -= a[i][k]*a[k][j];
3161: a[i][j]=sum;
3162: if ( (dum=vv[i]*fabs(sum)) >= big) {
3163: big=dum;
3164: imax=i;
3165: }
3166: }
3167: if (j != imax) {
3168: for (k=1;k<=n;k++) {
3169: dum=a[imax][k];
3170: a[imax][k]=a[j][k];
3171: a[j][k]=dum;
3172: }
3173: *d = -(*d);
3174: vv[imax]=vv[j];
3175: }
3176: indx[j]=imax;
3177: if (a[j][j] == 0.0) a[j][j]=TINY;
3178: if (j != n) {
3179: dum=1.0/(a[j][j]);
3180: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3181: }
3182: }
3183: free_vector(vv,1,n); /* Doesn't work */
3184: ;
3185: }
3186:
3187: void lubksb(double **a, int n, int *indx, double b[])
3188: {
3189: int i,ii=0,ip,j;
3190: double sum;
3191:
3192: for (i=1;i<=n;i++) {
3193: ip=indx[i];
3194: sum=b[ip];
3195: b[ip]=b[i];
3196: if (ii)
3197: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3198: else if (sum) ii=i;
3199: b[i]=sum;
3200: }
3201: for (i=n;i>=1;i--) {
3202: sum=b[i];
3203: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3204: b[i]=sum/a[i][i];
3205: }
3206: }
3207:
3208: void pstamp(FILE *fichier)
3209: {
1.196 brouard 3210: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126 brouard 3211: }
3212:
3213: /************ Frequencies ********************/
3214: 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[])
3215: { /* Some frequencies */
3216:
1.164 brouard 3217: int i, m, jk, j1, bool, z1,j;
1.126 brouard 3218: int first;
3219: double ***freq; /* Frequencies */
3220: double *pp, **prop;
3221: double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.213 ! brouard 3222: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH];
1.126 brouard 3223:
3224: pp=vector(1,nlstate);
3225: prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201 brouard 3226: strcpy(fileresp,"P_");
3227: strcat(fileresp,fileresu);
1.213 ! brouard 3228: /*strcat(fileresphtm,fileresu);*/
1.126 brouard 3229: if((ficresp=fopen(fileresp,"w"))==NULL) {
3230: printf("Problem with prevalence resultfile: %s\n", fileresp);
3231: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3232: exit(0);
3233: }
1.213 ! brouard 3234: printf("Problem with prevalence resultfile: %s\n", fileresp);
! 3235: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
! 3236: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
! 3237: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
! 3238: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
! 3239: fflush(ficlog);
! 3240: exit(70);
! 3241: }
1.126 brouard 3242: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3243: j1=0;
3244:
3245: j=cptcoveff;
3246: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3247:
3248: first=1;
3249:
1.169 brouard 3250: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3251: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3252: /* j1++; */
1.145 brouard 3253: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 3254: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3255: scanf("%d", i);*/
3256: for (i=-5; i<=nlstate+ndeath; i++)
3257: for (jk=-5; jk<=nlstate+ndeath; jk++)
3258: for(m=iagemin; m <= iagemax+3; m++)
3259: freq[i][jk][m]=0;
1.143 brouard 3260:
3261: for (i=1; i<=nlstate; i++)
3262: for(m=iagemin; m <= iagemax+3; m++)
3263: prop[i][m]=0;
1.126 brouard 3264:
3265: dateintsum=0;
3266: k2cpt=0;
3267: for (i=1; i<=imx; i++) {
3268: bool=1;
1.210 brouard 3269: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144 brouard 3270: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3271: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145 brouard 3272: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 3273: bool=0;
1.198 brouard 3274: /* 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",
3275: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3276: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3277: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144 brouard 3278: }
1.210 brouard 3279: } /* cptcovn > 0 */
1.144 brouard 3280:
1.126 brouard 3281: if (bool==1){
3282: for(m=firstpass; m<=lastpass; m++){
3283: k2=anint[m][i]+(mint[m][i]/12.);
3284: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3285: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3286: if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.213 ! brouard 3287: if (s[m][i]>0 && s[m][i]<=nlstate)
! 3288: prop[s[m][i]][(int)agev[m][i]] += weight[i];
1.126 brouard 3289: if (m<lastpass) {
3290: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3291: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3292: }
3293:
1.210 brouard 3294: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
1.126 brouard 3295: dateintsum=dateintsum+k2;
3296: k2cpt++;
1.210 brouard 3297: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.126 brouard 3298: }
3299: /*}*/
1.210 brouard 3300: } /* end m */
3301: } /* end bool */
3302: } /* end i = 1 to imx */
1.126 brouard 3303:
3304: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3305: pstamp(ficresp);
3306: if (cptcovn>0) {
3307: fprintf(ficresp, "\n#********** Variable ");
1.213 ! brouard 3308: fprintf(ficresphtm, "\n<h3>********** Variable ");
! 3309: for (z1=1; z1<=cptcoveff; z1++){
! 3310: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
! 3311: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
! 3312: }
! 3313: fprintf(ficresp, "**********\n#");
! 3314: fprintf(ficresphtm, "**********</h3>\n#");
1.143 brouard 3315: fprintf(ficlog, "\n#********** Variable ");
1.198 brouard 3316: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143 brouard 3317: fprintf(ficlog, "**********\n#");
1.126 brouard 3318: }
1.213 ! brouard 3319: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\"><th></th>");
! 3320: for(i=1; i<=nlstate;i++) {
1.126 brouard 3321: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213 ! brouard 3322: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
! 3323: }
1.126 brouard 3324: fprintf(ficresp, "\n");
1.213 ! brouard 3325: fprintf(ficresphtm, "\n");
1.126 brouard 3326:
3327: for(i=iagemin; i <= iagemax+3; i++){
1.213 ! brouard 3328: fprintf(ficresphtm,"<tr>");
1.126 brouard 3329: if(i==iagemax+3){
3330: fprintf(ficlog,"Total");
3331: }else{
3332: if(first==1){
3333: first=0;
3334: printf("See log file for details...\n");
3335: }
3336: fprintf(ficlog,"Age %d", i);
3337: }
3338: for(jk=1; jk <=nlstate ; jk++){
3339: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3340: pp[jk] += freq[jk][m][i];
3341: }
3342: for(jk=1; jk <=nlstate ; jk++){
3343: for(m=-1, pos=0; m <=0 ; m++)
3344: pos += freq[jk][m][i];
3345: if(pp[jk]>=1.e-10){
3346: if(first==1){
1.132 brouard 3347: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3348: }
3349: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3350: }else{
3351: if(first==1)
3352: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3353: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3354: }
3355: }
3356:
3357: for(jk=1; jk <=nlstate ; jk++){
3358: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3359: pp[jk] += freq[jk][m][i];
3360: }
3361: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3362: pos += pp[jk];
3363: posprop += prop[jk][i];
3364: }
3365: for(jk=1; jk <=nlstate ; jk++){
3366: if(pos>=1.e-5){
3367: if(first==1)
3368: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3369: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3370: }else{
3371: if(first==1)
3372: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3373: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3374: }
3375: if( i <= iagemax){
3376: if(pos>=1.e-5){
3377: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213 ! brouard 3378: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.126 brouard 3379: /*probs[i][jk][j1]= pp[jk]/pos;*/
3380: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3381: }
1.213 ! brouard 3382: else{
1.126 brouard 3383: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213 ! brouard 3384: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
! 3385: }
1.126 brouard 3386: }
3387: }
3388:
3389: for(jk=-1; jk <=nlstate+ndeath; jk++)
3390: for(m=-1; m <=nlstate+ndeath; m++)
3391: if(freq[jk][m][i] !=0 ) {
3392: if(first==1)
3393: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3394: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3395: }
1.213 ! brouard 3396: if(i <= iagemax){
1.126 brouard 3397: fprintf(ficresp,"\n");
1.213 ! brouard 3398: fprintf(ficresphtm,"</tr>\n");
! 3399: }
1.126 brouard 3400: if(first==1)
3401: printf("Others in log...\n");
3402: fprintf(ficlog,"\n");
1.210 brouard 3403: } /* end loop i */
1.213 ! brouard 3404: fprintf(ficresphtm,"</table>\n");
1.145 brouard 3405: /*}*/
1.210 brouard 3406: } /* end j1 */
1.126 brouard 3407: dateintmean=dateintsum/k2cpt;
3408:
3409: fclose(ficresp);
1.213 ! brouard 3410: fclose(ficresphtm);
1.126 brouard 3411: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3412: free_vector(pp,1,nlstate);
3413: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3414: /* End of Freq */
3415: }
3416:
3417: /************ Prevalence ********************/
3418: 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)
3419: {
3420: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3421: in each health status at the date of interview (if between dateprev1 and dateprev2).
3422: We still use firstpass and lastpass as another selection.
3423: */
3424:
1.164 brouard 3425: int i, m, jk, j1, bool, z1,j;
3426:
3427: double **prop;
3428: double posprop;
1.126 brouard 3429: double y2; /* in fractional years */
3430: int iagemin, iagemax;
1.145 brouard 3431: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3432:
3433: iagemin= (int) agemin;
3434: iagemax= (int) agemax;
3435: /*pp=vector(1,nlstate);*/
3436: prop=matrix(1,nlstate,iagemin,iagemax+3);
3437: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3438: j1=0;
3439:
1.145 brouard 3440: /*j=cptcoveff;*/
1.126 brouard 3441: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3442:
1.145 brouard 3443: first=1;
3444: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3445: /*for(i1=1; i1<=ncodemax[k1];i1++){
3446: j1++;*/
1.126 brouard 3447:
3448: for (i=1; i<=nlstate; i++)
3449: for(m=iagemin; m <= iagemax+3; m++)
3450: prop[i][m]=0.0;
3451:
3452: for (i=1; i<=imx; i++) { /* Each individual */
3453: bool=1;
3454: if (cptcovn>0) {
3455: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3456: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
1.126 brouard 3457: bool=0;
3458: }
3459: if (bool==1) {
3460: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3461: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3462: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3463: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3464: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3465: 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);
3466: if (s[m][i]>0 && s[m][i]<=nlstate) {
3467: /*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]]);*/
3468: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3469: prop[s[m][i]][iagemax+3] += weight[i];
3470: }
3471: }
3472: } /* end selection of waves */
3473: }
3474: }
3475: for(i=iagemin; i <= iagemax+3; i++){
3476: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3477: posprop += prop[jk][i];
3478: }
1.145 brouard 3479:
1.126 brouard 3480: for(jk=1; jk <=nlstate ; jk++){
3481: if( i <= iagemax){
3482: if(posprop>=1.e-5){
3483: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3484: } else{
3485: if(first==1){
3486: first=0;
3487: 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]);
3488: }
3489: }
1.126 brouard 3490: }
3491: }/* end jk */
3492: }/* end i */
1.145 brouard 3493: /*} *//* end i1 */
3494: } /* end j1 */
1.126 brouard 3495:
3496: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3497: /*free_vector(pp,1,nlstate);*/
3498: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3499: } /* End of prevalence */
3500:
3501: /************* Waves Concatenation ***************/
3502:
3503: 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)
3504: {
3505: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3506: Death is a valid wave (if date is known).
3507: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3508: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3509: and mw[mi+1][i]. dh depends on stepm.
3510: */
3511:
3512: int i, mi, m;
3513: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3514: double sum=0., jmean=0.;*/
3515: int first;
3516: int j, k=0,jk, ju, jl;
3517: double sum=0.;
3518: first=0;
1.164 brouard 3519: jmin=100000;
1.126 brouard 3520: jmax=-1;
3521: jmean=0.;
3522: for(i=1; i<=imx; i++){
3523: mi=0;
3524: m=firstpass;
3525: while(s[m][i] <= nlstate){
3526: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3527: mw[++mi][i]=m;
3528: if(m >=lastpass)
3529: break;
3530: else
3531: m++;
3532: }/* end while */
3533: if (s[m][i] > nlstate){
3534: mi++; /* Death is another wave */
3535: /* if(mi==0) never been interviewed correctly before death */
3536: /* Only death is a correct wave */
3537: mw[mi][i]=m;
3538: }
3539:
3540: wav[i]=mi;
3541: if(mi==0){
3542: nbwarn++;
3543: if(first==0){
3544: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3545: first=1;
3546: }
3547: if(first==1){
3548: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3549: }
3550: } /* end mi==0 */
3551: } /* End individuals */
3552:
3553: for(i=1; i<=imx; i++){
3554: for(mi=1; mi<wav[i];mi++){
3555: if (stepm <=0)
3556: dh[mi][i]=1;
3557: else{
3558: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3559: if (agedc[i] < 2*AGESUP) {
3560: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3561: if(j==0) j=1; /* Survives at least one month after exam */
3562: else if(j<0){
3563: nberr++;
3564: 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]);
3565: j=1; /* Temporary Dangerous patch */
3566: 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);
3567: 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]);
3568: 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);
3569: }
3570: k=k+1;
3571: if (j >= jmax){
3572: jmax=j;
3573: ijmax=i;
3574: }
3575: if (j <= jmin){
3576: jmin=j;
3577: ijmin=i;
3578: }
3579: sum=sum+j;
3580: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3581: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3582: }
3583: }
3584: else{
3585: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3586: /* 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]); */
3587:
3588: k=k+1;
3589: if (j >= jmax) {
3590: jmax=j;
3591: ijmax=i;
3592: }
3593: else if (j <= jmin){
3594: jmin=j;
3595: ijmin=i;
3596: }
3597: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3598: /*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]);*/
3599: if(j<0){
3600: nberr++;
3601: 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]);
3602: 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]);
3603: }
3604: sum=sum+j;
3605: }
3606: jk= j/stepm;
3607: jl= j -jk*stepm;
3608: ju= j -(jk+1)*stepm;
3609: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3610: if(jl==0){
3611: dh[mi][i]=jk;
3612: bh[mi][i]=0;
3613: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3614: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3615: dh[mi][i]=jk+1;
3616: bh[mi][i]=ju;
3617: }
3618: }else{
3619: if(jl <= -ju){
3620: dh[mi][i]=jk;
3621: bh[mi][i]=jl; /* bias is positive if real duration
3622: * is higher than the multiple of stepm and negative otherwise.
3623: */
3624: }
3625: else{
3626: dh[mi][i]=jk+1;
3627: bh[mi][i]=ju;
3628: }
3629: if(dh[mi][i]==0){
3630: dh[mi][i]=1; /* At least one step */
3631: bh[mi][i]=ju; /* At least one step */
3632: /* 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);*/
3633: }
3634: } /* end if mle */
3635: }
3636: } /* end wave */
3637: }
3638: jmean=sum/k;
3639: 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 3640: 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 3641: }
3642:
3643: /*********** Tricode ****************************/
1.145 brouard 3644: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3645: {
1.144 brouard 3646: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3647: /* 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 3648: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3649: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3650: * nbcode[Tvar[j]][1]=
1.144 brouard 3651: */
1.130 brouard 3652:
1.145 brouard 3653: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3654: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3655: int cptcode=0; /* Modality max of covariates j */
3656: int modmincovj=0; /* Modality min of covariates j */
3657:
3658:
1.126 brouard 3659: cptcoveff=0;
3660:
1.144 brouard 3661: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3662:
1.145 brouard 3663: /* Loop on covariates without age and products */
1.186 brouard 3664: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3665: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3666: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3667: modality of this covariate Vj*/
1.145 brouard 3668: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3669: * If product of Vn*Vm, still boolean *:
3670: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3671: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3672: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3673: modality of the nth covariate of individual i. */
1.145 brouard 3674: if (ij > modmaxcovj)
3675: modmaxcovj=ij;
3676: else if (ij < modmincovj)
3677: modmincovj=ij;
3678: if ((ij < -1) && (ij > NCOVMAX)){
3679: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3680: exit(1);
3681: }else
1.136 brouard 3682: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3683: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3684: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3685: /* getting the maximum value of the modality of the covariate
3686: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3687: female is 1, then modmaxcovj=1.*/
1.192 brouard 3688: } /* end for loop on individuals i */
1.145 brouard 3689: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3690: 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 3691: cptcode=modmaxcovj;
1.137 brouard 3692: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3693: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3694: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3695: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3696: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3697: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3698: if( k != -1){
3699: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3700: covariate for which somebody answered excluding
3701: undefined. Usually 2: 0 and 1. */
3702: }
3703: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3704: covariate for which somebody answered including
3705: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3706: }
3707: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3708: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3709: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3710:
1.136 brouard 3711: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3712: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3713: 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 3714: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3715: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3716: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3717: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3718: nbcode[Tvar[j]][ij]=k;
3719: nbcode[Tvar[j]][1]=0;
3720: nbcode[Tvar[j]][2]=1;
3721: nbcode[Tvar[j]][3]=2;
1.197 brouard 3722: To be continued (not working yet).
1.145 brouard 3723: */
1.197 brouard 3724: ij=0; /* ij is similar to i but can jump over null modalities */
3725: 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*/
3726: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192 brouard 3727: break;
3728: }
3729: ij++;
1.197 brouard 3730: 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 3731: cptcode = ij; /* New max modality for covar j */
3732: } /* end of loop on modality i=-1 to 1 or more */
3733:
3734: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3735: /* /\*recode from 0 *\/ */
3736: /* k is a modality. If we have model=V1+V1*sex */
3737: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3738: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3739: /* } */
3740: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3741: /* if (ij > ncodemax[j]) { */
3742: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3743: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3744: /* break; */
3745: /* } */
3746: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3747: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3748:
1.145 brouard 3749: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3750:
1.187 brouard 3751: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3752: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3753: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3754: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3755: }
1.126 brouard 3756:
1.192 brouard 3757: ij=0;
1.145 brouard 3758: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3759: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3760: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3761: ij++;
1.145 brouard 3762: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3763: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3764: }else{
3765: /* Tvaraff[ij]=0; */
3766: }
1.126 brouard 3767: }
1.192 brouard 3768: /* ij--; */
1.144 brouard 3769: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3770:
1.126 brouard 3771: }
3772:
1.145 brouard 3773:
1.126 brouard 3774: /*********** Health Expectancies ****************/
3775:
1.127 brouard 3776: 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 3777:
3778: {
3779: /* Health expectancies, no variances */
1.164 brouard 3780: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3781: int nhstepma, nstepma; /* Decreasing with age */
3782: double age, agelim, hf;
3783: double ***p3mat;
3784: double eip;
3785:
3786: pstamp(ficreseij);
3787: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3788: fprintf(ficreseij,"# Age");
3789: for(i=1; i<=nlstate;i++){
3790: for(j=1; j<=nlstate;j++){
3791: fprintf(ficreseij," e%1d%1d ",i,j);
3792: }
3793: fprintf(ficreseij," e%1d. ",i);
3794: }
3795: fprintf(ficreseij,"\n");
3796:
3797:
3798: if(estepm < stepm){
3799: printf ("Problem %d lower than %d\n",estepm, stepm);
3800: }
3801: else hstepm=estepm;
3802: /* We compute the life expectancy from trapezoids spaced every estepm months
3803: * This is mainly to measure the difference between two models: for example
3804: * if stepm=24 months pijx are given only every 2 years and by summing them
3805: * we are calculating an estimate of the Life Expectancy assuming a linear
3806: * progression in between and thus overestimating or underestimating according
3807: * to the curvature of the survival function. If, for the same date, we
3808: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3809: * to compare the new estimate of Life expectancy with the same linear
3810: * hypothesis. A more precise result, taking into account a more precise
3811: * curvature will be obtained if estepm is as small as stepm. */
3812:
3813: /* For example we decided to compute the life expectancy with the smallest unit */
3814: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3815: nhstepm is the number of hstepm from age to agelim
3816: nstepm is the number of stepm from age to agelin.
3817: Look at hpijx to understand the reason of that which relies in memory size
3818: and note for a fixed period like estepm months */
3819: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3820: survival function given by stepm (the optimization length). Unfortunately it
3821: means that if the survival funtion is printed only each two years of age and if
3822: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3823: results. So we changed our mind and took the option of the best precision.
3824: */
3825: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3826:
3827: agelim=AGESUP;
3828: /* If stepm=6 months */
3829: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3830: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3831:
3832: /* nhstepm age range expressed in number of stepm */
3833: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3834: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3835: /* if (stepm >= YEARM) hstepm=1;*/
3836: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3837: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3838:
3839: for (age=bage; age<=fage; age ++){
3840: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3841: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3842: /* if (stepm >= YEARM) hstepm=1;*/
3843: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3844:
3845: /* If stepm=6 months */
3846: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3847: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3848:
3849: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3850:
3851: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3852:
3853: printf("%d|",(int)age);fflush(stdout);
3854: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3855:
3856: /* Computing expectancies */
3857: for(i=1; i<=nlstate;i++)
3858: for(j=1; j<=nlstate;j++)
3859: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3860: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3861:
3862: /* 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]);*/
3863:
3864: }
3865:
3866: fprintf(ficreseij,"%3.0f",age );
3867: for(i=1; i<=nlstate;i++){
3868: eip=0;
3869: for(j=1; j<=nlstate;j++){
3870: eip +=eij[i][j][(int)age];
3871: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3872: }
3873: fprintf(ficreseij,"%9.4f", eip );
3874: }
3875: fprintf(ficreseij,"\n");
3876:
3877: }
3878: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3879: printf("\n");
3880: fprintf(ficlog,"\n");
3881:
3882: }
3883:
1.127 brouard 3884: 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 3885:
3886: {
3887: /* Covariances of health expectancies eij and of total life expectancies according
3888: to initial status i, ei. .
3889: */
3890: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3891: int nhstepma, nstepma; /* Decreasing with age */
3892: double age, agelim, hf;
3893: double ***p3matp, ***p3matm, ***varhe;
3894: double **dnewm,**doldm;
3895: double *xp, *xm;
3896: double **gp, **gm;
3897: double ***gradg, ***trgradg;
3898: int theta;
3899:
3900: double eip, vip;
3901:
3902: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3903: xp=vector(1,npar);
3904: xm=vector(1,npar);
3905: dnewm=matrix(1,nlstate*nlstate,1,npar);
3906: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3907:
3908: pstamp(ficresstdeij);
3909: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3910: fprintf(ficresstdeij,"# Age");
3911: for(i=1; i<=nlstate;i++){
3912: for(j=1; j<=nlstate;j++)
3913: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3914: fprintf(ficresstdeij," e%1d. ",i);
3915: }
3916: fprintf(ficresstdeij,"\n");
3917:
3918: pstamp(ficrescveij);
3919: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3920: fprintf(ficrescveij,"# Age");
3921: for(i=1; i<=nlstate;i++)
3922: for(j=1; j<=nlstate;j++){
3923: cptj= (j-1)*nlstate+i;
3924: for(i2=1; i2<=nlstate;i2++)
3925: for(j2=1; j2<=nlstate;j2++){
3926: cptj2= (j2-1)*nlstate+i2;
3927: if(cptj2 <= cptj)
3928: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3929: }
3930: }
3931: fprintf(ficrescveij,"\n");
3932:
3933: if(estepm < stepm){
3934: printf ("Problem %d lower than %d\n",estepm, stepm);
3935: }
3936: else hstepm=estepm;
3937: /* We compute the life expectancy from trapezoids spaced every estepm months
3938: * This is mainly to measure the difference between two models: for example
3939: * if stepm=24 months pijx are given only every 2 years and by summing them
3940: * we are calculating an estimate of the Life Expectancy assuming a linear
3941: * progression in between and thus overestimating or underestimating according
3942: * to the curvature of the survival function. If, for the same date, we
3943: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3944: * to compare the new estimate of Life expectancy with the same linear
3945: * hypothesis. A more precise result, taking into account a more precise
3946: * curvature will be obtained if estepm is as small as stepm. */
3947:
3948: /* For example we decided to compute the life expectancy with the smallest unit */
3949: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3950: nhstepm is the number of hstepm from age to agelim
3951: nstepm is the number of stepm from age to agelin.
3952: Look at hpijx to understand the reason of that which relies in memory size
3953: and note for a fixed period like estepm months */
3954: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3955: survival function given by stepm (the optimization length). Unfortunately it
3956: means that if the survival funtion is printed only each two years of age and if
3957: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3958: results. So we changed our mind and took the option of the best precision.
3959: */
3960: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3961:
3962: /* If stepm=6 months */
3963: /* nhstepm age range expressed in number of stepm */
3964: agelim=AGESUP;
3965: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3966: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3967: /* if (stepm >= YEARM) hstepm=1;*/
3968: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3969:
3970: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3971: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3972: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3973: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3974: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3975: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3976:
3977: for (age=bage; age<=fage; age ++){
3978: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3979: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3980: /* if (stepm >= YEARM) hstepm=1;*/
3981: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3982:
3983: /* If stepm=6 months */
3984: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3985: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3986:
3987: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3988:
3989: /* Computing Variances of health expectancies */
3990: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3991: decrease memory allocation */
3992: for(theta=1; theta <=npar; theta++){
3993: for(i=1; i<=npar; i++){
3994: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3995: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3996: }
3997: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3998: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3999:
4000: for(j=1; j<= nlstate; j++){
4001: for(i=1; i<=nlstate; i++){
4002: for(h=0; h<=nhstepm-1; h++){
4003: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
4004: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
4005: }
4006: }
4007: }
4008:
4009: for(ij=1; ij<= nlstate*nlstate; ij++)
4010: for(h=0; h<=nhstepm-1; h++){
4011: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
4012: }
4013: }/* End theta */
4014:
4015:
4016: for(h=0; h<=nhstepm-1; h++)
4017: for(j=1; j<=nlstate*nlstate;j++)
4018: for(theta=1; theta <=npar; theta++)
4019: trgradg[h][j][theta]=gradg[h][theta][j];
4020:
4021:
4022: for(ij=1;ij<=nlstate*nlstate;ij++)
4023: for(ji=1;ji<=nlstate*nlstate;ji++)
4024: varhe[ij][ji][(int)age] =0.;
4025:
4026: printf("%d|",(int)age);fflush(stdout);
4027: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4028: for(h=0;h<=nhstepm-1;h++){
4029: for(k=0;k<=nhstepm-1;k++){
4030: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
4031: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
4032: for(ij=1;ij<=nlstate*nlstate;ij++)
4033: for(ji=1;ji<=nlstate*nlstate;ji++)
4034: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
4035: }
4036: }
4037:
4038: /* Computing expectancies */
4039: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4040: for(i=1; i<=nlstate;i++)
4041: for(j=1; j<=nlstate;j++)
4042: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4043: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
4044:
4045: /* 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]);*/
4046:
4047: }
4048:
4049: fprintf(ficresstdeij,"%3.0f",age );
4050: for(i=1; i<=nlstate;i++){
4051: eip=0.;
4052: vip=0.;
4053: for(j=1; j<=nlstate;j++){
4054: eip += eij[i][j][(int)age];
4055: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4056: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4057: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4058: }
4059: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4060: }
4061: fprintf(ficresstdeij,"\n");
4062:
4063: fprintf(ficrescveij,"%3.0f",age );
4064: for(i=1; i<=nlstate;i++)
4065: for(j=1; j<=nlstate;j++){
4066: cptj= (j-1)*nlstate+i;
4067: for(i2=1; i2<=nlstate;i2++)
4068: for(j2=1; j2<=nlstate;j2++){
4069: cptj2= (j2-1)*nlstate+i2;
4070: if(cptj2 <= cptj)
4071: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4072: }
4073: }
4074: fprintf(ficrescveij,"\n");
4075:
4076: }
4077: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4078: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4079: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4080: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4081: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4082: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4083: printf("\n");
4084: fprintf(ficlog,"\n");
4085:
4086: free_vector(xm,1,npar);
4087: free_vector(xp,1,npar);
4088: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4089: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4090: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4091: }
4092:
4093: /************ Variance ******************/
1.209 brouard 4094: 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 *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126 brouard 4095: {
4096: /* Variance of health expectancies */
4097: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4098: /* double **newm;*/
1.169 brouard 4099: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4100:
4101: int movingaverage();
1.126 brouard 4102: double **dnewm,**doldm;
4103: double **dnewmp,**doldmp;
4104: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 4105: int k;
1.126 brouard 4106: double *xp;
4107: double **gp, **gm; /* for var eij */
4108: double ***gradg, ***trgradg; /*for var eij */
4109: double **gradgp, **trgradgp; /* for var p point j */
4110: double *gpp, *gmp; /* for var p point j */
4111: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4112: double ***p3mat;
4113: double age,agelim, hf;
4114: double ***mobaverage;
4115: int theta;
4116: char digit[4];
4117: char digitp[25];
4118:
4119: char fileresprobmorprev[FILENAMELENGTH];
4120:
4121: if(popbased==1){
4122: if(mobilav!=0)
1.201 brouard 4123: strcpy(digitp,"-POPULBASED-MOBILAV_");
4124: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126 brouard 4125: }
4126: else
1.201 brouard 4127: strcpy(digitp,"-STABLBASED_");
1.126 brouard 4128:
4129: if (mobilav!=0) {
4130: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4131: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4132: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4133: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4134: }
4135: }
4136:
1.201 brouard 4137: strcpy(fileresprobmorprev,"PRMORPREV-");
1.126 brouard 4138: sprintf(digit,"%-d",ij);
4139: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4140: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4141: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202 brouard 4142: strcat(fileresprobmorprev,fileresu);
1.126 brouard 4143: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4144: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4145: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4146: }
4147: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4148: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4149: pstamp(ficresprobmorprev);
4150: 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);
4151: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4152: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4153: fprintf(ficresprobmorprev," p.%-d SE",j);
4154: for(i=1; i<=nlstate;i++)
4155: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4156: }
4157: fprintf(ficresprobmorprev,"\n");
1.208 brouard 4158:
1.126 brouard 4159: fprintf(ficgp,"\n# Routine varevsij");
1.200 brouard 4160: fprintf(ficgp,"\nunset title \n");
4161: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126 brouard 4162: 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");
4163: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4164: /* } */
4165: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4166: pstamp(ficresvij);
4167: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4168: if(popbased==1)
1.128 brouard 4169: 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 4170: else
4171: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4172: fprintf(ficresvij,"# Age");
4173: for(i=1; i<=nlstate;i++)
4174: for(j=1; j<=nlstate;j++)
4175: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4176: fprintf(ficresvij,"\n");
4177:
4178: xp=vector(1,npar);
4179: dnewm=matrix(1,nlstate,1,npar);
4180: doldm=matrix(1,nlstate,1,nlstate);
4181: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4182: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4183:
4184: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4185: gpp=vector(nlstate+1,nlstate+ndeath);
4186: gmp=vector(nlstate+1,nlstate+ndeath);
4187: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4188:
4189: if(estepm < stepm){
4190: printf ("Problem %d lower than %d\n",estepm, stepm);
4191: }
4192: else hstepm=estepm;
4193: /* For example we decided to compute the life expectancy with the smallest unit */
4194: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4195: nhstepm is the number of hstepm from age to agelim
1.208 brouard 4196: nstepm is the number of stepm from age to agelim.
1.209 brouard 4197: Look at function hpijx to understand why because of memory size limitations,
1.208 brouard 4198: we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126 brouard 4199: survival function given by stepm (the optimization length). Unfortunately it
4200: means that if the survival funtion is printed every two years of age and if
4201: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4202: results. So we changed our mind and took the option of the best precision.
4203: */
4204: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4205: agelim = AGESUP;
4206: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4207: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4208: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4209: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4210: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4211: gp=matrix(0,nhstepm,1,nlstate);
4212: gm=matrix(0,nhstepm,1,nlstate);
4213:
4214:
4215: for(theta=1; theta <=npar; theta++){
4216: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4217: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4218: }
1.209 brouard 4219:
4220: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126 brouard 4221:
4222: if (popbased==1) {
4223: if(mobilav ==0){
4224: for(i=1; i<=nlstate;i++)
4225: prlim[i][i]=probs[(int)age][i][ij];
4226: }else{ /* mobilav */
4227: for(i=1; i<=nlstate;i++)
4228: prlim[i][i]=mobaverage[(int)age][i][ij];
4229: }
4230: }
4231:
1.209 brouard 4232: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126 brouard 4233: for(j=1; j<= nlstate; j++){
4234: for(h=0; h<=nhstepm; h++){
4235: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4236: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4237: }
4238: }
1.209 brouard 4239: /* Next for computing probability of death (h=1 means
1.126 brouard 4240: computed over hstepm matrices product = hstepm*stepm months)
4241: as a weighted average of prlim.
4242: */
4243: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4244: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4245: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4246: }
4247: /* end probability of death */
4248:
4249: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4250: xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209 brouard 4251:
4252: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126 brouard 4253:
4254: if (popbased==1) {
4255: if(mobilav ==0){
4256: for(i=1; i<=nlstate;i++)
4257: prlim[i][i]=probs[(int)age][i][ij];
4258: }else{ /* mobilav */
4259: for(i=1; i<=nlstate;i++)
4260: prlim[i][i]=mobaverage[(int)age][i][ij];
4261: }
4262: }
4263:
1.209 brouard 4264: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4265:
1.128 brouard 4266: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 4267: for(h=0; h<=nhstepm; h++){
4268: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4269: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4270: }
4271: }
4272: /* This for computing probability of death (h=1 means
4273: computed over hstepm matrices product = hstepm*stepm months)
4274: as a weighted average of prlim.
4275: */
4276: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4277: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4278: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4279: }
4280: /* end probability of death */
4281:
4282: for(j=1; j<= nlstate; j++) /* vareij */
4283: for(h=0; h<=nhstepm; h++){
4284: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4285: }
4286:
4287: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4288: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4289: }
4290:
4291: } /* End theta */
4292:
4293: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4294:
4295: for(h=0; h<=nhstepm; h++) /* veij */
4296: for(j=1; j<=nlstate;j++)
4297: for(theta=1; theta <=npar; theta++)
4298: trgradg[h][j][theta]=gradg[h][theta][j];
4299:
4300: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4301: for(theta=1; theta <=npar; theta++)
4302: trgradgp[j][theta]=gradgp[theta][j];
4303:
4304:
4305: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4306: for(i=1;i<=nlstate;i++)
4307: for(j=1;j<=nlstate;j++)
4308: vareij[i][j][(int)age] =0.;
4309:
4310: for(h=0;h<=nhstepm;h++){
4311: for(k=0;k<=nhstepm;k++){
4312: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4313: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4314: for(i=1;i<=nlstate;i++)
4315: for(j=1;j<=nlstate;j++)
4316: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4317: }
4318: }
4319:
4320: /* pptj */
4321: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4322: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4323: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4324: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4325: varppt[j][i]=doldmp[j][i];
4326: /* end ppptj */
4327: /* x centered again */
1.209 brouard 4328:
4329: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126 brouard 4330:
4331: if (popbased==1) {
4332: if(mobilav ==0){
4333: for(i=1; i<=nlstate;i++)
4334: prlim[i][i]=probs[(int)age][i][ij];
4335: }else{ /* mobilav */
4336: for(i=1; i<=nlstate;i++)
4337: prlim[i][i]=mobaverage[(int)age][i][ij];
4338: }
4339: }
4340:
4341: /* This for computing probability of death (h=1 means
4342: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4343: as a weighted average of prlim.
4344: */
1.209 brouard 4345: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
1.126 brouard 4346: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4347: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4348: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4349: }
4350: /* end probability of death */
4351:
4352: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4353: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4354: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4355: for(i=1; i<=nlstate;i++){
4356: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4357: }
4358: }
4359: fprintf(ficresprobmorprev,"\n");
4360:
4361: fprintf(ficresvij,"%.0f ",age );
4362: for(i=1; i<=nlstate;i++)
4363: for(j=1; j<=nlstate;j++){
4364: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4365: }
4366: fprintf(ficresvij,"\n");
4367: free_matrix(gp,0,nhstepm,1,nlstate);
4368: free_matrix(gm,0,nhstepm,1,nlstate);
4369: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4370: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4371: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4372: } /* End age */
4373: free_vector(gpp,nlstate+1,nlstate+ndeath);
4374: free_vector(gmp,nlstate+1,nlstate+ndeath);
4375: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4376: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199 brouard 4377: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4378: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126 brouard 4379: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4380: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201 brouard 4381: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4382: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4383: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4384: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4385: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4386: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4387: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4388: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201 brouard 4389: 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);
1.199 brouard 4390: /* 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 4391: */
1.199 brouard 4392: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201 brouard 4393: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4394:
4395: free_vector(xp,1,npar);
4396: free_matrix(doldm,1,nlstate,1,nlstate);
4397: free_matrix(dnewm,1,nlstate,1,npar);
4398: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4399: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4400: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4401: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4402: fclose(ficresprobmorprev);
4403: fflush(ficgp);
4404: fflush(fichtm);
4405: } /* end varevsij */
4406:
4407: /************ Variance of prevlim ******************/
1.209 brouard 4408: 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 *ncvyearp, int ij, char strstart[])
1.126 brouard 4409: {
1.205 brouard 4410: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126 brouard 4411: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4412:
1.126 brouard 4413: double **dnewm,**doldm;
4414: int i, j, nhstepm, hstepm;
4415: double *xp;
4416: double *gp, *gm;
4417: double **gradg, **trgradg;
1.208 brouard 4418: double **mgm, **mgp;
1.126 brouard 4419: double age,agelim;
4420: int theta;
4421:
4422: pstamp(ficresvpl);
4423: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4424: fprintf(ficresvpl,"# Age");
4425: for(i=1; i<=nlstate;i++)
4426: fprintf(ficresvpl," %1d-%1d",i,i);
4427: fprintf(ficresvpl,"\n");
4428:
4429: xp=vector(1,npar);
4430: dnewm=matrix(1,nlstate,1,npar);
4431: doldm=matrix(1,nlstate,1,nlstate);
4432:
4433: hstepm=1*YEARM; /* Every year of age */
4434: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4435: agelim = AGESUP;
4436: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4437: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4438: if (stepm >= YEARM) hstepm=1;
4439: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4440: gradg=matrix(1,npar,1,nlstate);
1.208 brouard 4441: mgp=matrix(1,npar,1,nlstate);
4442: mgm=matrix(1,npar,1,nlstate);
1.126 brouard 4443: gp=vector(1,nlstate);
4444: gm=vector(1,nlstate);
4445:
4446: for(theta=1; theta <=npar; theta++){
4447: for(i=1; i<=npar; i++){ /* Computes gradient */
4448: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4449: }
1.209 brouard 4450: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4451: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4452: else
4453: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208 brouard 4454: for(i=1;i<=nlstate;i++){
1.126 brouard 4455: gp[i] = prlim[i][i];
1.208 brouard 4456: mgp[theta][i] = prlim[i][i];
4457: }
1.126 brouard 4458: for(i=1; i<=npar; i++) /* Computes gradient */
4459: xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209 brouard 4460: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4461: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4462: else
4463: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208 brouard 4464: for(i=1;i<=nlstate;i++){
1.126 brouard 4465: gm[i] = prlim[i][i];
1.208 brouard 4466: mgm[theta][i] = prlim[i][i];
4467: }
1.126 brouard 4468: for(i=1;i<=nlstate;i++)
4469: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209 brouard 4470: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126 brouard 4471: } /* End theta */
4472:
4473: trgradg =matrix(1,nlstate,1,npar);
4474:
4475: for(j=1; j<=nlstate;j++)
4476: for(theta=1; theta <=npar; theta++)
4477: trgradg[j][theta]=gradg[theta][j];
1.209 brouard 4478: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4479: /* printf("\nmgm mgp %d ",(int)age); */
4480: /* for(j=1; j<=nlstate;j++){ */
4481: /* printf(" %d ",j); */
4482: /* for(theta=1; theta <=npar; theta++) */
4483: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4484: /* printf("\n "); */
4485: /* } */
4486: /* } */
4487: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4488: /* printf("\n gradg %d ",(int)age); */
4489: /* for(j=1; j<=nlstate;j++){ */
4490: /* printf("%d ",j); */
4491: /* for(theta=1; theta <=npar; theta++) */
4492: /* printf("%d %lf ",theta,gradg[theta][j]); */
4493: /* printf("\n "); */
4494: /* } */
4495: /* } */
1.126 brouard 4496:
4497: for(i=1;i<=nlstate;i++)
4498: varpl[i][(int)age] =0.;
1.209 brouard 4499: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
1.205 brouard 4500: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4501: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4502: }else{
1.126 brouard 4503: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4504: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205 brouard 4505: }
1.126 brouard 4506: for(i=1;i<=nlstate;i++)
4507: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4508:
4509: fprintf(ficresvpl,"%.0f ",age );
4510: for(i=1; i<=nlstate;i++)
4511: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4512: fprintf(ficresvpl,"\n");
4513: free_vector(gp,1,nlstate);
4514: free_vector(gm,1,nlstate);
1.208 brouard 4515: free_matrix(mgm,1,npar,1,nlstate);
4516: free_matrix(mgp,1,npar,1,nlstate);
1.126 brouard 4517: free_matrix(gradg,1,npar,1,nlstate);
4518: free_matrix(trgradg,1,nlstate,1,npar);
4519: } /* End age */
4520:
4521: free_vector(xp,1,npar);
4522: free_matrix(doldm,1,nlstate,1,npar);
4523: free_matrix(dnewm,1,nlstate,1,nlstate);
4524:
4525: }
4526:
4527: /************ Variance of one-step probabilities ******************/
4528: 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[])
4529: {
1.164 brouard 4530: int i, j=0, k1, l1, tj;
1.126 brouard 4531: int k2, l2, j1, z1;
1.164 brouard 4532: int k=0, l;
1.145 brouard 4533: int first=1, first1, first2;
1.126 brouard 4534: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4535: double **dnewm,**doldm;
4536: double *xp;
4537: double *gp, *gm;
4538: double **gradg, **trgradg;
4539: double **mu;
1.164 brouard 4540: double age, cov[NCOVMAX+1];
1.126 brouard 4541: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4542: int theta;
4543: char fileresprob[FILENAMELENGTH];
4544: char fileresprobcov[FILENAMELENGTH];
4545: char fileresprobcor[FILENAMELENGTH];
4546: double ***varpij;
4547:
1.201 brouard 4548: strcpy(fileresprob,"PROB_");
1.126 brouard 4549: strcat(fileresprob,fileres);
4550: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4551: printf("Problem with resultfile: %s\n", fileresprob);
4552: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4553: }
1.201 brouard 4554: strcpy(fileresprobcov,"PROBCOV_");
1.202 brouard 4555: strcat(fileresprobcov,fileresu);
1.126 brouard 4556: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4557: printf("Problem with resultfile: %s\n", fileresprobcov);
4558: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4559: }
1.201 brouard 4560: strcpy(fileresprobcor,"PROBCOR_");
1.202 brouard 4561: strcat(fileresprobcor,fileresu);
1.126 brouard 4562: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4563: printf("Problem with resultfile: %s\n", fileresprobcor);
4564: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4565: }
4566: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4567: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4568: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4569: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4570: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4571: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4572: pstamp(ficresprob);
4573: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4574: fprintf(ficresprob,"# Age");
4575: pstamp(ficresprobcov);
4576: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4577: fprintf(ficresprobcov,"# Age");
4578: pstamp(ficresprobcor);
4579: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4580: fprintf(ficresprobcor,"# Age");
4581:
4582:
4583: for(i=1; i<=nlstate;i++)
4584: for(j=1; j<=(nlstate+ndeath);j++){
4585: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4586: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4587: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4588: }
4589: /* fprintf(ficresprob,"\n");
4590: fprintf(ficresprobcov,"\n");
4591: fprintf(ficresprobcor,"\n");
4592: */
1.131 brouard 4593: xp=vector(1,npar);
1.126 brouard 4594: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4595: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4596: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4597: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4598: first=1;
4599: fprintf(ficgp,"\n# Routine varprob");
4600: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4601: fprintf(fichtm,"\n");
4602:
1.200 brouard 4603: 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 4604: 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);
4605: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126 brouard 4606: and drawn. It helps understanding how is the covariance between two incidences.\
4607: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4608: 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. \
4609: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4610: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4611: standard deviations wide on each axis. <br>\
4612: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4613: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4614: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4615:
4616: cov[1]=1;
1.145 brouard 4617: /* tj=cptcoveff; */
4618: tj = (int) pow(2,cptcoveff);
1.126 brouard 4619: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4620: j1=0;
1.145 brouard 4621: for(j1=1; j1<=tj;j1++){
4622: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4623: /*j1++;*/
1.126 brouard 4624: if (cptcovn>0) {
4625: fprintf(ficresprob, "\n#********** Variable ");
1.198 brouard 4626: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4627: fprintf(ficresprob, "**********\n#\n");
4628: fprintf(ficresprobcov, "\n#********** Variable ");
1.198 brouard 4629: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4630: fprintf(ficresprobcov, "**********\n#\n");
4631:
4632: fprintf(ficgp, "\n#********** Variable ");
1.198 brouard 4633: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4634: fprintf(ficgp, "**********\n#\n");
4635:
4636:
4637: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
1.198 brouard 4638: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4639: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4640:
4641: fprintf(ficresprobcor, "\n#********** Variable ");
1.198 brouard 4642: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4643: fprintf(ficresprobcor, "**********\n#");
4644: }
4645:
1.145 brouard 4646: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4647: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4648: gp=vector(1,(nlstate)*(nlstate+ndeath));
4649: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4650: for (age=bage; age<=fage; age ++){
4651: cov[2]=age;
1.187 brouard 4652: if(nagesqr==1)
4653: cov[3]= age*age;
1.126 brouard 4654: for (k=1; k<=cptcovn;k++) {
1.200 brouard 4655: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4656: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145 brouard 4657: * 1 1 1 1 1
4658: * 2 2 1 1 1
4659: * 3 1 2 1 1
4660: */
4661: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4662: }
1.186 brouard 4663: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 4664: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126 brouard 4665: for (k=1; k<=cptcovprod;k++)
1.200 brouard 4666: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126 brouard 4667:
4668:
4669: for(theta=1; theta <=npar; theta++){
4670: for(i=1; i<=npar; i++)
4671: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4672:
4673: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4674:
4675: k=0;
4676: for(i=1; i<= (nlstate); i++){
4677: for(j=1; j<=(nlstate+ndeath);j++){
4678: k=k+1;
4679: gp[k]=pmmij[i][j];
4680: }
4681: }
4682:
4683: for(i=1; i<=npar; i++)
4684: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4685:
4686: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4687: k=0;
4688: for(i=1; i<=(nlstate); i++){
4689: for(j=1; j<=(nlstate+ndeath);j++){
4690: k=k+1;
4691: gm[k]=pmmij[i][j];
4692: }
4693: }
4694:
4695: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4696: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4697: }
4698:
4699: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4700: for(theta=1; theta <=npar; theta++)
4701: trgradg[j][theta]=gradg[theta][j];
4702:
4703: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4704: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4705:
4706: pmij(pmmij,cov,ncovmodel,x,nlstate);
4707:
4708: k=0;
4709: for(i=1; i<=(nlstate); i++){
4710: for(j=1; j<=(nlstate+ndeath);j++){
4711: k=k+1;
4712: mu[k][(int) age]=pmmij[i][j];
4713: }
4714: }
4715: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4716: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4717: varpij[i][j][(int)age] = doldm[i][j];
4718:
4719: /*printf("\n%d ",(int)age);
4720: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4721: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4722: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4723: }*/
4724:
4725: fprintf(ficresprob,"\n%d ",(int)age);
4726: fprintf(ficresprobcov,"\n%d ",(int)age);
4727: fprintf(ficresprobcor,"\n%d ",(int)age);
4728:
4729: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4730: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4731: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4732: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4733: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4734: }
4735: i=0;
4736: for (k=1; k<=(nlstate);k++){
4737: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4738: i++;
1.126 brouard 4739: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4740: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4741: for (j=1; j<=i;j++){
1.145 brouard 4742: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4743: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4744: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4745: }
4746: }
4747: }/* end of loop for state */
4748: } /* end of loop for age */
1.145 brouard 4749: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4750: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4751: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4752: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4753:
1.126 brouard 4754: /* Confidence intervalle of pij */
4755: /*
1.131 brouard 4756: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4757: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4758: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4759: 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);
4760: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4761: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4762: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4763: */
4764:
4765: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4766: first1=1;first2=2;
1.126 brouard 4767: for (k2=1; k2<=(nlstate);k2++){
4768: for (l2=1; l2<=(nlstate+ndeath);l2++){
4769: if(l2==k2) continue;
4770: j=(k2-1)*(nlstate+ndeath)+l2;
4771: for (k1=1; k1<=(nlstate);k1++){
4772: for (l1=1; l1<=(nlstate+ndeath);l1++){
4773: if(l1==k1) continue;
4774: i=(k1-1)*(nlstate+ndeath)+l1;
4775: if(i<=j) continue;
4776: for (age=bage; age<=fage; age ++){
4777: if ((int)age %5==0){
4778: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4779: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4780: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4781: mu1=mu[i][(int) age]/stepm*YEARM ;
4782: mu2=mu[j][(int) age]/stepm*YEARM;
4783: c12=cv12/sqrt(v1*v2);
4784: /* Computing eigen value of matrix of covariance */
4785: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4786: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4787: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4788: if(first2==1){
4789: first1=0;
4790: 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);
4791: }
4792: 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);
4793: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4794: /* lc2=fabs(lc2); */
1.135 brouard 4795: }
4796:
1.126 brouard 4797: /* Eigen vectors */
4798: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4799: /*v21=sqrt(1.-v11*v11); *//* error */
4800: v21=(lc1-v1)/cv12*v11;
4801: v12=-v21;
4802: v22=v11;
4803: tnalp=v21/v11;
4804: if(first1==1){
4805: first1=0;
4806: 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);
4807: }
4808: 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);
4809: /*printf(fignu*/
4810: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4811: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4812: if(first==1){
4813: first=0;
1.200 brouard 4814: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126 brouard 4815: fprintf(ficgp,"\nset parametric;unset label");
4816: 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 4817: fprintf(ficgp,"\nset ter svg size 640, 480");
1.126 brouard 4818: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201 brouard 4819: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4820: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4821: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4822: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4823: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4824: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201 brouard 4825: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4826: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4827: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4828: 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",\
4829: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4830: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4831: }else{
4832: first=0;
4833: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4834: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4835: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4836: 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",\
4837: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4838: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4839: }/* if first */
4840: } /* age mod 5 */
4841: } /* end loop age */
1.201 brouard 4842: 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 4843: first=1;
4844: } /*l12 */
4845: } /* k12 */
4846: } /*l1 */
4847: }/* k1 */
1.169 brouard 4848: /* } */ /* loop covariates */
1.126 brouard 4849: }
4850: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4851: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4852: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4853: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4854: free_vector(xp,1,npar);
4855: fclose(ficresprob);
4856: fclose(ficresprobcov);
4857: fclose(ficresprobcor);
4858: fflush(ficgp);
4859: fflush(fichtmcov);
4860: }
4861:
4862:
4863: /******************* Printing html file ***********/
1.201 brouard 4864: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 4865: int lastpass, int stepm, int weightopt, char model[],\
4866: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211 brouard 4867: int popforecast, int prevfcast, int estepm , \
1.213 ! brouard 4868: double jprev1, double mprev1,double anprev1, double dateprev1, \
! 4869: double jprev2, double mprev2,double anprev2, double dateprev2){
1.126 brouard 4870: int jj1, k1, i1, cpt;
4871:
4872: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4873: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4874: </ul>");
4875: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
1.213 ! brouard 4876: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
! 4877: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
! 4878: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126 brouard 4879: fprintf(fichtm,"\
4880: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201 brouard 4881: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126 brouard 4882: fprintf(fichtm,"\
4883: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4884: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126 brouard 4885: fprintf(fichtm,"\
1.211 brouard 4886: - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . 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 4887: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4888: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211 brouard 4889: if(prevfcast==1){
4890: fprintf(fichtm,"\
4891: - Prevalence projections by age and states: \
1.201 brouard 4892: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211 brouard 4893: }
1.126 brouard 4894:
4895: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4896:
1.145 brouard 4897: m=pow(2,cptcoveff);
1.126 brouard 4898: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4899:
4900: jj1=0;
4901: for(k1=1; k1<=m;k1++){
1.192 brouard 4902: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4903: jj1++;
4904: if (cptcovn > 0) {
4905: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4906: for (cpt=1; cpt<=cptcoveff;cpt++){
1.198 brouard 4907: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4908: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192 brouard 4909: }
1.126 brouard 4910: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4911: }
1.201 brouard 4912: /* aij, bij */
1.211 brouard 4913: fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
4914: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4915: /* Pij */
1.211 brouard 4916: fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201 brouard 4917: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4918: /* Quasi-incidences */
1.211 brouard 4919: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.201 brouard 4920: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211 brouard 4921: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
4922: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201 brouard 4923: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4924: /* Survival functions (period) in state j */
4925: for(cpt=1; cpt<=nlstate;cpt++){
4926: fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
4927: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4928: }
4929: /* State specific survival functions (period) */
4930: for(cpt=1; cpt<=nlstate;cpt++){
1.208 brouard 4931: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201 brouard 4932: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4933: <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
4934: }
4935: /* Period (stable) prevalence in each health state */
4936: for(cpt=1; cpt<=nlstate;cpt++){
4937: fprintf(fichtm,"<br>\n- 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> \
4938: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4939: }
1.211 brouard 4940: if(prevfcast==1){
4941: /* Projection of prevalence up to period (stable) prevalence in each health state */
4942: for(cpt=1; cpt<=nlstate;cpt++){
1.213 ! brouard 4943: fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %f to %f) up 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> \
! 4944: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
1.211 brouard 4945: }
4946: }
4947:
1.126 brouard 4948: for(cpt=1; cpt<=nlstate;cpt++) {
1.205 brouard 4949: 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) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
1.201 brouard 4950: <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 4951: }
1.192 brouard 4952: /* } /\* end i1 *\/ */
1.126 brouard 4953: }/* End k1 */
4954: fprintf(fichtm,"</ul>");
4955:
4956: fprintf(fichtm,"\
4957: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4958: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203 brouard 4959: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197 brouard 4960: But because parameters are usually highly correlated (a higher incidence of disability \
4961: and a higher incidence of recovery can give very close observed transition) it might \
4962: be very useful to look not only at linear confidence intervals estimated from the \
4963: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4964: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4965: covariance matrix of the one-step probabilities. \
4966: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126 brouard 4967:
1.193 brouard 4968: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4969: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126 brouard 4970: fprintf(fichtm,"\
4971: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4972: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126 brouard 4973:
4974: fprintf(fichtm,"\
4975: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4976: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126 brouard 4977: fprintf(fichtm,"\
4978: - 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): \
4979: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4980: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126 brouard 4981: fprintf(fichtm,"\
4982: - (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): \
4983: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4984: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126 brouard 4985: fprintf(fichtm,"\
1.128 brouard 4986: - 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.201 brouard 4987: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126 brouard 4988: fprintf(fichtm,"\
1.128 brouard 4989: - 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",
1.201 brouard 4990: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126 brouard 4991: fprintf(fichtm,"\
4992: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201 brouard 4993: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126 brouard 4994:
4995: /* if(popforecast==1) fprintf(fichtm,"\n */
4996: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4997: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4998: /* <br>",fileres,fileres,fileres,fileres); */
4999: /* else */
5000: /* 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); */
5001: fflush(fichtm);
5002: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
5003:
1.145 brouard 5004: m=pow(2,cptcoveff);
1.126 brouard 5005: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5006:
5007: jj1=0;
5008: for(k1=1; k1<=m;k1++){
1.192 brouard 5009: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 5010: jj1++;
5011: if (cptcovn > 0) {
5012: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5013: for (cpt=1; cpt<=cptcoveff;cpt++)
1.198 brouard 5014: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126 brouard 5015: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5016: }
5017: for(cpt=1; cpt<=nlstate;cpt++) {
5018: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205 brouard 5019: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
5020: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
1.126 brouard 5021: }
5022: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 5023: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
5024: true period expectancies (those weighted with period prevalences are also\
5025: drawn in addition to the population based expectancies computed using\
1.205 brouard 5026: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
5027: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192 brouard 5028: /* } /\* end i1 *\/ */
1.126 brouard 5029: }/* End k1 */
5030: fprintf(fichtm,"</ul>");
5031: fflush(fichtm);
5032: }
5033:
5034: /******************* Gnuplot file **************/
1.211 brouard 5035: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126 brouard 5036:
5037: char dirfileres[132],optfileres[132];
1.164 brouard 5038: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211 brouard 5039: int lv=0, vlv=0, kl=0;
1.130 brouard 5040: int ng=0;
1.201 brouard 5041: int vpopbased;
1.126 brouard 5042: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
5043: /* printf("Problem with file %s",optionfilegnuplot); */
5044: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
5045: /* } */
5046:
5047: /*#ifdef windows */
5048: fprintf(ficgp,"cd \"%s\" \n",pathc);
5049: /*#endif */
5050: m=pow(2,cptcoveff);
5051:
1.202 brouard 5052: /* Contribution to likelihood */
5053: /* Plot the probability implied in the likelihood */
5054: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5055: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5056: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205 brouard 5057: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204 brouard 5058: /* nice for mle=4 plot by number of matrix products.
1.202 brouard 5059: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5060: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5061: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204 brouard 5062: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 brouard 5063: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
1.204 brouard 5064: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 brouard 5065: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
1.204 brouard 5066: for (i=1; i<= nlstate ; i ++) {
5067: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205 brouard 5068: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5069: fprintf(ficgp," u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
1.204 brouard 5070: for (j=2; j<= nlstate+ndeath ; j ++) {
1.205 brouard 5071: fprintf(ficgp,",\\\n \"\" u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
1.204 brouard 5072: }
5073: fprintf(ficgp,";\nset out; unset ylabel;\n");
5074: }
5075: /* unset log; plot "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */
5076: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5077: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
1.203 brouard 5078: fprintf(ficgp,"\nset out;unset log\n");
1.202 brouard 5079: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5080:
1.126 brouard 5081: strcpy(dirfileres,optionfilefiname);
5082: strcpy(optfileres,"vpl");
5083: /* 1eme*/
1.211 brouard 5084: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5085: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5086: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5087: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5088: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5089: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5090: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5091: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5092: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5093: vlv= nbcode[Tvaraff[lv]][lv];
5094: fprintf(ficgp," V%d=%d ",k,vlv);
5095: }
5096: fprintf(ficgp,"\n#\n");
5097:
1.201 brouard 5098: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5099: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126 brouard 5100: fprintf(ficgp,"set xlabel \"Age\" \n\
5101: set ylabel \"Probability\" \n\
1.199 brouard 5102: set ter svg size 640, 480\n\
1.201 brouard 5103: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126 brouard 5104:
5105: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5106: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5107: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5108: }
1.201 brouard 5109: fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126 brouard 5110: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5111: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5112: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5113: }
1.201 brouard 5114: fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126 brouard 5115: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5116: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5117: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5118: }
1.201 brouard 5119: fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
5120: fprintf(ficgp,"\nset out \n");
5121: } /* k1 */
5122: } /* cpt */
1.126 brouard 5123: /*2 eme*/
5124: for (k1=1; k1<= m ; k1 ++) {
1.211 brouard 5125: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5126: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5127: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5128: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5129: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5130: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5131: vlv= nbcode[Tvaraff[lv]][lv];
5132: fprintf(ficgp," V%d=%d ",k,vlv);
5133: }
5134: fprintf(ficgp,"\n#\n");
5135:
1.201 brouard 5136: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5137: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5138: if(vpopbased==0)
5139: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5140: else
5141: fprintf(ficgp,"\nreplot ");
5142: for (i=1; i<= nlstate+1 ; i ++) {
5143: k=2*i;
5144: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
5145: for (j=1; j<= nlstate+1 ; j ++) {
5146: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5147: else fprintf(ficgp," %%*lf (%%*lf)");
5148: }
5149: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5150: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5151: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
5152: for (j=1; j<= nlstate+1 ; j ++) {
5153: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5154: else fprintf(ficgp," %%*lf (%%*lf)");
5155: }
5156: fprintf(ficgp,"\" t\"\" w l lt 0,");
5157: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
5158: for (j=1; j<= nlstate+1 ; j ++) {
5159: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5160: else fprintf(ficgp," %%*lf (%%*lf)");
5161: }
5162: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5163: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5164: } /* state */
5165: } /* vpopbased */
5166: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5167: } /* k1 */
1.211 brouard 5168:
5169:
1.126 brouard 5170: /*3eme*/
5171: for (k1=1; k1<= m ; k1 ++) {
5172: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211 brouard 5173: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5174: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5175: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5176: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5177: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5178: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5179: vlv= nbcode[Tvaraff[lv]][lv];
5180: fprintf(ficgp," V%d=%d ",k,vlv);
5181: }
5182: fprintf(ficgp,"\n#\n");
5183:
1.126 brouard 5184: /* k=2+nlstate*(2*cpt-2); */
5185: k=2+(nlstate+1)*(cpt-1);
1.201 brouard 5186: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199 brouard 5187: fprintf(ficgp,"set ter svg size 640, 480\n\
1.201 brouard 5188: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.126 brouard 5189: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5190: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5191: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5192: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5193: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5194: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5195:
5196: */
5197: for (i=1; i< nlstate ; i ++) {
1.201 brouard 5198: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
1.126 brouard 5199: /* 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);*/
5200:
5201: }
1.201 brouard 5202: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126 brouard 5203: }
5204: }
5205:
1.201 brouard 5206: /* Survival functions (period) from state i in state j by initial state i */
5207: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5208: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211 brouard 5209: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5210: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5211: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5212: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5213: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5214: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5215: vlv= nbcode[Tvaraff[lv]][lv];
5216: fprintf(ficgp," V%d=%d ",k,vlv);
5217: }
5218: fprintf(ficgp,"\n#\n");
5219:
1.201 brouard 5220: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5221: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5222: set ter svg size 640, 480\n\
5223: unset log y\n\
5224: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5225: k=3;
1.201 brouard 5226: for (i=1; i<= nlstate ; i ++){
5227: if(i==1)
5228: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5229: else
5230: fprintf(ficgp,", '' ");
5231: l=(nlstate+ndeath)*(i-1)+1;
5232: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5233: for (j=2; j<= nlstate+ndeath ; j ++)
5234: fprintf(ficgp,"+$%d",k+l+j-1);
5235: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5236: } /* nlstate */
5237: fprintf(ficgp,"\nset out\n");
5238: } /* end cpt state*/
5239: } /* end covariate */
5240:
5241: /* Survival functions (period) from state i in state j by final state j */
1.202 brouard 5242: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201 brouard 5243: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5244: fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
1.211 brouard 5245: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5246: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5247: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5248: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5249: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5250: vlv= nbcode[Tvaraff[lv]][lv];
5251: fprintf(ficgp," V%d=%d ",k,vlv);
5252: }
5253: fprintf(ficgp,"\n#\n");
5254:
1.201 brouard 5255: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5256: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5257: set ter svg size 640, 480\n\
5258: unset log y\n\
5259: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5260: k=3;
1.201 brouard 5261: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5262: if(j==1)
5263: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5264: else
5265: fprintf(ficgp,", '' ");
5266: l=(nlstate+ndeath)*(cpt-1) +j;
5267: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5268: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5269: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5270: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5271: } /* nlstate */
5272: fprintf(ficgp,", '' ");
5273: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5274: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5275: l=(nlstate+ndeath)*(cpt-1) +j;
5276: if(j < nlstate)
5277: fprintf(ficgp,"$%d +",k+l);
5278: else
5279: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5280: }
5281: fprintf(ficgp,"\nset out\n");
5282: } /* end cpt state*/
5283: } /* end covariate */
5284:
1.202 brouard 5285: /* CV preval stable (period) for each covariate */
1.211 brouard 5286: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153 brouard 5287: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211 brouard 5288: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5289: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5290: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5291: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5292: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5293: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5294: vlv= nbcode[Tvaraff[lv]][lv];
5295: fprintf(ficgp," V%d=%d ",k,vlv);
5296: }
5297: fprintf(ficgp,"\n#\n");
5298:
1.201 brouard 5299: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126 brouard 5300: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199 brouard 5301: set ter svg size 640, 480\n\
1.126 brouard 5302: unset log y\n\
1.153 brouard 5303: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5304: k=3; /* Offset */
1.153 brouard 5305: for (i=1; i<= nlstate ; i ++){
5306: if(i==1)
1.201 brouard 5307: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153 brouard 5308: else
5309: fprintf(ficgp,", '' ");
1.154 brouard 5310: l=(nlstate+ndeath)*(i-1)+1;
5311: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201 brouard 5312: for (j=2; j<= nlstate ; j ++)
5313: fprintf(ficgp,"+$%d",k+l+j-1);
1.153 brouard 5314: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5315: } /* nlstate */
1.201 brouard 5316: fprintf(ficgp,"\nset out\n");
1.153 brouard 5317: } /* end cpt state*/
5318: } /* end covariate */
1.201 brouard 5319:
1.211 brouard 5320: if(prevfcast==1){
5321: /* Projection from cross-sectional to stable (period) for each covariate */
5322:
5323: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5324: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5325: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5326: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5327: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5328: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5329: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5330: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5331: vlv= nbcode[Tvaraff[lv]][lv];
5332: fprintf(ficgp," V%d=%d ",k,vlv);
5333: }
5334: fprintf(ficgp,"\n#\n");
5335:
5336: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
5337: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
5338: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
5339: set ter svg size 640, 480\n\
5340: unset log y\n\
5341: plot [%.f:%.f] ", ageminpar, agemaxpar);
5342: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
5343: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5344: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5345: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5346: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5347: if(i==1){
5348: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
5349: }else{
5350: fprintf(ficgp,",\\\n '' ");
5351: }
5352: if(cptcoveff ==0){ /* No covariate */
5353: fprintf(ficgp," u 2:("); /* Age is in 2 */
5354: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
5355: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
5356: if(i==nlstate+1)
5357: fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
5358: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,cpt );
5359: else
5360: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
5361: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5362: }else{
5363: fprintf(ficgp,"u 6:(("); /* Age is in 6 */
5364: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5365: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5366: kl=0;
5367: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
5368: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5369: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5370: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5371: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5372: vlv= nbcode[Tvaraff[lv]][lv];
5373: kl++;
5374: /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
5375: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5376: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5377: /* '' u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
5378: if(k==cptcoveff)
5379: if(i==nlstate+1)
5380: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5381: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,cpt );
5382: else
5383: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5384: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5385: else{
5386: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
5387: kl++;
5388: }
5389: } /* end covariate */
5390: } /* end if covariate */
5391: } /* nlstate */
5392: fprintf(ficgp,"\nset out\n");
5393: } /* end cpt state*/
5394: } /* end covariate */
5395: } /* End if prevfcast */
5396:
5397:
1.126 brouard 5398: /* proba elementaires */
1.187 brouard 5399: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 5400: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 5401: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 5402: for(k=1; k <=(nlstate+ndeath); k++){
5403: if (k != i) {
1.187 brouard 5404: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 5405: for(j=1; j <=ncovmodel; j++){
1.187 brouard 5406: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 5407: jk++;
5408: }
1.187 brouard 5409: fprintf(ficgp,"\n");
1.126 brouard 5410: }
5411: }
5412: }
1.187 brouard 5413: fprintf(ficgp,"##############\n#\n");
5414:
1.145 brouard 5415: /*goto avoid;*/
1.200 brouard 5416: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187 brouard 5417: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5418: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5419: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5420: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5421: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5422: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5423: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5424: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5425: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5426: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5427: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5428: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5429: fprintf(ficgp,"#\n");
1.201 brouard 5430: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187 brouard 5431: fprintf(ficgp,"# ng=%d\n",ng);
5432: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 5433: for(jk=1; jk <=m; jk++) {
1.187 brouard 5434: fprintf(ficgp,"# jk=%d\n",jk);
1.201 brouard 5435: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5436: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5437: if (ng==1){
5438: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5439: fprintf(ficgp,"\nunset log y");
5440: }else if (ng==2){
5441: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5442: fprintf(ficgp,"\nset log y");
5443: }else if (ng==3){
1.126 brouard 5444: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201 brouard 5445: fprintf(ficgp,"\nset log y");
5446: }else
5447: fprintf(ficgp,"\nunset title ");
5448: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 5449: i=1;
5450: for(k2=1; k2<=nlstate; k2++) {
5451: k3=i;
5452: for(k=1; k<=(nlstate+ndeath); k++) {
5453: if (k != k2){
1.201 brouard 5454: switch( ng) {
5455: case 1:
1.187 brouard 5456: if(nagesqr==0)
1.201 brouard 5457: fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187 brouard 5458: else /* nagesqr =1 */
1.201 brouard 5459: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5460: break;
5461: case 2: /* ng=2 */
1.187 brouard 5462: if(nagesqr==0)
5463: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5464: else /* nagesqr =1 */
1.201 brouard 5465: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5466: break;
5467: case 3:
5468: if(nagesqr==0)
5469: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5470: else /* nagesqr =1 */
5471: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5472: break;
5473: }
1.141 brouard 5474: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 5475: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197 brouard 5476: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5477: if(ij <=cptcovage) { /* Bug valgrind */
5478: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200 brouard 5479: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5480: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197 brouard 5481: ij++;
5482: }
1.186 brouard 5483: }
5484: else
1.198 brouard 5485: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 5486: }
1.201 brouard 5487: if(ng != 1){
5488: fprintf(ficgp,")/(1");
1.126 brouard 5489:
1.201 brouard 5490: for(k1=1; k1 <=nlstate; k1++){
5491: if(nagesqr==0)
5492: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5493: else /* nagesqr =1 */
5494: 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);
5495:
5496: ij=1;
5497: for(j=3; j <=ncovmodel-nagesqr; j++){
5498: if(ij <=cptcovage) { /* Bug valgrind */
5499: if((j-2)==Tage[ij]) { /* Bug valgrind */
5500: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5501: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5502: ij++;
5503: }
1.197 brouard 5504: }
1.201 brouard 5505: else
5506: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186 brouard 5507: }
1.201 brouard 5508: fprintf(ficgp,")");
1.126 brouard 5509: }
5510: fprintf(ficgp,")");
1.201 brouard 5511: if(ng ==2)
5512: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5513: else /* ng= 3 */
5514: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5515: }else{ /* end ng <> 1 */
5516: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126 brouard 5517: }
5518: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5519: i=i+ncovmodel;
5520: }
5521: } /* end k */
5522: } /* end k2 */
1.201 brouard 5523: fprintf(ficgp,"\n set out\n");
1.126 brouard 5524: } /* end jk */
5525: } /* end ng */
1.164 brouard 5526: /* avoid: */
1.126 brouard 5527: fflush(ficgp);
5528: } /* end gnuplot */
5529:
5530:
5531: /*************** Moving average **************/
5532: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5533:
5534: int i, cpt, cptcod;
5535: int modcovmax =1;
5536: int mobilavrange, mob;
5537: double age;
5538:
5539: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5540: a covariate has 2 modalities */
5541: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5542:
5543: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5544: if(mobilav==1) mobilavrange=5; /* default */
5545: else mobilavrange=mobilav;
5546: for (age=bage; age<=fage; age++)
5547: for (i=1; i<=nlstate;i++)
5548: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5549: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5550: /* We keep the original values on the extreme ages bage, fage and for
5551: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5552: we use a 5 terms etc. until the borders are no more concerned.
5553: */
5554: for (mob=3;mob <=mobilavrange;mob=mob+2){
5555: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5556: for (i=1; i<=nlstate;i++){
5557: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5558: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5559: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5560: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5561: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5562: }
5563: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5564: }
5565: }
5566: }/* end age */
5567: }/* end mob */
5568: }else return -1;
5569: return 0;
5570: }/* End movingaverage */
5571:
5572:
5573: /************** Forecasting ******************/
1.169 brouard 5574: 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 5575: /* proj1, year, month, day of starting projection
5576: agemin, agemax range of age
5577: dateprev1 dateprev2 range of dates during which prevalence is computed
5578: anproj2 year of en of projection (same day and month as proj1).
5579: */
1.164 brouard 5580: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 5581: double agec; /* generic age */
5582: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5583: double *popeffectif,*popcount;
5584: double ***p3mat;
5585: double ***mobaverage;
5586: char fileresf[FILENAMELENGTH];
5587:
5588: agelim=AGESUP;
1.211 brouard 5589: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
5590: in each health status at the date of interview (if between dateprev1 and dateprev2).
5591: We still use firstpass and lastpass as another selection.
5592: */
1.126 brouard 5593: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5594:
1.201 brouard 5595: strcpy(fileresf,"F_");
5596: strcat(fileresf,fileresu);
1.126 brouard 5597: if((ficresf=fopen(fileresf,"w"))==NULL) {
5598: printf("Problem with forecast resultfile: %s\n", fileresf);
5599: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5600: }
5601: printf("Computing forecasting: result on file '%s' \n", fileresf);
5602: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5603:
5604: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5605:
5606: if (mobilav!=0) {
5607: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5608: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5609: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5610: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5611: }
5612: }
5613:
5614: stepsize=(int) (stepm+YEARM-1)/YEARM;
5615: if (stepm<=12) stepsize=1;
5616: if(estepm < stepm){
5617: printf ("Problem %d lower than %d\n",estepm, stepm);
5618: }
5619: else hstepm=estepm;
5620:
5621: hstepm=hstepm/stepm;
5622: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5623: fractional in yp1 */
5624: anprojmean=yp;
5625: yp2=modf((yp1*12),&yp);
5626: mprojmean=yp;
5627: yp1=modf((yp2*30.5),&yp);
5628: jprojmean=yp;
5629: if(jprojmean==0) jprojmean=1;
5630: if(mprojmean==0) jprojmean=1;
5631:
5632: i1=cptcoveff;
5633: if (cptcovn < 1){i1=1;}
5634:
5635: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5636:
5637: fprintf(ficresf,"#****** Routine prevforecast **\n");
5638:
5639: /* if (h==(int)(YEARM*yearp)){ */
5640: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5641: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5642: k=k+1;
1.211 brouard 5643: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126 brouard 5644: for(j=1;j<=cptcoveff;j++) {
1.211 brouard 5645: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5646: }
1.211 brouard 5647: fprintf(ficresf," yearproj age");
1.126 brouard 5648: for(j=1; j<=nlstate+ndeath;j++){
5649: for(i=1; i<=nlstate;i++)
5650: fprintf(ficresf," p%d%d",i,j);
5651: fprintf(ficresf," p.%d",j);
5652: }
5653: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5654: fprintf(ficresf,"\n");
5655: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5656:
5657: for (agec=fage; agec>=(ageminpar-1); agec--){
5658: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5659: nhstepm = nhstepm/hstepm;
5660: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5661: oldm=oldms;savm=savms;
5662: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5663:
5664: for (h=0; h<=nhstepm; h++){
5665: if (h*hstepm/YEARM*stepm ==yearp) {
5666: fprintf(ficresf,"\n");
5667: for(j=1;j<=cptcoveff;j++)
1.198 brouard 5668: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5669: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5670: }
5671: for(j=1; j<=nlstate+ndeath;j++) {
5672: ppij=0.;
5673: for(i=1; i<=nlstate;i++) {
5674: if (mobilav==1)
5675: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5676: else {
5677: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5678: }
5679: if (h*hstepm/YEARM*stepm== yearp) {
5680: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5681: }
5682: } /* end i */
5683: if (h*hstepm/YEARM*stepm==yearp) {
5684: fprintf(ficresf," %.3f", ppij);
5685: }
5686: }/* end j */
5687: } /* end h */
5688: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5689: } /* end agec */
5690: } /* end yearp */
5691: } /* end cptcod */
5692: } /* end cptcov */
5693:
5694: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5695:
5696: fclose(ficresf);
5697: }
5698:
5699: /************** Forecasting *****not tested NB*************/
1.169 brouard 5700: 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 5701:
5702: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5703: int *popage;
5704: double calagedatem, agelim, kk1, kk2;
5705: double *popeffectif,*popcount;
5706: double ***p3mat,***tabpop,***tabpopprev;
5707: double ***mobaverage;
5708: char filerespop[FILENAMELENGTH];
5709:
5710: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5711: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5712: agelim=AGESUP;
5713: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5714:
5715: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5716:
5717:
1.201 brouard 5718: strcpy(filerespop,"POP_");
5719: strcat(filerespop,fileresu);
1.126 brouard 5720: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5721: printf("Problem with forecast resultfile: %s\n", filerespop);
5722: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5723: }
5724: printf("Computing forecasting: result on file '%s' \n", filerespop);
5725: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5726:
5727: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5728:
5729: if (mobilav!=0) {
5730: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5731: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5732: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5733: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5734: }
5735: }
5736:
5737: stepsize=(int) (stepm+YEARM-1)/YEARM;
5738: if (stepm<=12) stepsize=1;
5739:
5740: agelim=AGESUP;
5741:
5742: hstepm=1;
5743: hstepm=hstepm/stepm;
5744:
5745: if (popforecast==1) {
5746: if((ficpop=fopen(popfile,"r"))==NULL) {
5747: printf("Problem with population file : %s\n",popfile);exit(0);
5748: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5749: }
5750: popage=ivector(0,AGESUP);
5751: popeffectif=vector(0,AGESUP);
5752: popcount=vector(0,AGESUP);
5753:
5754: i=1;
5755: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5756:
5757: imx=i;
5758: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5759: }
5760:
5761: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5762: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5763: k=k+1;
5764: fprintf(ficrespop,"\n#******");
5765: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5766: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5767: }
5768: fprintf(ficrespop,"******\n");
5769: fprintf(ficrespop,"# Age");
5770: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5771: if (popforecast==1) fprintf(ficrespop," [Population]");
5772:
5773: for (cpt=0; cpt<=0;cpt++) {
5774: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5775:
5776: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5777: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5778: nhstepm = nhstepm/hstepm;
5779:
5780: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5781: oldm=oldms;savm=savms;
5782: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5783:
5784: for (h=0; h<=nhstepm; h++){
5785: if (h==(int) (calagedatem+YEARM*cpt)) {
5786: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5787: }
5788: for(j=1; j<=nlstate+ndeath;j++) {
5789: kk1=0.;kk2=0;
5790: for(i=1; i<=nlstate;i++) {
5791: if (mobilav==1)
5792: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5793: else {
5794: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5795: }
5796: }
5797: if (h==(int)(calagedatem+12*cpt)){
5798: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5799: /*fprintf(ficrespop," %.3f", kk1);
5800: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5801: }
5802: }
5803: for(i=1; i<=nlstate;i++){
5804: kk1=0.;
5805: for(j=1; j<=nlstate;j++){
5806: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5807: }
5808: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5809: }
5810:
5811: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5812: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5813: }
5814: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5815: }
5816: }
5817:
5818: /******/
5819:
5820: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5821: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5822: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5823: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5824: nhstepm = nhstepm/hstepm;
5825:
5826: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5827: oldm=oldms;savm=savms;
5828: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5829: for (h=0; h<=nhstepm; h++){
5830: if (h==(int) (calagedatem+YEARM*cpt)) {
5831: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5832: }
5833: for(j=1; j<=nlstate+ndeath;j++) {
5834: kk1=0.;kk2=0;
5835: for(i=1; i<=nlstate;i++) {
5836: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5837: }
5838: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5839: }
5840: }
5841: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5842: }
5843: }
5844: }
5845: }
5846:
5847: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5848:
5849: if (popforecast==1) {
5850: free_ivector(popage,0,AGESUP);
5851: free_vector(popeffectif,0,AGESUP);
5852: free_vector(popcount,0,AGESUP);
5853: }
5854: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5855: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5856: fclose(ficrespop);
5857: } /* End of popforecast */
5858:
5859: int fileappend(FILE *fichier, char *optionfich)
5860: {
5861: if((fichier=fopen(optionfich,"a"))==NULL) {
5862: printf("Problem with file: %s\n", optionfich);
5863: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5864: return (0);
5865: }
5866: fflush(fichier);
5867: return (1);
5868: }
5869:
5870:
5871: /**************** function prwizard **********************/
5872: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5873: {
5874:
5875: /* Wizard to print covariance matrix template */
5876:
1.164 brouard 5877: char ca[32], cb[32];
5878: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5879: int numlinepar;
5880:
5881: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5882: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5883: for(i=1; i <=nlstate; i++){
5884: jj=0;
5885: for(j=1; j <=nlstate+ndeath; j++){
5886: if(j==i) continue;
5887: jj++;
5888: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5889: printf("%1d%1d",i,j);
5890: fprintf(ficparo,"%1d%1d",i,j);
5891: for(k=1; k<=ncovmodel;k++){
5892: /* printf(" %lf",param[i][j][k]); */
5893: /* fprintf(ficparo," %lf",param[i][j][k]); */
5894: printf(" 0.");
5895: fprintf(ficparo," 0.");
5896: }
5897: printf("\n");
5898: fprintf(ficparo,"\n");
5899: }
5900: }
5901: printf("# Scales (for hessian or gradient estimation)\n");
5902: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5903: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5904: for(i=1; i <=nlstate; i++){
5905: jj=0;
5906: for(j=1; j <=nlstate+ndeath; j++){
5907: if(j==i) continue;
5908: jj++;
5909: fprintf(ficparo,"%1d%1d",i,j);
5910: printf("%1d%1d",i,j);
5911: fflush(stdout);
5912: for(k=1; k<=ncovmodel;k++){
5913: /* printf(" %le",delti3[i][j][k]); */
5914: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5915: printf(" 0.");
5916: fprintf(ficparo," 0.");
5917: }
5918: numlinepar++;
5919: printf("\n");
5920: fprintf(ficparo,"\n");
5921: }
5922: }
5923: printf("# Covariance matrix\n");
5924: /* # 121 Var(a12)\n\ */
5925: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5926: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5927: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5928: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5929: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5930: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5931: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5932: fflush(stdout);
5933: fprintf(ficparo,"# Covariance matrix\n");
5934: /* # 121 Var(a12)\n\ */
5935: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5936: /* # ...\n\ */
5937: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5938:
5939: for(itimes=1;itimes<=2;itimes++){
5940: jj=0;
5941: for(i=1; i <=nlstate; i++){
5942: for(j=1; j <=nlstate+ndeath; j++){
5943: if(j==i) continue;
5944: for(k=1; k<=ncovmodel;k++){
5945: jj++;
5946: ca[0]= k+'a'-1;ca[1]='\0';
5947: if(itimes==1){
5948: printf("#%1d%1d%d",i,j,k);
5949: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5950: }else{
5951: printf("%1d%1d%d",i,j,k);
5952: fprintf(ficparo,"%1d%1d%d",i,j,k);
5953: /* printf(" %.5le",matcov[i][j]); */
5954: }
5955: ll=0;
5956: for(li=1;li <=nlstate; li++){
5957: for(lj=1;lj <=nlstate+ndeath; lj++){
5958: if(lj==li) continue;
5959: for(lk=1;lk<=ncovmodel;lk++){
5960: ll++;
5961: if(ll<=jj){
5962: cb[0]= lk +'a'-1;cb[1]='\0';
5963: if(ll<jj){
5964: if(itimes==1){
5965: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5966: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5967: }else{
5968: printf(" 0.");
5969: fprintf(ficparo," 0.");
5970: }
5971: }else{
5972: if(itimes==1){
5973: printf(" Var(%s%1d%1d)",ca,i,j);
5974: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5975: }else{
5976: printf(" 0.");
5977: fprintf(ficparo," 0.");
5978: }
5979: }
5980: }
5981: } /* end lk */
5982: } /* end lj */
5983: } /* end li */
5984: printf("\n");
5985: fprintf(ficparo,"\n");
5986: numlinepar++;
5987: } /* end k*/
5988: } /*end j */
5989: } /* end i */
5990: } /* end itimes */
5991:
5992: } /* end of prwizard */
5993: /******************* Gompertz Likelihood ******************************/
5994: double gompertz(double x[])
5995: {
5996: double A,B,L=0.0,sump=0.,num=0.;
5997: int i,n=0; /* n is the size of the sample */
5998:
5999: for (i=0;i<=imx-1 ; i++) {
6000: sump=sump+weight[i];
6001: /* sump=sump+1;*/
6002: num=num+1;
6003: }
6004:
6005:
6006: /* for (i=0; i<=imx; i++)
6007: 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]);*/
6008:
6009: for (i=1;i<=imx ; i++)
6010: {
6011: if (cens[i] == 1 && wav[i]>1)
6012: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
6013:
6014: if (cens[i] == 0 && wav[i]>1)
6015: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
6016: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
6017:
6018: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6019: if (wav[i] > 1 ) { /* ??? */
6020: L=L+A*weight[i];
6021: /* 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]);*/
6022: }
6023: }
6024:
6025: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6026:
6027: return -2*L*num/sump;
6028: }
6029:
1.136 brouard 6030: #ifdef GSL
6031: /******************* Gompertz_f Likelihood ******************************/
6032: double gompertz_f(const gsl_vector *v, void *params)
6033: {
6034: double A,B,LL=0.0,sump=0.,num=0.;
6035: double *x= (double *) v->data;
6036: int i,n=0; /* n is the size of the sample */
6037:
6038: for (i=0;i<=imx-1 ; i++) {
6039: sump=sump+weight[i];
6040: /* sump=sump+1;*/
6041: num=num+1;
6042: }
6043:
6044:
6045: /* for (i=0; i<=imx; i++)
6046: 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]);*/
6047: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
6048: for (i=1;i<=imx ; i++)
6049: {
6050: if (cens[i] == 1 && wav[i]>1)
6051: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
6052:
6053: if (cens[i] == 0 && wav[i]>1)
6054: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6055: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6056:
6057: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6058: if (wav[i] > 1 ) { /* ??? */
6059: LL=LL+A*weight[i];
6060: /* 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]);*/
6061: }
6062: }
6063:
6064: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6065: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6066:
6067: return -2*LL*num/sump;
6068: }
6069: #endif
6070:
1.126 brouard 6071: /******************* Printing html file ***********/
1.201 brouard 6072: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 6073: int lastpass, int stepm, int weightopt, char model[],\
6074: int imx, double p[],double **matcov,double agemortsup){
6075: int i,k;
6076:
6077: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
6078: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
6079: for (i=1;i<=2;i++)
6080: 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 6081: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126 brouard 6082: fprintf(fichtm,"</ul>");
6083:
6084: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
6085:
6086: 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>");
6087:
6088: for (k=agegomp;k<(agemortsup-2);k++)
6089: 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]);
6090:
6091:
6092: fflush(fichtm);
6093: }
6094:
6095: /******************* Gnuplot file **************/
1.201 brouard 6096: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126 brouard 6097:
6098: char dirfileres[132],optfileres[132];
1.164 brouard 6099:
1.126 brouard 6100: int ng;
6101:
6102:
6103: /*#ifdef windows */
6104: fprintf(ficgp,"cd \"%s\" \n",pathc);
6105: /*#endif */
6106:
6107:
6108: strcpy(dirfileres,optionfilefiname);
6109: strcpy(optfileres,"vpl");
1.199 brouard 6110: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
1.126 brouard 6111: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.199 brouard 6112: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
1.145 brouard 6113: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 6114: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
6115:
6116: }
6117:
1.136 brouard 6118: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
6119: {
1.126 brouard 6120:
1.136 brouard 6121: /*-------- data file ----------*/
6122: FILE *fic;
6123: char dummy[]=" ";
1.164 brouard 6124: int i=0, j=0, n=0;
1.136 brouard 6125: int linei, month, year,iout;
6126: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 6127: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 6128: char *stratrunc;
6129: int lstra;
1.126 brouard 6130:
6131:
1.136 brouard 6132: if((fic=fopen(datafile,"r"))==NULL) {
1.195 brouard 6133: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
6134: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136 brouard 6135: }
1.126 brouard 6136:
1.136 brouard 6137: i=1;
6138: linei=0;
6139: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
6140: linei=linei+1;
6141: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
6142: if(line[j] == '\t')
6143: line[j] = ' ';
6144: }
6145: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
6146: ;
6147: };
6148: line[j+1]=0; /* Trims blanks at end of line */
6149: if(line[0]=='#'){
6150: fprintf(ficlog,"Comment line\n%s\n",line);
6151: printf("Comment line\n%s\n",line);
6152: continue;
6153: }
6154: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 6155: strcpy(line, linetmp);
1.136 brouard 6156:
1.126 brouard 6157:
1.136 brouard 6158: for (j=maxwav;j>=1;j--){
1.137 brouard 6159: cutv(stra, strb, line, ' ');
1.136 brouard 6160: if(strb[0]=='.') { /* Missing status */
6161: lval=-1;
6162: }else{
6163: errno=0;
6164: lval=strtol(strb,&endptr,10);
6165: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
6166: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6167: 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);
6168: 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 6169: return 1;
6170: }
6171: }
6172: s[j][i]=lval;
6173:
6174: strcpy(line,stra);
6175: cutv(stra, strb,line,' ');
1.169 brouard 6176: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6177: }
1.169 brouard 6178: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 6179: month=99;
6180: year=9999;
6181: }else{
1.141 brouard 6182: 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);
6183: 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 6184: return 1;
6185: }
6186: anint[j][i]= (double) year;
6187: mint[j][i]= (double)month;
6188: strcpy(line,stra);
6189: } /* ENd Waves */
6190:
6191: cutv(stra, strb,line,' ');
1.169 brouard 6192: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6193: }
1.169 brouard 6194: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 6195: month=99;
6196: year=9999;
6197: }else{
1.141 brouard 6198: 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);
6199: 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 6200: return 1;
6201: }
6202: andc[i]=(double) year;
6203: moisdc[i]=(double) month;
6204: strcpy(line,stra);
6205:
6206: cutv(stra, strb,line,' ');
1.169 brouard 6207: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6208: }
1.169 brouard 6209: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 6210: month=99;
6211: year=9999;
6212: }else{
1.141 brouard 6213: 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);
6214: 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 6215: return 1;
6216: }
6217: if (year==9999) {
1.141 brouard 6218: 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);
6219: 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 6220: return 1;
1.126 brouard 6221:
1.136 brouard 6222: }
6223: annais[i]=(double)(year);
6224: moisnais[i]=(double)(month);
6225: strcpy(line,stra);
6226:
6227: cutv(stra, strb,line,' ');
6228: errno=0;
6229: dval=strtod(strb,&endptr);
6230: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6231: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6232: 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 6233: fflush(ficlog);
6234: return 1;
6235: }
6236: weight[i]=dval;
6237: strcpy(line,stra);
6238:
6239: for (j=ncovcol;j>=1;j--){
6240: cutv(stra, strb,line,' ');
6241: if(strb[0]=='.') { /* Missing status */
6242: lval=-1;
6243: }else{
6244: errno=0;
6245: lval=strtol(strb,&endptr,10);
6246: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6247: 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);
6248: 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 6249: return 1;
6250: }
6251: }
6252: if(lval <-1 || lval >1){
1.141 brouard 6253: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 6254: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6255: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6256: For example, for multinomial values like 1, 2 and 3,\n \
6257: build V1=0 V2=0 for the reference value (1),\n \
6258: V1=1 V2=0 for (2) \n \
6259: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6260: output of IMaCh is often meaningless.\n \
6261: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 6262: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 6263: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6264: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6265: For example, for multinomial values like 1, 2 and 3,\n \
6266: build V1=0 V2=0 for the reference value (1),\n \
6267: V1=1 V2=0 for (2) \n \
6268: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6269: output of IMaCh is often meaningless.\n \
6270: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6271: return 1;
6272: }
6273: covar[j][i]=(double)(lval);
6274: strcpy(line,stra);
6275: }
6276: lstra=strlen(stra);
6277:
6278: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6279: stratrunc = &(stra[lstra-9]);
6280: num[i]=atol(stratrunc);
6281: }
6282: else
6283: num[i]=atol(stra);
6284: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6285: 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;}*/
6286:
6287: i=i+1;
6288: } /* End loop reading data */
1.126 brouard 6289:
1.136 brouard 6290: *imax=i-1; /* Number of individuals */
6291: fclose(fic);
6292:
6293: return (0);
1.164 brouard 6294: /* endread: */
1.136 brouard 6295: printf("Exiting readdata: ");
6296: fclose(fic);
6297: return (1);
1.126 brouard 6298:
6299:
6300:
1.136 brouard 6301: }
1.145 brouard 6302: void removespace(char *str) {
6303: char *p1 = str, *p2 = str;
6304: do
6305: while (*p2 == ' ')
6306: p2++;
1.169 brouard 6307: while (*p1++ == *p2++);
1.145 brouard 6308: }
6309:
6310: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 6311: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6312: * - nagesqr = 1 if age*age in the model, otherwise 0.
6313: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6314: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 6315: * - cptcovage number of covariates with age*products =2
6316: * - cptcovs number of simple covariates
6317: * - 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
6318: * which is a new column after the 9 (ncovcol) variables.
6319: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6320: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6321: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6322: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6323: */
1.136 brouard 6324: {
1.145 brouard 6325: int i, j, k, ks;
1.164 brouard 6326: int j1, k1, k2;
1.136 brouard 6327: char modelsav[80];
1.145 brouard 6328: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 6329: char *strpt;
1.136 brouard 6330:
1.145 brouard 6331: /*removespace(model);*/
1.136 brouard 6332: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 6333: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 6334: if (strstr(model,"AGE") !=0){
1.192 brouard 6335: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6336: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 6337: return 1;
6338: }
1.141 brouard 6339: if (strstr(model,"v") !=0){
6340: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6341: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6342: return 1;
6343: }
1.187 brouard 6344: strcpy(modelsav,model);
6345: if ((strpt=strstr(model,"age*age")) !=0){
6346: printf(" strpt=%s, model=%s\n",strpt, model);
6347: if(strpt != model){
6348: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6349: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6350: corresponding column of parameters.\n",model);
6351: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6352: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6353: corresponding column of parameters.\n",model); fflush(ficlog);
6354: return 1;
6355: }
6356:
6357: nagesqr=1;
6358: if (strstr(model,"+age*age") !=0)
6359: substrchaine(modelsav, model, "+age*age");
6360: else if (strstr(model,"age*age+") !=0)
6361: substrchaine(modelsav, model, "age*age+");
6362: else
6363: substrchaine(modelsav, model, "age*age");
6364: }else
6365: nagesqr=0;
6366: if (strlen(modelsav) >1){
6367: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6368: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6369: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6370: cptcovt= j+1; /* Number of total covariates in the model, not including
6371: * cst, age and age*age
6372: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6373: /* including age products which are counted in cptcovage.
6374: * but the covariates which are products must be treated
6375: * separately: ncovn=4- 2=2 (V1+V3). */
6376: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6377: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6378:
6379:
6380: /* Design
6381: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6382: * < ncovcol=8 >
6383: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6384: * k= 1 2 3 4 5 6 7 8
6385: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6386: * covar[k,i], value of kth covariate if not including age for individual i:
6387: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6388: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6389: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6390: * Tage[++cptcovage]=k
6391: * if products, new covar are created after ncovcol with k1
6392: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6393: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6394: * 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
6395: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6396: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6397: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6398: * < ncovcol=8 >
6399: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6400: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6401: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6402: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6403: * p Tprod[1]@2={ 6, 5}
6404: *p Tvard[1][1]@4= {7, 8, 5, 6}
6405: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6406: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6407: *How to reorganize?
6408: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6409: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6410: * {2, 1, 4, 8, 5, 6, 3, 7}
6411: * Struct []
6412: */
1.145 brouard 6413:
1.187 brouard 6414: /* This loop fills the array Tvar from the string 'model'.*/
6415: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6416: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6417: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6418: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6419: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6420: /* k=1 Tvar[1]=2 (from V2) */
6421: /* k=5 Tvar[5] */
6422: /* for (k=1; k<=cptcovn;k++) { */
1.198 brouard 6423: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187 brouard 6424: /* } */
1.198 brouard 6425: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187 brouard 6426: /*
6427: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6428: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 6429: Tvar[k]=0;
1.187 brouard 6430: cptcovage=0;
6431: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6432: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6433: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6434: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6435: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6436: /*scanf("%d",i);*/
6437: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6438: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6439: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6440: /* covar is not filled and then is empty */
6441: cptcovprod--;
6442: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6443: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6444: cptcovage++; /* Sums the number of covariates which include age as a product */
6445: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6446: /*printf("stre=%s ", stre);*/
6447: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6448: cptcovprod--;
6449: cutl(stre,strb,strc,'V');
6450: Tvar[k]=atoi(stre);
6451: cptcovage++;
6452: Tage[cptcovage]=k;
6453: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6454: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6455: cptcovn++;
6456: cptcovprodnoage++;k1++;
6457: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6458: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6459: because this model-covariate is a construction we invent a new column
6460: ncovcol + k1
6461: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6462: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6463: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6464: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6465: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6466: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6467: k2=k2+2;
6468: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6469: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6470: for (i=1; i<=lastobs;i++){
6471: /* Computes the new covariate which is a product of
6472: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6473: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6474: }
6475: } /* End age is not in the model */
6476: } /* End if model includes a product */
6477: else { /* no more sum */
6478: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6479: /* scanf("%d",i);*/
6480: cutl(strd,strc,strb,'V');
6481: ks++; /**< Number of simple covariates */
1.145 brouard 6482: cptcovn++;
1.187 brouard 6483: Tvar[k]=atoi(strd);
6484: }
6485: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6486: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6487: scanf("%d",i);*/
6488: } /* end of loop + on total covariates */
6489: } /* end if strlen(modelsave == 0) age*age might exist */
6490: } /* end if strlen(model == 0) */
1.136 brouard 6491:
6492: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6493: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6494:
6495: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6496: printf("cptcovprod=%d ", cptcovprod);
6497: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6498:
6499: scanf("%d ",i);*/
6500:
6501:
1.137 brouard 6502: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 6503: /*endread:*/
1.136 brouard 6504: printf("Exiting decodemodel: ");
6505: return (1);
6506: }
6507:
1.169 brouard 6508: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 6509: {
6510: int i, m;
6511:
6512: for (i=1; i<=imx; i++) {
6513: for(m=2; (m<= maxwav); m++) {
6514: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6515: anint[m][i]=9999;
6516: s[m][i]=-1;
6517: }
6518: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 6519: *nberr = *nberr + 1;
6520: 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);
6521: 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 6522: s[m][i]=-1;
6523: }
6524: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 6525: (*nberr)++;
1.136 brouard 6526: 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]);
6527: 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]);
6528: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6529: }
6530: }
6531: }
6532:
6533: for (i=1; i<=imx; i++) {
6534: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6535: for(m=firstpass; (m<= lastpass); m++){
6536: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6537: if (s[m][i] >= nlstate+1) {
1.169 brouard 6538: if(agedc[i]>0){
6539: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 6540: agev[m][i]=agedc[i];
6541: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 6542: }else {
1.136 brouard 6543: if ((int)andc[i]!=9999){
6544: nbwarn++;
6545: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6546: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6547: agev[m][i]=-1;
6548: }
6549: }
1.169 brouard 6550: } /* agedc > 0 */
1.136 brouard 6551: }
6552: else if(s[m][i] !=9){ /* Standard case, age in fractional
6553: years but with the precision of a month */
6554: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6555: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6556: agev[m][i]=1;
6557: else if(agev[m][i] < *agemin){
6558: *agemin=agev[m][i];
6559: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6560: }
6561: else if(agev[m][i] >*agemax){
6562: *agemax=agev[m][i];
1.156 brouard 6563: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 6564: }
6565: /*agev[m][i]=anint[m][i]-annais[i];*/
6566: /* agev[m][i] = age[i]+2*m;*/
6567: }
6568: else { /* =9 */
6569: agev[m][i]=1;
6570: s[m][i]=-1;
6571: }
6572: }
6573: else /*= 0 Unknown */
6574: agev[m][i]=1;
6575: }
6576:
6577: }
6578: for (i=1; i<=imx; i++) {
6579: for(m=firstpass; (m<=lastpass); m++){
6580: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 6581: (*nberr)++;
1.136 brouard 6582: 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);
6583: 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);
6584: return 1;
6585: }
6586: }
6587: }
6588:
6589: /*for (i=1; i<=imx; i++){
6590: for (m=firstpass; (m<lastpass); m++){
6591: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6592: }
6593:
6594: }*/
6595:
6596:
1.139 brouard 6597: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6598: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 6599:
6600: return (0);
1.164 brouard 6601: /* endread:*/
1.136 brouard 6602: printf("Exiting calandcheckages: ");
6603: return (1);
6604: }
6605:
1.172 brouard 6606: #if defined(_MSC_VER)
6607: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6608: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6609: //#include "stdafx.h"
6610: //#include <stdio.h>
6611: //#include <tchar.h>
6612: //#include <windows.h>
6613: //#include <iostream>
6614: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6615:
6616: LPFN_ISWOW64PROCESS fnIsWow64Process;
6617:
6618: BOOL IsWow64()
6619: {
6620: BOOL bIsWow64 = FALSE;
6621:
6622: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6623: // (HANDLE, PBOOL);
6624:
6625: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6626:
6627: HMODULE module = GetModuleHandle(_T("kernel32"));
6628: const char funcName[] = "IsWow64Process";
6629: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6630: GetProcAddress(module, funcName);
6631:
6632: if (NULL != fnIsWow64Process)
6633: {
6634: if (!fnIsWow64Process(GetCurrentProcess(),
6635: &bIsWow64))
6636: //throw std::exception("Unknown error");
6637: printf("Unknown error\n");
6638: }
6639: return bIsWow64 != FALSE;
6640: }
6641: #endif
1.177 brouard 6642:
1.191 brouard 6643: void syscompilerinfo(int logged)
1.167 brouard 6644: {
6645: /* #include "syscompilerinfo.h"*/
1.185 brouard 6646: /* command line Intel compiler 32bit windows, XP compatible:*/
6647: /* /GS /W3 /Gy
6648: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6649: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6650: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 6651: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6652: */
6653: /* 64 bits */
1.185 brouard 6654: /*
6655: /GS /W3 /Gy
6656: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6657: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6658: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6659: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6660: /* Optimization are useless and O3 is slower than O2 */
6661: /*
6662: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6663: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6664: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6665: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6666: */
1.186 brouard 6667: /* Link is */ /* /OUT:"visual studio
1.185 brouard 6668: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6669: /PDB:"visual studio
6670: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6671: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6672: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6673: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6674: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6675: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6676: uiAccess='false'"
6677: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6678: /NOLOGO /TLBID:1
6679: */
1.177 brouard 6680: #if defined __INTEL_COMPILER
1.178 brouard 6681: #if defined(__GNUC__)
6682: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6683: #endif
1.177 brouard 6684: #elif defined(__GNUC__)
1.179 brouard 6685: #ifndef __APPLE__
1.174 brouard 6686: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 6687: #endif
1.177 brouard 6688: struct utsname sysInfo;
1.178 brouard 6689: int cross = CROSS;
6690: if (cross){
6691: printf("Cross-");
1.191 brouard 6692: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6693: }
1.174 brouard 6694: #endif
6695:
1.171 brouard 6696: #include <stdint.h>
1.178 brouard 6697:
1.191 brouard 6698: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6699: #if defined(__clang__)
1.191 brouard 6700: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6701: #endif
6702: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6703: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6704: #endif
6705: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6706: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6707: #endif
6708: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6709: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6710: #endif
6711: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6712: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6713: #endif
6714: #if defined(_MSC_VER)
1.191 brouard 6715: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6716: #endif
6717: #if defined(__PGI)
1.191 brouard 6718: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6719: #endif
6720: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6721: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6722: #endif
1.191 brouard 6723: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6724:
1.167 brouard 6725: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6726: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6727: // Windows (x64 and x86)
1.191 brouard 6728: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6729: #elif __unix__ // all unices, not all compilers
6730: // Unix
1.191 brouard 6731: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6732: #elif __linux__
6733: // linux
1.191 brouard 6734: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6735: #elif __APPLE__
1.174 brouard 6736: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6737: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6738: #endif
6739:
6740: /* __MINGW32__ */
6741: /* __CYGWIN__ */
6742: /* __MINGW64__ */
6743: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6744: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6745: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6746: /* _WIN64 // Defined for applications for Win64. */
6747: /* _M_X64 // Defined for compilations that target x64 processors. */
6748: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6749:
1.167 brouard 6750: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6751: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6752: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6753: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6754: #else
1.191 brouard 6755: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6756: #endif
6757:
1.169 brouard 6758: #if defined(__GNUC__)
6759: # if defined(__GNUC_PATCHLEVEL__)
6760: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6761: + __GNUC_MINOR__ * 100 \
6762: + __GNUC_PATCHLEVEL__)
6763: # else
6764: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6765: + __GNUC_MINOR__ * 100)
6766: # endif
1.174 brouard 6767: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6768: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6769:
6770: if (uname(&sysInfo) != -1) {
6771: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6772: 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 6773: }
6774: else
6775: perror("uname() error");
1.179 brouard 6776: //#ifndef __INTEL_COMPILER
6777: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6778: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6779: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6780: #endif
1.169 brouard 6781: #endif
1.172 brouard 6782:
6783: // void main()
6784: // {
1.169 brouard 6785: #if defined(_MSC_VER)
1.174 brouard 6786: if (IsWow64()){
1.191 brouard 6787: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6788: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6789: }
6790: else{
1.191 brouard 6791: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6792: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6793: }
1.172 brouard 6794: // printf("\nPress Enter to continue...");
6795: // getchar();
6796: // }
6797:
1.169 brouard 6798: #endif
6799:
1.167 brouard 6800:
6801: }
1.136 brouard 6802:
1.209 brouard 6803: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180 brouard 6804: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6805: int i, j, k, i1 ;
1.202 brouard 6806: /* double ftolpl = 1.e-10; */
1.180 brouard 6807: double age, agebase, agelim;
1.203 brouard 6808: double tot;
1.180 brouard 6809:
1.202 brouard 6810: strcpy(filerespl,"PL_");
6811: strcat(filerespl,fileresu);
6812: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6813: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6814: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6815: }
6816: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6817: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6818: pstamp(ficrespl);
1.203 brouard 6819: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202 brouard 6820: fprintf(ficrespl,"#Age ");
6821: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6822: fprintf(ficrespl,"\n");
1.180 brouard 6823:
6824: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6825:
6826: agebase=ageminpar;
6827: agelim=agemaxpar;
6828:
6829: i1=pow(2,cptcoveff);
6830: if (cptcovn < 1){i1=1;}
6831:
6832: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6833: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6834: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6835: k=k+1;
6836: /* to clean */
1.198 brouard 6837: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200 brouard 6838: fprintf(ficrespl,"#******");
6839: printf("#******");
6840: fprintf(ficlog,"#******");
1.180 brouard 6841: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 6842: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6843: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6844: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6845: }
6846: fprintf(ficrespl,"******\n");
6847: printf("******\n");
6848: fprintf(ficlog,"******\n");
6849:
6850: fprintf(ficrespl,"#Age ");
6851: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 6852: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6853: }
1.203 brouard 6854: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6855: fprintf(ficrespl,"Total Years_to_converge\n");
1.180 brouard 6856:
6857: for (age=agebase; age<=agelim; age++){
6858: /* for (age=agebase; age<=agebase; age++){ */
1.209 brouard 6859: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180 brouard 6860: fprintf(ficrespl,"%.0f ",age );
6861: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6862: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203 brouard 6863: tot=0.;
6864: for(i=1; i<=nlstate;i++){
6865: tot += prlim[i][i];
1.180 brouard 6866: fprintf(ficrespl," %.5f", prlim[i][i]);
1.203 brouard 6867: }
1.209 brouard 6868: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180 brouard 6869: } /* Age */
6870: /* was end of cptcod */
6871: } /* cptcov */
1.184 brouard 6872: return 0;
1.180 brouard 6873: }
6874:
6875: int hPijx(double *p, int bage, int fage){
6876: /*------------- h Pij x at various ages ------------*/
6877:
6878: int stepsize;
6879: int agelim;
6880: int hstepm;
6881: int nhstepm;
6882: int h, i, i1, j, k;
6883:
6884: double agedeb;
6885: double ***p3mat;
6886:
1.201 brouard 6887: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
1.180 brouard 6888: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6889: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6890: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6891: }
6892: printf("Computing pij: result on file '%s' \n", filerespij);
6893: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6894:
6895: stepsize=(int) (stepm+YEARM-1)/YEARM;
6896: /*if (stepm<=24) stepsize=2;*/
6897:
6898: agelim=AGESUP;
6899: hstepm=stepsize*YEARM; /* Every year of age */
6900: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6901:
6902: /* hstepm=1; aff par mois*/
6903: pstamp(ficrespij);
6904: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6905: i1= pow(2,cptcoveff);
1.183 brouard 6906: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6907: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6908: /* k=k+1; */
6909: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6910: fprintf(ficrespij,"\n#****** ");
6911: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6912: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183 brouard 6913: fprintf(ficrespij,"******\n");
6914:
6915: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6916: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6917: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6918:
6919: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6920:
1.183 brouard 6921: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6922: oldm=oldms;savm=savms;
6923: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6924: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6925: for(i=1; i<=nlstate;i++)
6926: for(j=1; j<=nlstate+ndeath;j++)
6927: fprintf(ficrespij," %1d-%1d",i,j);
6928: fprintf(ficrespij,"\n");
6929: for (h=0; h<=nhstepm; h++){
6930: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6931: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6932: for(i=1; i<=nlstate;i++)
6933: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6934: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6935: fprintf(ficrespij,"\n");
6936: }
1.183 brouard 6937: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6938: fprintf(ficrespij,"\n");
6939: }
1.180 brouard 6940: /*}*/
6941: }
1.184 brouard 6942: return 0;
1.180 brouard 6943: }
6944:
6945:
1.136 brouard 6946: /***********************************************/
6947: /**************** Main Program *****************/
6948: /***********************************************/
6949:
6950: int main(int argc, char *argv[])
6951: {
6952: #ifdef GSL
6953: const gsl_multimin_fminimizer_type *T;
6954: size_t iteri = 0, it;
6955: int rval = GSL_CONTINUE;
6956: int status = GSL_SUCCESS;
6957: double ssval;
6958: #endif
6959: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6960: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209 brouard 6961: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164 brouard 6962: int jj, ll, li, lj, lk;
1.136 brouard 6963: int numlinepar=0; /* Current linenumber of parameter file */
1.197 brouard 6964: int num_filled;
1.136 brouard 6965: int itimes;
6966: int NDIM=2;
6967: int vpopbased=0;
6968:
1.164 brouard 6969: char ca[32], cb[32];
1.136 brouard 6970: /* FILE *fichtm; *//* Html File */
6971: /* FILE *ficgp;*/ /*Gnuplot File */
6972: struct stat info;
1.191 brouard 6973: double agedeb=0.;
1.194 brouard 6974:
6975: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6976:
1.165 brouard 6977: double fret;
1.191 brouard 6978: double dum=0.; /* Dummy variable */
1.136 brouard 6979: double ***p3mat;
6980: double ***mobaverage;
1.164 brouard 6981:
6982: char line[MAXLINE];
1.197 brouard 6983: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6984:
6985: char model[MAXLINE], modeltemp[MAXLINE];
1.136 brouard 6986: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6987: char *tok, *val; /* pathtot */
1.136 brouard 6988: int firstobs=1, lastobs=10;
1.195 brouard 6989: int c, h , cpt, c2;
1.191 brouard 6990: int jl=0;
6991: int i1, j1, jk, stepsize=0;
1.194 brouard 6992: int count=0;
6993:
1.164 brouard 6994: int *tab;
1.136 brouard 6995: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6996: int mobilav=0,popforecast=0;
1.191 brouard 6997: int hstepm=0, nhstepm=0;
1.136 brouard 6998: int agemortsup;
6999: float sumlpop=0.;
7000: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
7001: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
7002:
1.191 brouard 7003: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 7004: double ftolpl=FTOL;
7005: double **prlim;
7006: double ***param; /* Matrix of parameters */
7007: double *p;
7008: double **matcov; /* Matrix of covariance */
1.203 brouard 7009: double **hess; /* Hessian matrix */
1.136 brouard 7010: double ***delti3; /* Scale */
7011: double *delti; /* Scale */
7012: double ***eij, ***vareij;
7013: double **varpl; /* Variances of prevalence limits by age */
7014: double *epj, vepp;
1.164 brouard 7015:
1.136 brouard 7016: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
7017: double **ximort;
1.145 brouard 7018: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 7019: int *dcwave;
7020:
1.164 brouard 7021: char z[1]="c";
1.136 brouard 7022:
7023: /*char *strt;*/
7024: char strtend[80];
1.126 brouard 7025:
1.164 brouard 7026:
1.126 brouard 7027: /* setlocale (LC_ALL, ""); */
7028: /* bindtextdomain (PACKAGE, LOCALEDIR); */
7029: /* textdomain (PACKAGE); */
7030: /* setlocale (LC_CTYPE, ""); */
7031: /* setlocale (LC_MESSAGES, ""); */
7032:
7033: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 7034: rstart_time = time(NULL);
7035: /* (void) gettimeofday(&start_time,&tzp);*/
7036: start_time = *localtime(&rstart_time);
1.126 brouard 7037: curr_time=start_time;
1.157 brouard 7038: /*tml = *localtime(&start_time.tm_sec);*/
7039: /* strcpy(strstart,asctime(&tml)); */
7040: strcpy(strstart,asctime(&start_time));
1.126 brouard 7041:
7042: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 7043: /* tp.tm_sec = tp.tm_sec +86400; */
7044: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 7045: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
7046: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
7047: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 7048: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 7049: /* strt=asctime(&tmg); */
7050: /* printf("Time(after) =%s",strstart); */
7051: /* (void) time (&time_value);
7052: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
7053: * tm = *localtime(&time_value);
7054: * strstart=asctime(&tm);
7055: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
7056: */
7057:
7058: nberr=0; /* Number of errors and warnings */
7059: nbwarn=0;
1.184 brouard 7060: #ifdef WIN32
7061: _getcwd(pathcd, size);
7062: #else
1.126 brouard 7063: getcwd(pathcd, size);
1.184 brouard 7064: #endif
1.191 brouard 7065: syscompilerinfo(0);
1.196 brouard 7066: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126 brouard 7067: if(argc <=1){
7068: printf("\nEnter the parameter file name: ");
1.205 brouard 7069: if(!fgets(pathr,FILENAMELENGTH,stdin)){
7070: printf("ERROR Empty parameter file name\n");
7071: goto end;
7072: }
1.126 brouard 7073: i=strlen(pathr);
7074: if(pathr[i-1]=='\n')
7075: pathr[i-1]='\0';
1.156 brouard 7076: i=strlen(pathr);
1.205 brouard 7077: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156 brouard 7078: pathr[i-1]='\0';
1.205 brouard 7079: }
7080: i=strlen(pathr);
7081: if( i==0 ){
7082: printf("ERROR Empty parameter file name\n");
7083: goto end;
7084: }
7085: for (tok = pathr; tok != NULL; ){
1.126 brouard 7086: printf("Pathr |%s|\n",pathr);
7087: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
7088: printf("val= |%s| pathr=%s\n",val,pathr);
7089: strcpy (pathtot, val);
7090: if(pathr[0] == '\0') break; /* Dirty */
7091: }
7092: }
7093: else{
7094: strcpy(pathtot,argv[1]);
7095: }
7096: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
7097: /*cygwin_split_path(pathtot,path,optionfile);
7098: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
7099: /* cutv(path,optionfile,pathtot,'\\');*/
7100:
7101: /* Split argv[0], imach program to get pathimach */
7102: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
7103: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7104: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7105: /* strcpy(pathimach,argv[0]); */
7106: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
7107: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
7108: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 7109: #ifdef WIN32
7110: _chdir(path); /* Can be a relative path */
7111: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
7112: #else
1.126 brouard 7113: chdir(path); /* Can be a relative path */
1.184 brouard 7114: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
7115: #endif
7116: printf("Current directory %s!\n",pathcd);
1.126 brouard 7117: strcpy(command,"mkdir ");
7118: strcat(command,optionfilefiname);
7119: if((outcmd=system(command)) != 0){
1.169 brouard 7120: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 7121: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
7122: /* fclose(ficlog); */
7123: /* exit(1); */
7124: }
7125: /* if((imk=mkdir(optionfilefiname))<0){ */
7126: /* perror("mkdir"); */
7127: /* } */
7128:
7129: /*-------- arguments in the command line --------*/
7130:
1.186 brouard 7131: /* Main Log file */
1.126 brouard 7132: strcat(filelog, optionfilefiname);
7133: strcat(filelog,".log"); /* */
7134: if((ficlog=fopen(filelog,"w"))==NULL) {
7135: printf("Problem with logfile %s\n",filelog);
7136: goto end;
7137: }
7138: fprintf(ficlog,"Log filename:%s\n",filelog);
1.197 brouard 7139: fprintf(ficlog,"Version %s %s",version,fullversion);
1.126 brouard 7140: fprintf(ficlog,"\nEnter the parameter file name: \n");
7141: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
7142: path=%s \n\
7143: optionfile=%s\n\
7144: optionfilext=%s\n\
1.156 brouard 7145: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 7146:
1.197 brouard 7147: syscompilerinfo(1);
1.167 brouard 7148:
1.126 brouard 7149: printf("Local time (at start):%s",strstart);
7150: fprintf(ficlog,"Local time (at start): %s",strstart);
7151: fflush(ficlog);
7152: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 7153: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 7154:
7155: /* */
7156: strcpy(fileres,"r");
7157: strcat(fileres, optionfilefiname);
1.201 brouard 7158: strcat(fileresu, optionfilefiname); /* Without r in front */
1.126 brouard 7159: strcat(fileres,".txt"); /* Other files have txt extension */
1.201 brouard 7160: strcat(fileresu,".txt"); /* Other files have txt extension */
1.126 brouard 7161:
1.186 brouard 7162: /* Main ---------arguments file --------*/
1.126 brouard 7163:
7164: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 7165: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7166: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 7167: fflush(ficlog);
1.149 brouard 7168: /* goto end; */
7169: exit(70);
1.126 brouard 7170: }
7171:
7172:
7173:
7174: strcpy(filereso,"o");
1.201 brouard 7175: strcat(filereso,fileresu);
1.126 brouard 7176: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
7177: printf("Problem with Output resultfile: %s\n", filereso);
7178: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
7179: fflush(ficlog);
7180: goto end;
7181: }
7182:
7183: /* Reads comments: lines beginning with '#' */
7184: numlinepar=0;
1.197 brouard 7185:
7186: /* First parameter line */
7187: while(fgets(line, MAXLINE, ficpar)) {
7188: /* If line starts with a # it is a comment */
7189: if (line[0] == '#') {
7190: numlinepar++;
7191: fputs(line,stdout);
7192: fputs(line,ficparo);
7193: fputs(line,ficlog);
7194: continue;
7195: }else
7196: break;
7197: }
7198: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
7199: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
7200: if (num_filled != 5) {
7201: printf("Should be 5 parameters\n");
7202: }
1.126 brouard 7203: numlinepar++;
1.197 brouard 7204: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
7205: }
7206: /* Second parameter line */
7207: while(fgets(line, MAXLINE, ficpar)) {
7208: /* If line starts with a # it is a comment */
7209: if (line[0] == '#') {
7210: numlinepar++;
7211: fputs(line,stdout);
7212: fputs(line,ficparo);
7213: fputs(line,ficlog);
7214: continue;
7215: }else
7216: break;
7217: }
7218: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
7219: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7220: if (num_filled != 8) {
1.209 brouard 7221: printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
7222: printf("but line=%s\n",line);
1.197 brouard 7223: }
7224: 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 7225: }
1.203 brouard 7226: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209 brouard 7227: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197 brouard 7228: /* Third parameter line */
7229: while(fgets(line, MAXLINE, ficpar)) {
7230: /* If line starts with a # it is a comment */
7231: if (line[0] == '#') {
7232: numlinepar++;
7233: fputs(line,stdout);
7234: fputs(line,ficparo);
7235: fputs(line,ficlog);
7236: continue;
7237: }else
7238: break;
7239: }
1.201 brouard 7240: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7241: if (num_filled == 0)
7242: model[0]='\0';
7243: else if (num_filled != 1){
1.197 brouard 7244: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7245: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7246: model[0]='\0';
7247: goto end;
7248: }
7249: else{
7250: if (model[0]=='+'){
7251: for(i=1; i<=strlen(model);i++)
7252: modeltemp[i-1]=model[i];
1.201 brouard 7253: strcpy(model,modeltemp);
1.197 brouard 7254: }
7255: }
1.199 brouard 7256: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203 brouard 7257: printf("model=1+age+%s\n",model);fflush(stdout);
1.197 brouard 7258: }
7259: /* 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); */
7260: /* numlinepar=numlinepar+3; /\* In general *\/ */
7261: /* 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.203 brouard 7262: 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);
7263: 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 7264: fflush(ficlog);
1.190 brouard 7265: /* if(model[0]=='#'|| model[0]== '\0'){ */
7266: if(model[0]=='#'){
1.187 brouard 7267: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7268: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7269: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7270: if(mle != -1){
7271: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7272: exit(1);
7273: }
7274: }
1.126 brouard 7275: while((c=getc(ficpar))=='#' && c!= EOF){
7276: ungetc(c,ficpar);
7277: fgets(line, MAXLINE, ficpar);
7278: numlinepar++;
1.195 brouard 7279: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7280: z[0]=line[1];
7281: }
7282: /* printf("****line [1] = %c \n",line[1]); */
1.141 brouard 7283: fputs(line, stdout);
7284: //puts(line);
1.126 brouard 7285: fputs(line,ficparo);
7286: fputs(line,ficlog);
7287: }
7288: ungetc(c,ficpar);
7289:
7290:
1.145 brouard 7291: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 7292: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7293: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7294: v1+v2*age+v2*v3 makes cptcovn = 3
7295: */
7296: if (strlen(model)>1)
1.187 brouard 7297: 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 7298: else
1.187 brouard 7299: ncovmodel=2; /* Constant and age */
1.133 brouard 7300: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7301: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 7302: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7303: 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);
7304: 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);
7305: fflush(stdout);
7306: fclose (ficlog);
7307: goto end;
7308: }
1.126 brouard 7309: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7310: delti=delti3[1][1];
7311: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7312: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7313: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 7314: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7315: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7316: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7317: fclose (ficparo);
7318: fclose (ficlog);
7319: goto end;
7320: exit(0);
7321: }
1.186 brouard 7322: else if(mle==-3) { /* Main Wizard */
1.126 brouard 7323: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 7324: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7325: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7326: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7327: matcov=matrix(1,npar,1,npar);
1.203 brouard 7328: hess=matrix(1,npar,1,npar);
1.126 brouard 7329: }
7330: else{
1.145 brouard 7331: /* Read guessed parameters */
1.126 brouard 7332: /* Reads comments: lines beginning with '#' */
7333: while((c=getc(ficpar))=='#' && c!= EOF){
7334: ungetc(c,ficpar);
7335: fgets(line, MAXLINE, ficpar);
7336: numlinepar++;
1.141 brouard 7337: fputs(line,stdout);
1.126 brouard 7338: fputs(line,ficparo);
7339: fputs(line,ficlog);
7340: }
7341: ungetc(c,ficpar);
7342:
7343: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7344: for(i=1; i <=nlstate; i++){
7345: j=0;
7346: for(jj=1; jj <=nlstate+ndeath; jj++){
7347: if(jj==i) continue;
7348: j++;
7349: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 7350: if ((i1 != i) || (j1 != jj)){
1.126 brouard 7351: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7352: It might be a problem of design; if ncovcol and the model are correct\n \
7353: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7354: exit(1);
7355: }
7356: fprintf(ficparo,"%1d%1d",i1,j1);
7357: if(mle==1)
1.193 brouard 7358: printf("%1d%1d",i,jj);
7359: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 7360: for(k=1; k<=ncovmodel;k++){
7361: fscanf(ficpar," %lf",¶m[i][j][k]);
7362: if(mle==1){
7363: printf(" %lf",param[i][j][k]);
7364: fprintf(ficlog," %lf",param[i][j][k]);
7365: }
7366: else
7367: fprintf(ficlog," %lf",param[i][j][k]);
7368: fprintf(ficparo," %lf",param[i][j][k]);
7369: }
7370: fscanf(ficpar,"\n");
7371: numlinepar++;
7372: if(mle==1)
7373: printf("\n");
7374: fprintf(ficlog,"\n");
7375: fprintf(ficparo,"\n");
7376: }
7377: }
7378: fflush(ficlog);
7379:
1.145 brouard 7380: /* Reads scales values */
1.126 brouard 7381: p=param[1][1];
7382:
7383: /* Reads comments: lines beginning with '#' */
7384: while((c=getc(ficpar))=='#' && c!= EOF){
7385: ungetc(c,ficpar);
7386: fgets(line, MAXLINE, ficpar);
7387: numlinepar++;
1.141 brouard 7388: fputs(line,stdout);
1.126 brouard 7389: fputs(line,ficparo);
7390: fputs(line,ficlog);
7391: }
7392: ungetc(c,ficpar);
7393:
7394: for(i=1; i <=nlstate; i++){
7395: for(j=1; j <=nlstate+ndeath-1; j++){
7396: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 7397: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 7398: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7399: exit(1);
7400: }
7401: printf("%1d%1d",i,j);
7402: fprintf(ficparo,"%1d%1d",i1,j1);
7403: fprintf(ficlog,"%1d%1d",i1,j1);
7404: for(k=1; k<=ncovmodel;k++){
7405: fscanf(ficpar,"%le",&delti3[i][j][k]);
7406: printf(" %le",delti3[i][j][k]);
7407: fprintf(ficparo," %le",delti3[i][j][k]);
7408: fprintf(ficlog," %le",delti3[i][j][k]);
7409: }
7410: fscanf(ficpar,"\n");
7411: numlinepar++;
7412: printf("\n");
7413: fprintf(ficparo,"\n");
7414: fprintf(ficlog,"\n");
7415: }
7416: }
7417: fflush(ficlog);
7418:
1.145 brouard 7419: /* Reads covariance matrix */
1.126 brouard 7420: delti=delti3[1][1];
7421:
7422:
7423: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7424:
7425: /* Reads comments: lines beginning with '#' */
7426: while((c=getc(ficpar))=='#' && c!= EOF){
7427: ungetc(c,ficpar);
7428: fgets(line, MAXLINE, ficpar);
7429: numlinepar++;
1.141 brouard 7430: fputs(line,stdout);
1.126 brouard 7431: fputs(line,ficparo);
7432: fputs(line,ficlog);
7433: }
7434: ungetc(c,ficpar);
7435:
7436: matcov=matrix(1,npar,1,npar);
1.203 brouard 7437: hess=matrix(1,npar,1,npar);
1.131 brouard 7438: for(i=1; i <=npar; i++)
7439: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7440:
1.194 brouard 7441: /* Scans npar lines */
1.126 brouard 7442: for(i=1; i <=npar; i++){
1.194 brouard 7443: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7444: if(count != 3){
7445: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7446: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7447: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7448: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7449: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7450: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7451: exit(1);
7452: }else
1.126 brouard 7453: if(mle==1)
1.194 brouard 7454: printf("%1d%1d%1d",i1,j1,jk);
7455: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7456: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 7457: for(j=1; j <=i; j++){
7458: fscanf(ficpar," %le",&matcov[i][j]);
7459: if(mle==1){
7460: printf(" %.5le",matcov[i][j]);
7461: }
7462: fprintf(ficlog," %.5le",matcov[i][j]);
7463: fprintf(ficparo," %.5le",matcov[i][j]);
7464: }
7465: fscanf(ficpar,"\n");
7466: numlinepar++;
7467: if(mle==1)
7468: printf("\n");
7469: fprintf(ficlog,"\n");
7470: fprintf(ficparo,"\n");
7471: }
1.194 brouard 7472: /* End of read covariance matrix npar lines */
1.126 brouard 7473: for(i=1; i <=npar; i++)
7474: for(j=i+1;j<=npar;j++)
7475: matcov[i][j]=matcov[j][i];
7476:
7477: if(mle==1)
7478: printf("\n");
7479: fprintf(ficlog,"\n");
7480:
7481: fflush(ficlog);
7482:
7483: /*-------- Rewriting parameter file ----------*/
7484: strcpy(rfileres,"r"); /* "Rparameterfile */
7485: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7486: strcat(rfileres,"."); /* */
7487: strcat(rfileres,optionfilext); /* Other files have txt extension */
7488: if((ficres =fopen(rfileres,"w"))==NULL) {
1.201 brouard 7489: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7490: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126 brouard 7491: }
7492: fprintf(ficres,"#%s\n",version);
7493: } /* End of mle != -3 */
7494:
1.186 brouard 7495: /* Main data
7496: */
1.126 brouard 7497: n= lastobs;
7498: num=lvector(1,n);
7499: moisnais=vector(1,n);
7500: annais=vector(1,n);
7501: moisdc=vector(1,n);
7502: andc=vector(1,n);
7503: agedc=vector(1,n);
7504: cod=ivector(1,n);
7505: weight=vector(1,n);
7506: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7507: mint=matrix(1,maxwav,1,n);
7508: anint=matrix(1,maxwav,1,n);
1.131 brouard 7509: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 7510: tab=ivector(1,NCOVMAX);
1.144 brouard 7511: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 7512: 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 7513:
1.136 brouard 7514: /* Reads data from file datafile */
7515: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7516: goto end;
7517:
7518: /* Calculation of the number of parameters from char model */
1.137 brouard 7519: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7520: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7521: k=3 V4 Tvar[k=3]= 4 (from V4)
7522: k=2 V1 Tvar[k=2]= 1 (from V1)
7523: k=1 Tvar[1]=2 (from V2)
7524: */
7525: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7526: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7527: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7528: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7529: */
7530: /* For model-covariate k tells which data-covariate to use but
7531: because this model-covariate is a construction we invent a new column
7532: ncovcol + k1
7533: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7534: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 7535: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 7536: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7537: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7538: */
1.145 brouard 7539: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7540: 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 7541: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7542: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 7543: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 7544: 4 covariates (3 plus signs)
7545: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7546: */
1.136 brouard 7547:
1.186 brouard 7548: /* Main decodemodel */
7549:
1.187 brouard 7550:
1.136 brouard 7551: if(decodemodel(model, lastobs) == 1)
7552: goto end;
7553:
1.137 brouard 7554: if((double)(lastobs-imx)/(double)imx > 1.10){
7555: nbwarn++;
7556: 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);
7557: 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);
7558: }
1.136 brouard 7559: /* if(mle==1){*/
1.137 brouard 7560: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7561: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 7562: }
7563:
7564: /*-calculation of age at interview from date of interview and age at death -*/
7565: agev=matrix(1,maxwav,1,imx);
7566:
7567: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7568: goto end;
7569:
1.126 brouard 7570:
1.136 brouard 7571: agegomp=(int)agemin;
7572: free_vector(moisnais,1,n);
7573: free_vector(annais,1,n);
1.126 brouard 7574: /* free_matrix(mint,1,maxwav,1,n);
7575: free_matrix(anint,1,maxwav,1,n);*/
7576: free_vector(moisdc,1,n);
7577: free_vector(andc,1,n);
1.145 brouard 7578: /* */
7579:
1.126 brouard 7580: wav=ivector(1,imx);
7581: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7582: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7583: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7584:
7585: /* Concatenates waves */
7586: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 7587: /* */
7588:
1.126 brouard 7589: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7590:
7591: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7592: ncodemax[1]=1;
1.145 brouard 7593: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 7594: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 7595: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211 brouard 7596: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186 brouard 7597: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211 brouard 7598: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145 brouard 7599:
1.200 brouard 7600: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198 brouard 7601: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186 brouard 7602: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211 brouard 7603: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
7604: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
7605: * (currently 0 or 1) in the data.
7606: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
7607: * corresponding modality (h,j).
7608: */
7609:
1.145 brouard 7610: h=0;
7611:
7612:
7613: /*if (cptcovn > 0) */
1.126 brouard 7614:
1.145 brouard 7615:
1.126 brouard 7616: m=pow(2,cptcoveff);
7617:
1.144 brouard 7618: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211 brouard 7619: * For k=4 covariates, h goes from 1 to m=2**k
7620: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
7621: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.186 brouard 7622: * h\k 1 2 3 4
1.143 brouard 7623: *______________________________
7624: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7625: * 2 2 1 1 1
7626: * 3 i=2 1 2 1 1
7627: * 4 2 2 1 1
7628: * 5 i=3 1 i=2 1 2 1
7629: * 6 2 1 2 1
7630: * 7 i=4 1 2 2 1
7631: * 8 2 2 2 1
1.197 brouard 7632: * 9 i=5 1 i=3 1 i=2 1 2
7633: * 10 2 1 1 2
7634: * 11 i=6 1 2 1 2
7635: * 12 2 2 1 2
7636: * 13 i=7 1 i=4 1 2 2
7637: * 14 2 1 2 2
7638: * 15 i=8 1 2 2 2
7639: * 16 2 2 2 2
1.143 brouard 7640: */
1.212 brouard 7641: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211 brouard 7642: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
7643: * and the value of each covariate?
7644: * V1=1, V2=1, V3=2, V4=1 ?
7645: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
7646: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
7647: * In order to get the real value in the data, we use nbcode
7648: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
7649: * We are keeping this crazy system in order to be able (in the future?)
7650: * to have more than 2 values (0 or 1) for a covariate.
7651: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7652: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
7653: * bbbbbbbb
7654: * 76543210
7655: * h-1 00000101 (6-1=5)
7656: *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
7657: * &
7658: * 1 00000001 (1)
7659: * 00000001 = 1 & ((h-1) >> (k-1))
7660: * +1= 00000010 =2
7661: *
7662: * h=14, k=3 => h'=h-1=13, k'=k-1=2
7663: * h' 1101 =2^3+2^2+0x2^1+2^0
7664: * >>k' 11
7665: * & 00000001
7666: * = 00000001
7667: * +1 = 00000010=2 = codtabm(14,3)
7668: * Reverse h=6 and m=16?
7669: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
7670: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
7671: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
7672: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
7673: * V3=decodtabm(14,3,2**4)=2
7674: * h'=13 1101 =2^3+2^2+0x2^1+2^0
7675: *(h-1) >> (j-1) 0011 =13 >> 2
7676: * &1 000000001
7677: * = 000000001
7678: * +1= 000000010 =2
7679: * 2211
7680: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
7681: * V3=2
7682: */
7683:
1.202 brouard 7684: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7685: /* /\* printf("h=%2d ", h); *\/ */
7686: /* /\* for(k=1; k <=10; k++){ *\/ */
7687: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7688: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7689: /* /\* } *\/ */
7690: /* /\* printf("\n"); *\/ */
7691: /* } */
1.197 brouard 7692: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7693: /* 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 *\/ */
7694: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7695: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7696: /* h++; */
7697: /* if (h>m) */
7698: /* h=1; */
7699: /* codtab[h][k]=j; */
7700: /* /\* codtab[12][3]=1; *\/ */
7701: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7702: /* /\* 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]]); *\/ */
7703: /* } */
7704: /* } */
7705: /* } */
7706: /* } */
1.126 brouard 7707: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7708: codtab[1][2]=1;codtab[2][2]=2; */
1.197 brouard 7709: /* for(i=1; i <=m ;i++){ */
7710: /* for(k=1; k <=cptcovn; k++){ */
7711: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7712: /* } */
7713: /* printf("\n"); */
7714: /* } */
7715: /* scanf("%d",i);*/
1.145 brouard 7716:
7717: free_ivector(Ndum,-1,NCOVMAX);
7718:
7719:
1.126 brouard 7720:
1.186 brouard 7721: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 7722: strcpy(optionfilegnuplot,optionfilefiname);
7723: if(mle==-3)
1.201 brouard 7724: strcat(optionfilegnuplot,"-MORT_");
1.126 brouard 7725: strcat(optionfilegnuplot,".gp");
7726:
7727: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7728: printf("Problem with file %s",optionfilegnuplot);
7729: }
7730: else{
1.204 brouard 7731: fprintf(ficgp,"\n# IMaCh-%s\n", version);
1.126 brouard 7732: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 7733: //fprintf(ficgp,"set missing 'NaNq'\n");
7734: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 7735: }
7736: /* fclose(ficgp);*/
1.186 brouard 7737:
7738:
7739: /* Initialisation of --------- index.htm --------*/
1.126 brouard 7740:
7741: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7742: if(mle==-3)
1.201 brouard 7743: strcat(optionfilehtm,"-MORT_");
1.126 brouard 7744: strcat(optionfilehtm,".htm");
7745: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 7746: printf("Problem with %s \n",optionfilehtm);
7747: exit(0);
1.126 brouard 7748: }
7749:
7750: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7751: strcat(optionfilehtmcov,"-cov.htm");
7752: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7753: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7754: }
7755: else{
7756: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7757: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7758: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126 brouard 7759: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7760: }
7761:
1.213 ! brouard 7762: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \
1.204 brouard 7763: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7764: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126 brouard 7765: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7766: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126 brouard 7767: \n\
7768: <hr size=\"2\" color=\"#EC5E5E\">\
7769: <ul><li><h4>Parameter files</h4>\n\
7770: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7771: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7772: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7773: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7774: - Date and time at start: %s</ul>\n",\
7775: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7776: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7777: fileres,fileres,\
7778: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7779: fflush(fichtm);
7780:
7781: strcpy(pathr,path);
7782: strcat(pathr,optionfilefiname);
1.184 brouard 7783: #ifdef WIN32
7784: _chdir(optionfilefiname); /* Move to directory named optionfile */
7785: #else
1.126 brouard 7786: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 7787: #endif
7788:
1.126 brouard 7789:
7790: /* Calculates basic frequencies. Computes observed prevalence at single age
7791: and prints on file fileres'p'. */
7792: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7793:
7794: fprintf(fichtm,"\n");
7795: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7796: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7797: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7798: imx,agemin,agemax,jmin,jmax,jmean);
7799: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7800: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7801: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7802: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7803: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7804:
7805:
7806: /* For Powell, parameters are in a vector p[] starting at p[1]
7807: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7808: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7809:
7810: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 7811: /* For mortality only */
1.126 brouard 7812: if (mle==-3){
1.136 brouard 7813: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 7814: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 7815: cens=ivector(1,n);
7816: ageexmed=vector(1,n);
7817: agecens=vector(1,n);
7818: dcwave=ivector(1,n);
7819:
7820: for (i=1; i<=imx; i++){
7821: dcwave[i]=-1;
7822: for (m=firstpass; m<=lastpass; m++)
7823: if (s[m][i]>nlstate) {
7824: dcwave[i]=m;
7825: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7826: break;
7827: }
7828: }
7829:
7830: for (i=1; i<=imx; i++) {
7831: if (wav[i]>0){
7832: ageexmed[i]=agev[mw[1][i]][i];
7833: j=wav[i];
7834: agecens[i]=1.;
7835:
7836: if (ageexmed[i]> 1 && wav[i] > 0){
7837: agecens[i]=agev[mw[j][i]][i];
7838: cens[i]= 1;
7839: }else if (ageexmed[i]< 1)
7840: cens[i]= -1;
7841: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7842: cens[i]=0 ;
7843: }
7844: else cens[i]=-1;
7845: }
7846:
7847: for (i=1;i<=NDIM;i++) {
7848: for (j=1;j<=NDIM;j++)
7849: ximort[i][j]=(i == j ? 1.0 : 0.0);
7850: }
7851:
1.145 brouard 7852: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7853: /*printf("%lf %lf", p[1], p[2]);*/
7854:
7855:
1.136 brouard 7856: #ifdef GSL
7857: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7858: #else
1.126 brouard 7859: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7860: #endif
1.201 brouard 7861: strcpy(filerespow,"POW-MORT_");
7862: strcat(filerespow,fileresu);
1.126 brouard 7863: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7864: printf("Problem with resultfile: %s\n", filerespow);
7865: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7866: }
1.136 brouard 7867: #ifdef GSL
7868: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7869: #else
1.126 brouard 7870: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7871: #endif
1.126 brouard 7872: /* for (i=1;i<=nlstate;i++)
7873: for(j=1;j<=nlstate+ndeath;j++)
7874: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7875: */
7876: fprintf(ficrespow,"\n");
1.136 brouard 7877: #ifdef GSL
7878: /* gsl starts here */
7879: T = gsl_multimin_fminimizer_nmsimplex;
7880: gsl_multimin_fminimizer *sfm = NULL;
7881: gsl_vector *ss, *x;
7882: gsl_multimin_function minex_func;
7883:
7884: /* Initial vertex size vector */
7885: ss = gsl_vector_alloc (NDIM);
7886:
7887: if (ss == NULL){
7888: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7889: }
7890: /* Set all step sizes to 1 */
7891: gsl_vector_set_all (ss, 0.001);
7892:
7893: /* Starting point */
1.126 brouard 7894:
1.136 brouard 7895: x = gsl_vector_alloc (NDIM);
7896:
7897: if (x == NULL){
7898: gsl_vector_free(ss);
7899: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7900: }
7901:
7902: /* Initialize method and iterate */
7903: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7904: /* gsl_vector_set(x, 0, 0.0268); */
7905: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7906: gsl_vector_set(x, 0, p[1]);
7907: gsl_vector_set(x, 1, p[2]);
7908:
7909: minex_func.f = &gompertz_f;
7910: minex_func.n = NDIM;
7911: minex_func.params = (void *)&p; /* ??? */
7912:
7913: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7914: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7915:
7916: printf("Iterations beginning .....\n\n");
7917: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7918:
7919: iteri=0;
7920: while (rval == GSL_CONTINUE){
7921: iteri++;
7922: status = gsl_multimin_fminimizer_iterate(sfm);
7923:
7924: if (status) printf("error: %s\n", gsl_strerror (status));
7925: fflush(0);
7926:
7927: if (status)
7928: break;
7929:
7930: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7931: ssval = gsl_multimin_fminimizer_size (sfm);
7932:
7933: if (rval == GSL_SUCCESS)
7934: printf ("converged to a local maximum at\n");
7935:
7936: printf("%5d ", iteri);
7937: for (it = 0; it < NDIM; it++){
7938: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7939: }
7940: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7941: }
7942:
7943: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7944:
7945: gsl_vector_free(x); /* initial values */
7946: gsl_vector_free(ss); /* inital step size */
7947: for (it=0; it<NDIM; it++){
7948: p[it+1]=gsl_vector_get(sfm->x,it);
7949: fprintf(ficrespow," %.12lf", p[it]);
7950: }
7951: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7952: #endif
7953: #ifdef POWELL
7954: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7955: #endif
1.126 brouard 7956: fclose(ficrespow);
7957:
1.203 brouard 7958: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
1.126 brouard 7959:
7960: for(i=1; i <=NDIM; i++)
7961: for(j=i+1;j<=NDIM;j++)
7962: matcov[i][j]=matcov[j][i];
7963:
7964: printf("\nCovariance matrix\n ");
1.203 brouard 7965: fprintf(ficlog,"\nCovariance matrix\n ");
1.126 brouard 7966: for(i=1; i <=NDIM; i++) {
7967: for(j=1;j<=NDIM;j++){
7968: printf("%f ",matcov[i][j]);
1.203 brouard 7969: fprintf(ficlog,"%f ",matcov[i][j]);
1.126 brouard 7970: }
1.203 brouard 7971: printf("\n "); fprintf(ficlog,"\n ");
1.126 brouard 7972: }
7973:
7974: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7975: for (i=1;i<=NDIM;i++) {
1.126 brouard 7976: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7977: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7978: }
1.126 brouard 7979: lsurv=vector(1,AGESUP);
7980: lpop=vector(1,AGESUP);
7981: tpop=vector(1,AGESUP);
7982: lsurv[agegomp]=100000;
7983:
7984: for (k=agegomp;k<=AGESUP;k++) {
7985: agemortsup=k;
7986: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7987: }
7988:
7989: for (k=agegomp;k<agemortsup;k++)
7990: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7991:
7992: for (k=agegomp;k<agemortsup;k++){
7993: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7994: sumlpop=sumlpop+lpop[k];
7995: }
7996:
7997: tpop[agegomp]=sumlpop;
7998: for (k=agegomp;k<(agemortsup-3);k++){
7999: /* tpop[k+1]=2;*/
8000: tpop[k+1]=tpop[k]-lpop[k];
8001: }
8002:
8003:
8004: printf("\nAge lx qx dx Lx Tx e(x)\n");
8005: for (k=agegomp;k<(agemortsup-2);k++)
8006: 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]);
8007:
8008:
8009: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 8010: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
8011: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8012: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8013: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8014: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8015: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8016: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8017: }else
1.201 brouard 8018: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8019: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126 brouard 8020: stepm, weightopt,\
8021: model,imx,p,matcov,agemortsup);
8022:
8023: free_vector(lsurv,1,AGESUP);
8024: free_vector(lpop,1,AGESUP);
8025: free_vector(tpop,1,AGESUP);
1.136 brouard 8026: #ifdef GSL
8027: free_ivector(cens,1,n);
8028: free_vector(agecens,1,n);
8029: free_ivector(dcwave,1,n);
8030: free_matrix(ximort,1,NDIM,1,NDIM);
8031: #endif
1.186 brouard 8032: } /* Endof if mle==-3 mortality only */
1.205 brouard 8033: /* Standard */
8034: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
8035: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8036: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132 brouard 8037: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 8038: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8039: for (k=1; k<=npar;k++)
8040: printf(" %d %8.5f",k,p[k]);
8041: printf("\n");
1.205 brouard 8042: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
8043: /* mlikeli uses func not funcone */
8044: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
8045: }
8046: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
8047: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8048: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8049: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8050: }
8051: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126 brouard 8052: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8053: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8054: for (k=1; k<=npar;k++)
8055: printf(" %d %8.5f",k,p[k]);
8056: printf("\n");
8057:
8058: /*--------- results files --------------*/
1.192 brouard 8059: 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 8060:
8061:
8062: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8063: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8064: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8065: for(i=1,jk=1; i <=nlstate; i++){
8066: for(k=1; k <=(nlstate+ndeath); k++){
8067: if (k != i) {
8068: printf("%d%d ",i,k);
8069: fprintf(ficlog,"%d%d ",i,k);
8070: fprintf(ficres,"%1d%1d ",i,k);
8071: for(j=1; j <=ncovmodel; j++){
1.190 brouard 8072: printf("%12.7f ",p[jk]);
8073: fprintf(ficlog,"%12.7f ",p[jk]);
8074: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 8075: jk++;
8076: }
8077: printf("\n");
8078: fprintf(ficlog,"\n");
8079: fprintf(ficres,"\n");
8080: }
8081: }
8082: }
1.203 brouard 8083: if(mle != 0){
8084: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126 brouard 8085: ftolhess=ftol; /* Usually correct */
1.203 brouard 8086: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
8087: 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");
8088: 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");
8089: for(i=1,jk=1; i <=nlstate; i++){
8090: for(k=1; k <=(nlstate+ndeath); k++){
8091: if (k != i) {
8092: printf("%d%d ",i,k);
8093: fprintf(ficlog,"%d%d ",i,k);
8094: for(j=1; j <=ncovmodel; j++){
8095: 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]));
8096: 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]));
8097: jk++;
8098: }
8099: printf("\n");
8100: fprintf(ficlog,"\n");
1.193 brouard 8101: }
8102: }
8103: }
1.203 brouard 8104: } /* end of hesscov and Wald tests */
1.193 brouard 8105:
1.203 brouard 8106: /* */
1.126 brouard 8107: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
8108: printf("# Scales (for hessian or gradient estimation)\n");
8109: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
8110: for(i=1,jk=1; i <=nlstate; i++){
8111: for(j=1; j <=nlstate+ndeath; j++){
8112: if (j!=i) {
8113: fprintf(ficres,"%1d%1d",i,j);
8114: printf("%1d%1d",i,j);
8115: fprintf(ficlog,"%1d%1d",i,j);
8116: for(k=1; k<=ncovmodel;k++){
8117: printf(" %.5e",delti[jk]);
8118: fprintf(ficlog," %.5e",delti[jk]);
8119: fprintf(ficres," %.5e",delti[jk]);
8120: jk++;
8121: }
8122: printf("\n");
8123: fprintf(ficlog,"\n");
8124: fprintf(ficres,"\n");
8125: }
8126: }
8127: }
8128:
8129: 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");
1.203 brouard 8130: if(mle >= 1) /* To big for the screen */
1.126 brouard 8131: 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");
8132: 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");
8133: /* # 121 Var(a12)\n\ */
8134: /* # 122 Cov(b12,a12) Var(b12)\n\ */
8135: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
8136: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
8137: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
8138: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
8139: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
8140: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
8141:
8142:
8143: /* Just to have a covariance matrix which will be more understandable
8144: even is we still don't want to manage dictionary of variables
8145: */
8146: for(itimes=1;itimes<=2;itimes++){
8147: jj=0;
8148: for(i=1; i <=nlstate; i++){
8149: for(j=1; j <=nlstate+ndeath; j++){
8150: if(j==i) continue;
8151: for(k=1; k<=ncovmodel;k++){
8152: jj++;
8153: ca[0]= k+'a'-1;ca[1]='\0';
8154: if(itimes==1){
8155: if(mle>=1)
8156: printf("#%1d%1d%d",i,j,k);
8157: fprintf(ficlog,"#%1d%1d%d",i,j,k);
8158: fprintf(ficres,"#%1d%1d%d",i,j,k);
8159: }else{
8160: if(mle>=1)
8161: printf("%1d%1d%d",i,j,k);
8162: fprintf(ficlog,"%1d%1d%d",i,j,k);
8163: fprintf(ficres,"%1d%1d%d",i,j,k);
8164: }
8165: ll=0;
8166: for(li=1;li <=nlstate; li++){
8167: for(lj=1;lj <=nlstate+ndeath; lj++){
8168: if(lj==li) continue;
8169: for(lk=1;lk<=ncovmodel;lk++){
8170: ll++;
8171: if(ll<=jj){
8172: cb[0]= lk +'a'-1;cb[1]='\0';
8173: if(ll<jj){
8174: if(itimes==1){
8175: if(mle>=1)
8176: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8177: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8178: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8179: }else{
8180: if(mle>=1)
8181: printf(" %.5e",matcov[jj][ll]);
8182: fprintf(ficlog," %.5e",matcov[jj][ll]);
8183: fprintf(ficres," %.5e",matcov[jj][ll]);
8184: }
8185: }else{
8186: if(itimes==1){
8187: if(mle>=1)
8188: printf(" Var(%s%1d%1d)",ca,i,j);
8189: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
8190: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
8191: }else{
8192: if(mle>=1)
1.203 brouard 8193: printf(" %.7e",matcov[jj][ll]);
8194: fprintf(ficlog," %.7e",matcov[jj][ll]);
8195: fprintf(ficres," %.7e",matcov[jj][ll]);
1.126 brouard 8196: }
8197: }
8198: }
8199: } /* end lk */
8200: } /* end lj */
8201: } /* end li */
8202: if(mle>=1)
8203: printf("\n");
8204: fprintf(ficlog,"\n");
8205: fprintf(ficres,"\n");
8206: numlinepar++;
8207: } /* end k*/
8208: } /*end j */
8209: } /* end i */
8210: } /* end itimes */
8211:
8212: fflush(ficlog);
8213: fflush(ficres);
1.209 brouard 8214: while(fgets(line, MAXLINE, ficpar)) {
8215: /* If line starts with a # it is a comment */
8216: if (line[0] == '#') {
8217: numlinepar++;
1.141 brouard 8218: fputs(line,stdout);
1.126 brouard 8219: fputs(line,ficparo);
1.209 brouard 8220: fputs(line,ficlog);
8221: continue;
8222: }else
8223: break;
8224: }
8225:
8226: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
8227: /* ungetc(c,ficpar); */
8228: /* fgets(line, MAXLINE, ficpar); */
8229: /* fputs(line,stdout); */
8230: /* fputs(line,ficparo); */
8231: /* } */
8232: /* ungetc(c,ficpar); */
1.126 brouard 8233:
8234: estepm=0;
1.209 brouard 8235: if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
8236:
8237: if (num_filled != 6) {
8238: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
8239: printf("but line=%s\n",line);
8240: goto end;
8241: }
8242: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
8243: }
8244: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8245: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8246:
8247: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126 brouard 8248: if (estepm==0 || estepm < stepm) estepm=stepm;
8249: if (fage <= 2) {
8250: bage = ageminpar;
8251: fage = agemaxpar;
8252: }
8253:
8254: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211 brouard 8255: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8256: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186 brouard 8257:
8258: /* Other stuffs, more or less useful */
1.126 brouard 8259: while((c=getc(ficpar))=='#' && c!= EOF){
8260: ungetc(c,ficpar);
8261: fgets(line, MAXLINE, ficpar);
1.141 brouard 8262: fputs(line,stdout);
1.126 brouard 8263: fputs(line,ficparo);
8264: }
8265: ungetc(c,ficpar);
8266:
8267: 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);
8268: 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);
8269: 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);
8270: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8271: 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);
8272:
8273: while((c=getc(ficpar))=='#' && c!= EOF){
8274: ungetc(c,ficpar);
8275: fgets(line, MAXLINE, ficpar);
1.141 brouard 8276: fputs(line,stdout);
1.126 brouard 8277: fputs(line,ficparo);
8278: }
8279: ungetc(c,ficpar);
8280:
8281:
8282: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8283: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8284:
8285: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 8286: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 8287: fprintf(ficparo,"pop_based=%d\n",popbased);
8288: fprintf(ficres,"pop_based=%d\n",popbased);
8289:
8290: while((c=getc(ficpar))=='#' && c!= EOF){
8291: ungetc(c,ficpar);
8292: fgets(line, MAXLINE, ficpar);
1.141 brouard 8293: fputs(line,stdout);
1.126 brouard 8294: fputs(line,ficparo);
8295: }
8296: ungetc(c,ficpar);
8297:
8298: 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);
8299: 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);
8300: 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);
8301: 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);
8302: 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);
8303: /* day and month of proj2 are not used but only year anproj2.*/
8304:
8305:
8306:
1.145 brouard 8307: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8308: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 8309:
8310: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 8311: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8312: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8313: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8314: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8315: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8316: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8317: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8318: }else
1.211 brouard 8319: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126 brouard 8320:
1.201 brouard 8321: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211 brouard 8322: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.213 ! brouard 8323: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126 brouard 8324:
8325: /*------------ free_vector -------------*/
8326: /* chdir(path); */
8327:
8328: free_ivector(wav,1,imx);
8329: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
8330: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
8331: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
8332: free_lvector(num,1,n);
8333: free_vector(agedc,1,n);
8334: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8335: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8336: fclose(ficparo);
8337: fclose(ficres);
8338:
8339:
1.186 brouard 8340: /* Other results (useful)*/
8341:
8342:
1.126 brouard 8343: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 8344: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8345: prlim=matrix(1,nlstate,1,nlstate);
1.209 brouard 8346: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126 brouard 8347: fclose(ficrespl);
8348:
1.145 brouard 8349: #ifdef FREEEXIT2
8350: #include "freeexit2.h"
8351: #endif
8352:
1.126 brouard 8353: /*------------- h Pij x at various ages ------------*/
1.180 brouard 8354: /*#include "hpijx.h"*/
8355: hPijx(p, bage, fage);
1.145 brouard 8356: fclose(ficrespij);
1.126 brouard 8357:
1.145 brouard 8358: /*-------------- Variance of one-step probabilities---*/
8359: k=1;
1.126 brouard 8360: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8361:
8362:
8363: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8364: for(i=1;i<=AGESUP;i++)
8365: for(j=1;j<=NCOVMAX;j++)
8366: for(k=1;k<=NCOVMAX;k++)
8367: probs[i][j][k]=0.;
8368:
8369: /*---------- Forecasting ------------------*/
8370: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8371: if(prevfcast==1){
8372: /* if(stepm ==1){*/
1.201 brouard 8373: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126 brouard 8374: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8375: /* } */
8376: /* else{ */
8377: /* erreur=108; */
8378: /* 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); */
8379: /* 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); */
8380: /* } */
8381: }
1.186 brouard 8382:
8383: /* ------ Other prevalence ratios------------ */
1.126 brouard 8384:
1.127 brouard 8385: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8386:
8387: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8388: /* 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",\
8389: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8390: */
1.126 brouard 8391:
1.127 brouard 8392: if (mobilav!=0) {
8393: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8394: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8395: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8396: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8397: }
1.126 brouard 8398: }
8399:
8400:
1.127 brouard 8401: /*---------- Health expectancies, no variances ------------*/
8402:
1.201 brouard 8403: strcpy(filerese,"E_");
8404: strcat(filerese,fileresu);
1.126 brouard 8405: if((ficreseij=fopen(filerese,"w"))==NULL) {
8406: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8407: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8408: }
1.208 brouard 8409: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8410: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145 brouard 8411: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8412: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8413:
8414: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 8415: fprintf(ficreseij,"\n#****** ");
8416: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 8417: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127 brouard 8418: }
8419: fprintf(ficreseij,"******\n");
8420:
8421: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8422: oldm=oldms;savm=savms;
8423: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8424:
8425: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8426: /*}*/
1.127 brouard 8427: }
8428: fclose(ficreseij);
1.208 brouard 8429: printf("done evsij\n");fflush(stdout);
8430: fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127 brouard 8431:
8432: /*---------- Health expectancies and variances ------------*/
8433:
8434:
1.201 brouard 8435: strcpy(filerest,"T_");
8436: strcat(filerest,fileresu);
1.127 brouard 8437: if((ficrest=fopen(filerest,"w"))==NULL) {
8438: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8439: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8440: }
1.208 brouard 8441: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8442: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127 brouard 8443:
1.126 brouard 8444:
1.201 brouard 8445: strcpy(fileresstde,"STDE_");
8446: strcat(fileresstde,fileresu);
1.126 brouard 8447: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8448: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8449: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8450: }
1.208 brouard 8451: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8452: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126 brouard 8453:
1.201 brouard 8454: strcpy(filerescve,"CVE_");
8455: strcat(filerescve,fileresu);
1.126 brouard 8456: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8457: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8458: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8459: }
1.208 brouard 8460: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8461: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126 brouard 8462:
1.201 brouard 8463: strcpy(fileresv,"V_");
8464: strcat(fileresv,fileresu);
1.126 brouard 8465: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8466: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8467: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8468: }
1.208 brouard 8469: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8470: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126 brouard 8471:
1.145 brouard 8472: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8473: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8474:
8475: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208 brouard 8476: fprintf(ficrest,"\n#****** ");
8477: for(j=1;j<=cptcoveff;j++)
8478: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8479: fprintf(ficrest,"******\n");
8480:
8481: fprintf(ficresstdeij,"\n#****** ");
8482: fprintf(ficrescveij,"\n#****** ");
8483: for(j=1;j<=cptcoveff;j++) {
8484: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8485: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8486: }
8487: fprintf(ficresstdeij,"******\n");
8488: fprintf(ficrescveij,"******\n");
8489:
8490: fprintf(ficresvij,"\n#****** ");
8491: for(j=1;j<=cptcoveff;j++)
8492: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8493: fprintf(ficresvij,"******\n");
8494:
8495: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8496: oldm=oldms;savm=savms;
8497: printf(" cvevsij %d, ",k);
8498: fprintf(ficlog, " cvevsij %d, ",k);
8499: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8500: printf(" end cvevsij \n ");
8501: fprintf(ficlog, " end cvevsij \n ");
8502:
8503: /*
8504: */
8505: /* goto endfree; */
8506:
8507: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8508: pstamp(ficrest);
8509:
8510:
8511: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8512: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8513: cptcod= 0; /* To be deleted */
8514: printf("varevsij %d \n",vpopbased);
8515: fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209 brouard 8516: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.208 brouard 8517: 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 ");
8518: if(vpopbased==1)
8519: 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);
8520: else
8521: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8522: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8523: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8524: fprintf(ficrest,"\n");
8525: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8526: epj=vector(1,nlstate+1);
8527: printf("Computing age specific period (stable) prevalences in each health state \n");
8528: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8529: for(age=bage; age <=fage ;age++){
1.209 brouard 8530: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208 brouard 8531: if (vpopbased==1) {
8532: if(mobilav ==0){
8533: for(i=1; i<=nlstate;i++)
8534: prlim[i][i]=probs[(int)age][i][k];
8535: }else{ /* mobilav */
8536: for(i=1; i<=nlstate;i++)
8537: prlim[i][i]=mobaverage[(int)age][i][k];
1.126 brouard 8538: }
1.208 brouard 8539: }
8540:
8541: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8542: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8543: /* printf(" age %4.0f ",age); */
8544: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8545: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8546: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8547: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8548: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126 brouard 8549: }
1.208 brouard 8550: epj[nlstate+1] +=epj[j];
8551: }
8552: /* printf(" age %4.0f \n",age); */
8553:
8554: for(i=1, vepp=0.;i <=nlstate;i++)
8555: for(j=1;j <=nlstate;j++)
8556: vepp += vareij[i][j][(int)age];
8557: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8558: for(j=1;j <=nlstate;j++){
8559: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126 brouard 8560: }
1.208 brouard 8561: fprintf(ficrest,"\n");
1.126 brouard 8562: }
1.208 brouard 8563: } /* End vpopbased */
8564: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8565: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8566: free_vector(epj,1,nlstate+1);
8567: printf("done \n");fflush(stdout);
8568: fprintf(ficlog,"done\n");fflush(ficlog);
8569:
1.145 brouard 8570: /*}*/
1.208 brouard 8571: } /* End k */
1.126 brouard 8572: free_vector(weight,1,n);
1.145 brouard 8573: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 8574: free_imatrix(s,1,maxwav+1,1,n);
8575: free_matrix(anint,1,maxwav,1,n);
8576: free_matrix(mint,1,maxwav,1,n);
8577: free_ivector(cod,1,n);
8578: free_ivector(tab,1,NCOVMAX);
8579: fclose(ficresstdeij);
8580: fclose(ficrescveij);
8581: fclose(ficresvij);
8582: fclose(ficrest);
1.208 brouard 8583: printf("done Health expectancies\n");fflush(stdout);
8584: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126 brouard 8585: fclose(ficpar);
8586:
8587: /*------- Variance of period (stable) prevalence------*/
8588:
1.201 brouard 8589: strcpy(fileresvpl,"VPL_");
8590: strcat(fileresvpl,fileresu);
1.126 brouard 8591: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8592: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8593: exit(0);
8594: }
1.208 brouard 8595: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8596: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126 brouard 8597:
1.145 brouard 8598: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8599: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8600:
8601: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8602: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 8603: for(j=1;j<=cptcoveff;j++)
1.200 brouard 8604: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8605: fprintf(ficresvpl,"******\n");
8606:
8607: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8608: oldm=oldms;savm=savms;
1.209 brouard 8609: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126 brouard 8610: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8611: /*}*/
1.126 brouard 8612: }
8613:
8614: fclose(ficresvpl);
1.208 brouard 8615: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8616: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126 brouard 8617:
8618: /*---------- End : free ----------------*/
8619: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8620: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8621: } /* mle==-3 arrives here for freeing */
1.164 brouard 8622: /* endfree:*/
1.141 brouard 8623: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 8624: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8625: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8626: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8627: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8628: free_matrix(covar,0,NCOVMAX,1,n);
8629: free_matrix(matcov,1,npar,1,npar);
1.203 brouard 8630: free_matrix(hess,1,npar,1,npar);
1.126 brouard 8631: /*free_vector(delti,1,npar);*/
8632: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8633: free_matrix(agev,1,maxwav,1,imx);
8634: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8635:
1.145 brouard 8636: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 8637: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 8638: free_ivector(Tvar,1,NCOVMAX);
8639: free_ivector(Tprod,1,NCOVMAX);
8640: free_ivector(Tvaraff,1,NCOVMAX);
8641: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 8642:
8643: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200 brouard 8644: /* free_imatrix(codtab,1,100,1,10); */
1.126 brouard 8645: fflush(fichtm);
8646: fflush(ficgp);
8647:
8648:
8649: if((nberr >0) || (nbwarn>0)){
8650: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8651: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8652: }else{
8653: printf("End of Imach\n");
8654: fprintf(ficlog,"End of Imach\n");
8655: }
8656: printf("See log file on %s\n",filelog);
8657: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 8658: /*(void) gettimeofday(&end_time,&tzp);*/
8659: rend_time = time(NULL);
8660: end_time = *localtime(&rend_time);
8661: /* tml = *localtime(&end_time.tm_sec); */
8662: strcpy(strtend,asctime(&end_time));
1.126 brouard 8663: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8664: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 8665: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 8666:
1.157 brouard 8667: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8668: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8669: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 8670: /* printf("Total time was %d uSec.\n", total_usecs);*/
8671: /* if(fileappend(fichtm,optionfilehtm)){ */
8672: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8673: fclose(fichtm);
8674: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8675: fclose(fichtmcov);
8676: fclose(ficgp);
8677: fclose(ficlog);
8678: /*------ End -----------*/
8679:
8680:
8681: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 8682: #ifdef WIN32
8683: if (_chdir(pathcd) != 0)
8684: printf("Can't move to directory %s!\n",path);
8685: if(_getcwd(pathcd,MAXLINE) > 0)
8686: #else
1.126 brouard 8687: if(chdir(pathcd) != 0)
1.184 brouard 8688: printf("Can't move to directory %s!\n", path);
8689: if (getcwd(pathcd, MAXLINE) > 0)
8690: #endif
1.126 brouard 8691: printf("Current directory %s!\n",pathcd);
8692: /*strcat(plotcmd,CHARSEPARATOR);*/
8693: sprintf(plotcmd,"gnuplot");
1.157 brouard 8694: #ifdef _WIN32
1.126 brouard 8695: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8696: #endif
8697: if(!stat(plotcmd,&info)){
1.158 brouard 8698: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8699: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 8700: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 8701: }else
8702: strcpy(pplotcmd,plotcmd);
1.157 brouard 8703: #ifdef __unix
1.126 brouard 8704: strcpy(plotcmd,GNUPLOTPROGRAM);
8705: if(!stat(plotcmd,&info)){
1.158 brouard 8706: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8707: }else
8708: strcpy(pplotcmd,plotcmd);
8709: #endif
8710: }else
8711: strcpy(pplotcmd,plotcmd);
8712:
8713: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 8714: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8715:
8716: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 8717: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 8718: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 8719: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 8720: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 8721: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 8722: }
1.158 brouard 8723: printf(" Successful, please wait...");
1.126 brouard 8724: while (z[0] != 'q') {
8725: /* chdir(path); */
1.154 brouard 8726: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 8727: scanf("%s",z);
8728: /* if (z[0] == 'c') system("./imach"); */
8729: if (z[0] == 'e') {
1.158 brouard 8730: #ifdef __APPLE__
1.152 brouard 8731: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 8732: #elif __linux
8733: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 8734: #else
1.152 brouard 8735: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 8736: #endif
8737: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8738: system(pplotcmd);
1.126 brouard 8739: }
8740: else if (z[0] == 'g') system(plotcmd);
8741: else if (z[0] == 'q') exit(0);
8742: }
8743: end:
8744: while (z[0] != 'q') {
1.195 brouard 8745: printf("\nType q for exiting: "); fflush(stdout);
1.126 brouard 8746: scanf("%s",z);
8747: }
8748: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>