Annotation of imach/src/imach.c, revision 1.212
1.212 ! brouard 1: /* $Id: imach.c,v 1.211 2015/11/21 12:41:11 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.212 ! brouard 4: Revision 1.211 2015/11/21 12:41:11 brouard
! 5: Summary: 0.98r3 with some graph of projected cross-sectional
! 6:
! 7: Author: Nicolas Brouard
! 8:
1.211 brouard 9: Revision 1.210 2015/11/18 17:41:20 brouard
10: Summary: Start working on projected prevalences
11:
1.210 brouard 12: Revision 1.209 2015/11/17 22:12:03 brouard
13: Summary: Adding ftolpl parameter
14: Author: N Brouard
15:
16: We had difficulties to get smoothed confidence intervals. It was due
17: to the period prevalence which wasn't computed accurately. The inner
18: parameter ftolpl is now an outer parameter of the .imach parameter
19: file after estepm. If ftolpl is small 1.e-4 and estepm too,
20: computation are long.
21:
1.209 brouard 22: Revision 1.208 2015/11/17 14:31:57 brouard
23: Summary: temporary
24:
1.208 brouard 25: Revision 1.207 2015/10/27 17:36:57 brouard
26: *** empty log message ***
27:
1.207 brouard 28: Revision 1.206 2015/10/24 07:14:11 brouard
29: *** empty log message ***
30:
1.206 brouard 31: Revision 1.205 2015/10/23 15:50:53 brouard
32: Summary: 0.98r3 some clarification for graphs on likelihood contributions
33:
1.205 brouard 34: Revision 1.204 2015/10/01 16:20:26 brouard
35: Summary: Some new graphs of contribution to likelihood
36:
1.204 brouard 37: Revision 1.203 2015/09/30 17:45:14 brouard
38: Summary: looking at better estimation of the hessian
39:
40: Also a better criteria for convergence to the period prevalence And
41: therefore adding the number of years needed to converge. (The
42: prevalence in any alive state shold sum to one
43:
1.203 brouard 44: Revision 1.202 2015/09/22 19:45:16 brouard
45: Summary: Adding some overall graph on contribution to likelihood. Might change
46:
1.202 brouard 47: Revision 1.201 2015/09/15 17:34:58 brouard
48: Summary: 0.98r0
49:
50: - Some new graphs like suvival functions
51: - Some bugs fixed like model=1+age+V2.
52:
1.201 brouard 53: Revision 1.200 2015/09/09 16:53:55 brouard
54: Summary: Big bug thanks to Flavia
55:
56: Even model=1+age+V2. did not work anymore
57:
1.200 brouard 58: Revision 1.199 2015/09/07 14:09:23 brouard
59: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
60:
1.199 brouard 61: Revision 1.198 2015/09/03 07:14:39 brouard
62: Summary: 0.98q5 Flavia
63:
1.198 brouard 64: Revision 1.197 2015/09/01 18:24:39 brouard
65: *** empty log message ***
66:
1.197 brouard 67: Revision 1.196 2015/08/18 23:17:52 brouard
68: Summary: 0.98q5
69:
1.196 brouard 70: Revision 1.195 2015/08/18 16:28:39 brouard
71: Summary: Adding a hack for testing purpose
72:
73: After reading the title, ftol and model lines, if the comment line has
74: a q, starting with #q, the answer at the end of the run is quit. It
75: permits to run test files in batch with ctest. The former workaround was
76: $ echo q | imach foo.imach
77:
1.195 brouard 78: Revision 1.194 2015/08/18 13:32:00 brouard
79: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
80:
1.194 brouard 81: Revision 1.193 2015/08/04 07:17:42 brouard
82: Summary: 0.98q4
83:
1.193 brouard 84: Revision 1.192 2015/07/16 16:49:02 brouard
85: Summary: Fixing some outputs
86:
1.192 brouard 87: Revision 1.191 2015/07/14 10:00:33 brouard
88: Summary: Some fixes
89:
1.191 brouard 90: Revision 1.190 2015/05/05 08:51:13 brouard
91: Summary: Adding digits in output parameters (7 digits instead of 6)
92:
93: Fix 1+age+.
94:
1.190 brouard 95: Revision 1.189 2015/04/30 14:45:16 brouard
96: Summary: 0.98q2
97:
1.189 brouard 98: Revision 1.188 2015/04/30 08:27:53 brouard
99: *** empty log message ***
100:
1.188 brouard 101: Revision 1.187 2015/04/29 09:11:15 brouard
102: *** empty log message ***
103:
1.187 brouard 104: Revision 1.186 2015/04/23 12:01:52 brouard
105: Summary: V1*age is working now, version 0.98q1
106:
107: Some codes had been disabled in order to simplify and Vn*age was
108: working in the optimization phase, ie, giving correct MLE parameters,
109: but, as usual, outputs were not correct and program core dumped.
110:
1.186 brouard 111: Revision 1.185 2015/03/11 13:26:42 brouard
112: Summary: Inclusion of compile and links command line for Intel Compiler
113:
1.185 brouard 114: Revision 1.184 2015/03/11 11:52:39 brouard
115: Summary: Back from Windows 8. Intel Compiler
116:
1.184 brouard 117: Revision 1.183 2015/03/10 20:34:32 brouard
118: Summary: 0.98q0, trying with directest, mnbrak fixed
119:
120: We use directest instead of original Powell test; probably no
121: incidence on the results, but better justifications;
122: We fixed Numerical Recipes mnbrak routine which was wrong and gave
123: wrong results.
124:
1.183 brouard 125: Revision 1.182 2015/02/12 08:19:57 brouard
126: Summary: Trying to keep directest which seems simpler and more general
127: Author: Nicolas Brouard
128:
1.182 brouard 129: Revision 1.181 2015/02/11 23:22:24 brouard
130: Summary: Comments on Powell added
131:
132: Author:
133:
1.181 brouard 134: Revision 1.180 2015/02/11 17:33:45 brouard
135: Summary: Finishing move from main to function (hpijx and prevalence_limit)
136:
1.180 brouard 137: Revision 1.179 2015/01/04 09:57:06 brouard
138: Summary: back to OS/X
139:
1.179 brouard 140: Revision 1.178 2015/01/04 09:35:48 brouard
141: *** empty log message ***
142:
1.178 brouard 143: Revision 1.177 2015/01/03 18:40:56 brouard
144: Summary: Still testing ilc32 on OSX
145:
1.177 brouard 146: Revision 1.176 2015/01/03 16:45:04 brouard
147: *** empty log message ***
148:
1.176 brouard 149: Revision 1.175 2015/01/03 16:33:42 brouard
150: *** empty log message ***
151:
1.175 brouard 152: Revision 1.174 2015/01/03 16:15:49 brouard
153: Summary: Still in cross-compilation
154:
1.174 brouard 155: Revision 1.173 2015/01/03 12:06:26 brouard
156: Summary: trying to detect cross-compilation
157:
1.173 brouard 158: Revision 1.172 2014/12/27 12:07:47 brouard
159: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
160:
1.172 brouard 161: Revision 1.171 2014/12/23 13:26:59 brouard
162: Summary: Back from Visual C
163:
164: Still problem with utsname.h on Windows
165:
1.171 brouard 166: Revision 1.170 2014/12/23 11:17:12 brouard
167: Summary: Cleaning some \%% back to %%
168:
169: The escape was mandatory for a specific compiler (which one?), but too many warnings.
170:
1.170 brouard 171: Revision 1.169 2014/12/22 23:08:31 brouard
172: Summary: 0.98p
173:
174: Outputs some informations on compiler used, OS etc. Testing on different platforms.
175:
1.169 brouard 176: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 177: Summary: update
1.169 brouard 178:
1.168 brouard 179: Revision 1.167 2014/12/22 13:50:56 brouard
180: Summary: Testing uname and compiler version and if compiled 32 or 64
181:
182: Testing on Linux 64
183:
1.167 brouard 184: Revision 1.166 2014/12/22 11:40:47 brouard
185: *** empty log message ***
186:
1.166 brouard 187: Revision 1.165 2014/12/16 11:20:36 brouard
188: Summary: After compiling on Visual C
189:
190: * imach.c (Module): Merging 1.61 to 1.162
191:
1.165 brouard 192: Revision 1.164 2014/12/16 10:52:11 brouard
193: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
194:
195: * imach.c (Module): Merging 1.61 to 1.162
196:
1.164 brouard 197: Revision 1.163 2014/12/16 10:30:11 brouard
198: * imach.c (Module): Merging 1.61 to 1.162
199:
1.163 brouard 200: Revision 1.162 2014/09/25 11:43:39 brouard
201: Summary: temporary backup 0.99!
202:
1.162 brouard 203: Revision 1.1 2014/09/16 11:06:58 brouard
204: Summary: With some code (wrong) for nlopt
205:
206: Author:
207:
208: Revision 1.161 2014/09/15 20:41:41 brouard
209: Summary: Problem with macro SQR on Intel compiler
210:
1.161 brouard 211: Revision 1.160 2014/09/02 09:24:05 brouard
212: *** empty log message ***
213:
1.160 brouard 214: Revision 1.159 2014/09/01 10:34:10 brouard
215: Summary: WIN32
216: Author: Brouard
217:
1.159 brouard 218: Revision 1.158 2014/08/27 17:11:51 brouard
219: *** empty log message ***
220:
1.158 brouard 221: Revision 1.157 2014/08/27 16:26:55 brouard
222: Summary: Preparing windows Visual studio version
223: Author: Brouard
224:
225: In order to compile on Visual studio, time.h is now correct and time_t
226: and tm struct should be used. difftime should be used but sometimes I
227: just make the differences in raw time format (time(&now).
228: Trying to suppress #ifdef LINUX
229: Add xdg-open for __linux in order to open default browser.
230:
1.157 brouard 231: Revision 1.156 2014/08/25 20:10:10 brouard
232: *** empty log message ***
233:
1.156 brouard 234: Revision 1.155 2014/08/25 18:32:34 brouard
235: Summary: New compile, minor changes
236: Author: Brouard
237:
1.155 brouard 238: Revision 1.154 2014/06/20 17:32:08 brouard
239: Summary: Outputs now all graphs of convergence to period prevalence
240:
1.154 brouard 241: Revision 1.153 2014/06/20 16:45:46 brouard
242: Summary: If 3 live state, convergence to period prevalence on same graph
243: Author: Brouard
244:
1.153 brouard 245: Revision 1.152 2014/06/18 17:54:09 brouard
246: Summary: open browser, use gnuplot on same dir than imach if not found in the path
247:
1.152 brouard 248: Revision 1.151 2014/06/18 16:43:30 brouard
249: *** empty log message ***
250:
1.151 brouard 251: Revision 1.150 2014/06/18 16:42:35 brouard
252: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
253: Author: brouard
254:
1.150 brouard 255: Revision 1.149 2014/06/18 15:51:14 brouard
256: Summary: Some fixes in parameter files errors
257: Author: Nicolas Brouard
258:
1.149 brouard 259: Revision 1.148 2014/06/17 17:38:48 brouard
260: Summary: Nothing new
261: Author: Brouard
262:
263: Just a new packaging for OS/X version 0.98nS
264:
1.148 brouard 265: Revision 1.147 2014/06/16 10:33:11 brouard
266: *** empty log message ***
267:
1.147 brouard 268: Revision 1.146 2014/06/16 10:20:28 brouard
269: Summary: Merge
270: Author: Brouard
271:
272: Merge, before building revised version.
273:
1.146 brouard 274: Revision 1.145 2014/06/10 21:23:15 brouard
275: Summary: Debugging with valgrind
276: Author: Nicolas Brouard
277:
278: Lot of changes in order to output the results with some covariates
279: After the Edimburgh REVES conference 2014, it seems mandatory to
280: improve the code.
281: No more memory valgrind error but a lot has to be done in order to
282: continue the work of splitting the code into subroutines.
283: Also, decodemodel has been improved. Tricode is still not
284: optimal. nbcode should be improved. Documentation has been added in
285: the source code.
286:
1.144 brouard 287: Revision 1.143 2014/01/26 09:45:38 brouard
288: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
289:
290: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
291: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
292:
1.143 brouard 293: Revision 1.142 2014/01/26 03:57:36 brouard
294: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
295:
296: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
297:
1.142 brouard 298: Revision 1.141 2014/01/26 02:42:01 brouard
299: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
300:
1.141 brouard 301: Revision 1.140 2011/09/02 10:37:54 brouard
302: Summary: times.h is ok with mingw32 now.
303:
1.140 brouard 304: Revision 1.139 2010/06/14 07:50:17 brouard
305: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
306: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
307:
1.139 brouard 308: Revision 1.138 2010/04/30 18:19:40 brouard
309: *** empty log message ***
310:
1.138 brouard 311: Revision 1.137 2010/04/29 18:11:38 brouard
312: (Module): Checking covariates for more complex models
313: than V1+V2. A lot of change to be done. Unstable.
314:
1.137 brouard 315: Revision 1.136 2010/04/26 20:30:53 brouard
316: (Module): merging some libgsl code. Fixing computation
317: of likelione (using inter/intrapolation if mle = 0) in order to
318: get same likelihood as if mle=1.
319: Some cleaning of code and comments added.
320:
1.136 brouard 321: Revision 1.135 2009/10/29 15:33:14 brouard
322: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
323:
1.135 brouard 324: Revision 1.134 2009/10/29 13:18:53 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.134 brouard 327: Revision 1.133 2009/07/06 10:21:25 brouard
328: just nforces
329:
1.133 brouard 330: Revision 1.132 2009/07/06 08:22:05 brouard
331: Many tings
332:
1.132 brouard 333: Revision 1.131 2009/06/20 16:22:47 brouard
334: Some dimensions resccaled
335:
1.131 brouard 336: Revision 1.130 2009/05/26 06:44:34 brouard
337: (Module): Max Covariate is now set to 20 instead of 8. A
338: lot of cleaning with variables initialized to 0. Trying to make
339: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
340:
1.130 brouard 341: Revision 1.129 2007/08/31 13:49:27 lievre
342: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
343:
1.129 lievre 344: Revision 1.128 2006/06/30 13:02:05 brouard
345: (Module): Clarifications on computing e.j
346:
1.128 brouard 347: Revision 1.127 2006/04/28 18:11:50 brouard
348: (Module): Yes the sum of survivors was wrong since
349: imach-114 because nhstepm was no more computed in the age
350: loop. Now we define nhstepma in the age loop.
351: (Module): In order to speed up (in case of numerous covariates) we
352: compute health expectancies (without variances) in a first step
353: and then all the health expectancies with variances or standard
354: deviation (needs data from the Hessian matrices) which slows the
355: computation.
356: In the future we should be able to stop the program is only health
357: expectancies and graph are needed without standard deviations.
358:
1.127 brouard 359: Revision 1.126 2006/04/28 17:23:28 brouard
360: (Module): Yes the sum of survivors was wrong since
361: imach-114 because nhstepm was no more computed in the age
362: loop. Now we define nhstepma in the age loop.
363: Version 0.98h
364:
1.126 brouard 365: Revision 1.125 2006/04/04 15:20:31 lievre
366: Errors in calculation of health expectancies. Age was not initialized.
367: Forecasting file added.
368:
369: Revision 1.124 2006/03/22 17:13:53 lievre
370: Parameters are printed with %lf instead of %f (more numbers after the comma).
371: The log-likelihood is printed in the log file
372:
373: Revision 1.123 2006/03/20 10:52:43 brouard
374: * imach.c (Module): <title> changed, corresponds to .htm file
375: name. <head> headers where missing.
376:
377: * imach.c (Module): Weights can have a decimal point as for
378: English (a comma might work with a correct LC_NUMERIC environment,
379: otherwise the weight is truncated).
380: Modification of warning when the covariates values are not 0 or
381: 1.
382: Version 0.98g
383:
384: Revision 1.122 2006/03/20 09:45:41 brouard
385: (Module): Weights can have a decimal point as for
386: English (a comma might work with a correct LC_NUMERIC environment,
387: otherwise the weight is truncated).
388: Modification of warning when the covariates values are not 0 or
389: 1.
390: Version 0.98g
391:
392: Revision 1.121 2006/03/16 17:45:01 lievre
393: * imach.c (Module): Comments concerning covariates added
394:
395: * imach.c (Module): refinements in the computation of lli if
396: status=-2 in order to have more reliable computation if stepm is
397: not 1 month. Version 0.98f
398:
399: Revision 1.120 2006/03/16 15:10:38 lievre
400: (Module): refinements in the computation of lli if
401: status=-2 in order to have more reliable computation if stepm is
402: not 1 month. Version 0.98f
403:
404: Revision 1.119 2006/03/15 17:42:26 brouard
405: (Module): Bug if status = -2, the loglikelihood was
406: computed as likelihood omitting the logarithm. Version O.98e
407:
408: Revision 1.118 2006/03/14 18:20:07 brouard
409: (Module): varevsij Comments added explaining the second
410: table of variances if popbased=1 .
411: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
412: (Module): Function pstamp added
413: (Module): Version 0.98d
414:
415: Revision 1.117 2006/03/14 17:16:22 brouard
416: (Module): varevsij Comments added explaining the second
417: table of variances if popbased=1 .
418: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
419: (Module): Function pstamp added
420: (Module): Version 0.98d
421:
422: Revision 1.116 2006/03/06 10:29:27 brouard
423: (Module): Variance-covariance wrong links and
424: varian-covariance of ej. is needed (Saito).
425:
426: Revision 1.115 2006/02/27 12:17:45 brouard
427: (Module): One freematrix added in mlikeli! 0.98c
428:
429: Revision 1.114 2006/02/26 12:57:58 brouard
430: (Module): Some improvements in processing parameter
431: filename with strsep.
432:
433: Revision 1.113 2006/02/24 14:20:24 brouard
434: (Module): Memory leaks checks with valgrind and:
435: datafile was not closed, some imatrix were not freed and on matrix
436: allocation too.
437:
438: Revision 1.112 2006/01/30 09:55:26 brouard
439: (Module): Back to gnuplot.exe instead of wgnuplot.exe
440:
441: Revision 1.111 2006/01/25 20:38:18 brouard
442: (Module): Lots of cleaning and bugs added (Gompertz)
443: (Module): Comments can be added in data file. Missing date values
444: can be a simple dot '.'.
445:
446: Revision 1.110 2006/01/25 00:51:50 brouard
447: (Module): Lots of cleaning and bugs added (Gompertz)
448:
449: Revision 1.109 2006/01/24 19:37:15 brouard
450: (Module): Comments (lines starting with a #) are allowed in data.
451:
452: Revision 1.108 2006/01/19 18:05:42 lievre
453: Gnuplot problem appeared...
454: To be fixed
455:
456: Revision 1.107 2006/01/19 16:20:37 brouard
457: Test existence of gnuplot in imach path
458:
459: Revision 1.106 2006/01/19 13:24:36 brouard
460: Some cleaning and links added in html output
461:
462: Revision 1.105 2006/01/05 20:23:19 lievre
463: *** empty log message ***
464:
465: Revision 1.104 2005/09/30 16:11:43 lievre
466: (Module): sump fixed, loop imx fixed, and simplifications.
467: (Module): If the status is missing at the last wave but we know
468: that the person is alive, then we can code his/her status as -2
469: (instead of missing=-1 in earlier versions) and his/her
470: contributions to the likelihood is 1 - Prob of dying from last
471: health status (= 1-p13= p11+p12 in the easiest case of somebody in
472: the healthy state at last known wave). Version is 0.98
473:
474: Revision 1.103 2005/09/30 15:54:49 lievre
475: (Module): sump fixed, loop imx fixed, and simplifications.
476:
477: Revision 1.102 2004/09/15 17:31:30 brouard
478: Add the possibility to read data file including tab characters.
479:
480: Revision 1.101 2004/09/15 10:38:38 brouard
481: Fix on curr_time
482:
483: Revision 1.100 2004/07/12 18:29:06 brouard
484: Add version for Mac OS X. Just define UNIX in Makefile
485:
486: Revision 1.99 2004/06/05 08:57:40 brouard
487: *** empty log message ***
488:
489: Revision 1.98 2004/05/16 15:05:56 brouard
490: New version 0.97 . First attempt to estimate force of mortality
491: directly from the data i.e. without the need of knowing the health
492: state at each age, but using a Gompertz model: log u =a + b*age .
493: This is the basic analysis of mortality and should be done before any
494: other analysis, in order to test if the mortality estimated from the
495: cross-longitudinal survey is different from the mortality estimated
496: from other sources like vital statistic data.
497:
498: The same imach parameter file can be used but the option for mle should be -3.
499:
1.133 brouard 500: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 501: former routines in order to include the new code within the former code.
502:
503: The output is very simple: only an estimate of the intercept and of
504: the slope with 95% confident intervals.
505:
506: Current limitations:
507: A) Even if you enter covariates, i.e. with the
508: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
509: B) There is no computation of Life Expectancy nor Life Table.
510:
511: Revision 1.97 2004/02/20 13:25:42 lievre
512: Version 0.96d. Population forecasting command line is (temporarily)
513: suppressed.
514:
515: Revision 1.96 2003/07/15 15:38:55 brouard
516: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
517: rewritten within the same printf. Workaround: many printfs.
518:
519: Revision 1.95 2003/07/08 07:54:34 brouard
520: * imach.c (Repository):
521: (Repository): Using imachwizard code to output a more meaningful covariance
522: matrix (cov(a12,c31) instead of numbers.
523:
524: Revision 1.94 2003/06/27 13:00:02 brouard
525: Just cleaning
526:
527: Revision 1.93 2003/06/25 16:33:55 brouard
528: (Module): On windows (cygwin) function asctime_r doesn't
529: exist so I changed back to asctime which exists.
530: (Module): Version 0.96b
531:
532: Revision 1.92 2003/06/25 16:30:45 brouard
533: (Module): On windows (cygwin) function asctime_r doesn't
534: exist so I changed back to asctime which exists.
535:
536: Revision 1.91 2003/06/25 15:30:29 brouard
537: * imach.c (Repository): Duplicated warning errors corrected.
538: (Repository): Elapsed time after each iteration is now output. It
539: helps to forecast when convergence will be reached. Elapsed time
540: is stamped in powell. We created a new html file for the graphs
541: concerning matrix of covariance. It has extension -cov.htm.
542:
543: Revision 1.90 2003/06/24 12:34:15 brouard
544: (Module): Some bugs corrected for windows. Also, when
545: mle=-1 a template is output in file "or"mypar.txt with the design
546: of the covariance matrix to be input.
547:
548: Revision 1.89 2003/06/24 12:30:52 brouard
549: (Module): Some bugs corrected for windows. Also, when
550: mle=-1 a template is output in file "or"mypar.txt with the design
551: of the covariance matrix to be input.
552:
553: Revision 1.88 2003/06/23 17:54:56 brouard
554: * 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.
555:
556: Revision 1.87 2003/06/18 12:26:01 brouard
557: Version 0.96
558:
559: Revision 1.86 2003/06/17 20:04:08 brouard
560: (Module): Change position of html and gnuplot routines and added
561: routine fileappend.
562:
563: Revision 1.85 2003/06/17 13:12:43 brouard
564: * imach.c (Repository): Check when date of death was earlier that
565: current date of interview. It may happen when the death was just
566: prior to the death. In this case, dh was negative and likelihood
567: was wrong (infinity). We still send an "Error" but patch by
568: assuming that the date of death was just one stepm after the
569: interview.
570: (Repository): Because some people have very long ID (first column)
571: we changed int to long in num[] and we added a new lvector for
572: memory allocation. But we also truncated to 8 characters (left
573: truncation)
574: (Repository): No more line truncation errors.
575:
576: Revision 1.84 2003/06/13 21:44:43 brouard
577: * imach.c (Repository): Replace "freqsummary" at a correct
578: place. It differs from routine "prevalence" which may be called
579: many times. Probs is memory consuming and must be used with
580: parcimony.
581: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
582:
583: Revision 1.83 2003/06/10 13:39:11 lievre
584: *** empty log message ***
585:
586: Revision 1.82 2003/06/05 15:57:20 brouard
587: Add log in imach.c and fullversion number is now printed.
588:
589: */
590: /*
591: Interpolated Markov Chain
592:
593: Short summary of the programme:
594:
595: This program computes Healthy Life Expectancies from
596: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
597: first survey ("cross") where individuals from different ages are
598: interviewed on their health status or degree of disability (in the
599: case of a health survey which is our main interest) -2- at least a
600: second wave of interviews ("longitudinal") which measure each change
601: (if any) in individual health status. Health expectancies are
602: computed from the time spent in each health state according to a
603: model. More health states you consider, more time is necessary to reach the
604: Maximum Likelihood of the parameters involved in the model. The
605: simplest model is the multinomial logistic model where pij is the
606: probability to be observed in state j at the second wave
607: conditional to be observed in state i at the first wave. Therefore
608: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
609: 'age' is age and 'sex' is a covariate. If you want to have a more
610: complex model than "constant and age", you should modify the program
611: where the markup *Covariates have to be included here again* invites
612: you to do it. More covariates you add, slower the
613: convergence.
614:
615: The advantage of this computer programme, compared to a simple
616: multinomial logistic model, is clear when the delay between waves is not
617: identical for each individual. Also, if a individual missed an
618: intermediate interview, the information is lost, but taken into
619: account using an interpolation or extrapolation.
620:
621: hPijx is the probability to be observed in state i at age x+h
622: conditional to the observed state i at age x. The delay 'h' can be
623: split into an exact number (nh*stepm) of unobserved intermediate
624: states. This elementary transition (by month, quarter,
625: semester or year) is modelled as a multinomial logistic. The hPx
626: matrix is simply the matrix product of nh*stepm elementary matrices
627: and the contribution of each individual to the likelihood is simply
628: hPijx.
629:
630: Also this programme outputs the covariance matrix of the parameters but also
631: of the life expectancies. It also computes the period (stable) prevalence.
632:
1.133 brouard 633: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
634: Institut national d'études démographiques, Paris.
1.126 brouard 635: This software have been partly granted by Euro-REVES, a concerted action
636: from the European Union.
637: It is copyrighted identically to a GNU software product, ie programme and
638: software can be distributed freely for non commercial use. Latest version
639: can be accessed at http://euroreves.ined.fr/imach .
640:
641: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
642: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
643:
644: **********************************************************************/
645: /*
646: main
647: read parameterfile
648: read datafile
649: concatwav
650: freqsummary
651: if (mle >= 1)
652: mlikeli
653: print results files
654: if mle==1
655: computes hessian
656: read end of parameter file: agemin, agemax, bage, fage, estepm
657: begin-prev-date,...
658: open gnuplot file
659: open html file
1.145 brouard 660: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
661: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
662: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
663: freexexit2 possible for memory heap.
664:
665: h Pij x | pij_nom ficrestpij
666: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
667: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
668: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
669:
670: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
671: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
672: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
673: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
674: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
675:
1.126 brouard 676: forecasting if prevfcast==1 prevforecast call prevalence()
677: health expectancies
678: Variance-covariance of DFLE
679: prevalence()
680: movingaverage()
681: varevsij()
682: if popbased==1 varevsij(,popbased)
683: total life expectancies
684: Variance of period (stable) prevalence
685: end
686: */
687:
1.187 brouard 688: /* #define DEBUG */
689: /* #define DEBUGBRENT */
1.203 brouard 690: /* #define DEBUGLINMIN */
691: /* #define DEBUGHESS */
692: #define DEBUGHESSIJ
693: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165 brouard 694: #define POWELL /* Instead of NLOPT */
1.192 brouard 695: #define POWELLF1F3 /* Skip test */
1.186 brouard 696: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
697: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126 brouard 698:
699: #include <math.h>
700: #include <stdio.h>
701: #include <stdlib.h>
702: #include <string.h>
1.159 brouard 703:
704: #ifdef _WIN32
705: #include <io.h>
1.172 brouard 706: #include <windows.h>
707: #include <tchar.h>
1.159 brouard 708: #else
1.126 brouard 709: #include <unistd.h>
1.159 brouard 710: #endif
1.126 brouard 711:
712: #include <limits.h>
713: #include <sys/types.h>
1.171 brouard 714:
715: #if defined(__GNUC__)
716: #include <sys/utsname.h> /* Doesn't work on Windows */
717: #endif
718:
1.126 brouard 719: #include <sys/stat.h>
720: #include <errno.h>
1.159 brouard 721: /* extern int errno; */
1.126 brouard 722:
1.157 brouard 723: /* #ifdef LINUX */
724: /* #include <time.h> */
725: /* #include "timeval.h" */
726: /* #else */
727: /* #include <sys/time.h> */
728: /* #endif */
729:
1.126 brouard 730: #include <time.h>
731:
1.136 brouard 732: #ifdef GSL
733: #include <gsl/gsl_errno.h>
734: #include <gsl/gsl_multimin.h>
735: #endif
736:
1.167 brouard 737:
1.162 brouard 738: #ifdef NLOPT
739: #include <nlopt.h>
740: typedef struct {
741: double (* function)(double [] );
742: } myfunc_data ;
743: #endif
744:
1.126 brouard 745: /* #include <libintl.h> */
746: /* #define _(String) gettext (String) */
747:
1.141 brouard 748: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 749:
750: #define GNUPLOTPROGRAM "gnuplot"
751: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
752: #define FILENAMELENGTH 132
753:
754: #define GLOCK_ERROR_NOPATH -1 /* empty path */
755: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
756:
1.144 brouard 757: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
758: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 759:
760: #define NINTERVMAX 8
1.144 brouard 761: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
762: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
763: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197 brouard 764: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.211 brouard 765: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
766: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
1.126 brouard 767: #define MAXN 20000
1.144 brouard 768: #define YEARM 12. /**< Number of months per year */
1.126 brouard 769: #define AGESUP 130
770: #define AGEBASE 40
1.194 brouard 771: #define AGEOVERFLOW 1.e20
1.164 brouard 772: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 773: #ifdef _WIN32
774: #define DIRSEPARATOR '\\'
775: #define CHARSEPARATOR "\\"
776: #define ODIRSEPARATOR '/'
777: #else
1.126 brouard 778: #define DIRSEPARATOR '/'
779: #define CHARSEPARATOR "/"
780: #define ODIRSEPARATOR '\\'
781: #endif
782:
1.212 ! brouard 783: /* $Id: imach.c,v 1.211 2015/11/21 12:41:11 brouard Exp $ */
1.126 brouard 784: /* $State: Exp $ */
1.196 brouard 785: #include "version.h"
786: char version[]=__IMACH_VERSION__;
1.204 brouard 787: 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.212 ! brouard 788: char fullversion[]="$Revision: 1.211 $ $Date: 2015/11/21 12:41:11 $";
1.126 brouard 789: char strstart[80];
790: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 791: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.187 brouard 792: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145 brouard 793: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
794: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
795: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
796: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
797: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
798: int cptcovprodnoage=0; /**< Number of covariate products without age */
799: int cptcoveff=0; /* Total number of covariates to vary for printing results */
800: int cptcov=0; /* Working variable */
1.126 brouard 801: int npar=NPARMAX;
802: int nlstate=2; /* Number of live states */
803: int ndeath=1; /* Number of dead states */
1.130 brouard 804: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 805: int popbased=0;
806:
807: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 808: int maxwav=0; /* Maxim number of waves */
809: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
810: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
811: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 812: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 813: int mle=1, weightopt=0;
1.126 brouard 814: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
815: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
816: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
817: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 818: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 819: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 820: double **matprod2(); /* test */
1.126 brouard 821: double **oldm, **newm, **savm; /* Working pointers to matrices */
822: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 823: /*FILE *fic ; */ /* Used in readdata only */
824: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 825: FILE *ficlog, *ficrespow;
1.130 brouard 826: int globpr=0; /* Global variable for printing or not */
1.126 brouard 827: double fretone; /* Only one call to likelihood */
1.130 brouard 828: long ipmx=0; /* Number of contributions */
1.126 brouard 829: double sw; /* Sum of weights */
830: char filerespow[FILENAMELENGTH];
831: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
832: FILE *ficresilk;
833: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
834: FILE *ficresprobmorprev;
835: FILE *fichtm, *fichtmcov; /* Html File */
836: FILE *ficreseij;
837: char filerese[FILENAMELENGTH];
838: FILE *ficresstdeij;
839: char fileresstde[FILENAMELENGTH];
840: FILE *ficrescveij;
841: char filerescve[FILENAMELENGTH];
842: FILE *ficresvij;
843: char fileresv[FILENAMELENGTH];
844: FILE *ficresvpl;
845: char fileresvpl[FILENAMELENGTH];
846: char title[MAXLINE];
847: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
848: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
849: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
850: char command[FILENAMELENGTH];
851: int outcmd=0;
852:
853: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202 brouard 854: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126 brouard 855: char filelog[FILENAMELENGTH]; /* Log file */
856: char filerest[FILENAMELENGTH];
857: char fileregp[FILENAMELENGTH];
858: char popfile[FILENAMELENGTH];
859:
860: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
861:
1.157 brouard 862: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
863: /* struct timezone tzp; */
864: /* extern int gettimeofday(); */
865: struct tm tml, *gmtime(), *localtime();
866:
867: extern time_t time();
868:
869: struct tm start_time, end_time, curr_time, last_time, forecast_time;
870: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
871: struct tm tm;
872:
1.126 brouard 873: char strcurr[80], strfor[80];
874:
875: char *endptr;
876: long lval;
877: double dval;
878:
879: #define NR_END 1
880: #define FREE_ARG char*
881: #define FTOL 1.0e-10
882:
883: #define NRANSI
884: #define ITMAX 200
885:
886: #define TOL 2.0e-4
887:
888: #define CGOLD 0.3819660
889: #define ZEPS 1.0e-10
890: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
891:
892: #define GOLD 1.618034
893: #define GLIMIT 100.0
894: #define TINY 1.0e-20
895:
896: static double maxarg1,maxarg2;
897: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
898: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
899:
900: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
901: #define rint(a) floor(a+0.5)
1.166 brouard 902: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183 brouard 903: #define mytinydouble 1.0e-16
1.166 brouard 904: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
905: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
906: /* static double dsqrarg; */
907: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 908: static double sqrarg;
909: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
910: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
911: int agegomp= AGEGOMP;
912:
913: int imx;
914: int stepm=1;
915: /* Stepm, step in month: minimum step interpolation*/
916:
917: int estepm;
918: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
919:
920: int m,nb;
921: long *num;
1.197 brouard 922: int firstpass=0, lastpass=4,*cod, *cens;
1.192 brouard 923: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
924: covariate for which somebody answered excluding
925: undefined. Usually 2: 0 and 1. */
926: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
927: covariate for which somebody answered including
928: undefined. Usually 3: -1, 0 and 1. */
1.126 brouard 929: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
930: double **pmmij, ***probs;
931: double *ageexmed,*agecens;
932: double dateintmean=0;
933:
934: double *weight;
935: int **s; /* Status */
1.141 brouard 936: double *agedc;
1.145 brouard 937: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 938: * covar=matrix(0,NCOVMAX,1,n);
1.187 brouard 939: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141 brouard 940: double idx;
941: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197 brouard 942: int *Tage;
1.145 brouard 943: int *Ndum; /** Freq of modality (tricode */
1.200 brouard 944: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141 brouard 945: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 946: double *lsurv, *lpop, *tpop;
947:
1.143 brouard 948: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
949: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 950:
951: /**************** split *************************/
952: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
953: {
954: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
955: the name of the file (name), its extension only (ext) and its first part of the name (finame)
956: */
957: char *ss; /* pointer */
1.186 brouard 958: int l1=0, l2=0; /* length counters */
1.126 brouard 959:
960: l1 = strlen(path ); /* length of path */
961: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
962: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
963: if ( ss == NULL ) { /* no directory, so determine current directory */
964: strcpy( name, path ); /* we got the fullname name because no directory */
965: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
966: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
967: /* get current working directory */
968: /* extern char* getcwd ( char *buf , int len);*/
1.184 brouard 969: #ifdef WIN32
970: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
971: #else
972: if (getcwd(dirc, FILENAME_MAX) == NULL) {
973: #endif
1.126 brouard 974: return( GLOCK_ERROR_GETCWD );
975: }
976: /* got dirc from getcwd*/
977: printf(" DIRC = %s \n",dirc);
1.205 brouard 978: } else { /* strip directory from path */
1.126 brouard 979: ss++; /* after this, the filename */
980: l2 = strlen( ss ); /* length of filename */
981: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
982: strcpy( name, ss ); /* save file name */
983: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1.186 brouard 984: dirc[l1-l2] = '\0'; /* add zero */
1.126 brouard 985: printf(" DIRC2 = %s \n",dirc);
986: }
987: /* We add a separator at the end of dirc if not exists */
988: l1 = strlen( dirc ); /* length of directory */
989: if( dirc[l1-1] != DIRSEPARATOR ){
990: dirc[l1] = DIRSEPARATOR;
991: dirc[l1+1] = 0;
992: printf(" DIRC3 = %s \n",dirc);
993: }
994: ss = strrchr( name, '.' ); /* find last / */
995: if (ss >0){
996: ss++;
997: strcpy(ext,ss); /* save extension */
998: l1= strlen( name);
999: l2= strlen(ss)+1;
1000: strncpy( finame, name, l1-l2);
1001: finame[l1-l2]= 0;
1002: }
1003:
1004: return( 0 ); /* we're done */
1005: }
1006:
1007:
1008: /******************************************/
1009:
1010: void replace_back_to_slash(char *s, char*t)
1011: {
1012: int i;
1013: int lg=0;
1014: i=0;
1015: lg=strlen(t);
1016: for(i=0; i<= lg; i++) {
1017: (s[i] = t[i]);
1018: if (t[i]== '\\') s[i]='/';
1019: }
1020: }
1021:
1.132 brouard 1022: char *trimbb(char *out, char *in)
1.137 brouard 1023: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 1024: char *s;
1025: s=out;
1026: while (*in != '\0'){
1.137 brouard 1027: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 1028: in++;
1029: }
1030: *out++ = *in++;
1031: }
1032: *out='\0';
1033: return s;
1034: }
1035:
1.187 brouard 1036: /* char *substrchaine(char *out, char *in, char *chain) */
1037: /* { */
1038: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1039: /* char *s, *t; */
1040: /* t=in;s=out; */
1041: /* while ((*in != *chain) && (*in != '\0')){ */
1042: /* *out++ = *in++; */
1043: /* } */
1044:
1045: /* /\* *in matches *chain *\/ */
1046: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1047: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1048: /* } */
1049: /* in--; chain--; */
1050: /* while ( (*in != '\0')){ */
1051: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1052: /* *out++ = *in++; */
1053: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1054: /* } */
1055: /* *out='\0'; */
1056: /* out=s; */
1057: /* return out; */
1058: /* } */
1059: char *substrchaine(char *out, char *in, char *chain)
1060: {
1061: /* Substract chain 'chain' from 'in', return and output 'out' */
1062: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1063:
1064: char *strloc;
1065:
1066: strcpy (out, in);
1067: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1068: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1069: if(strloc != NULL){
1070: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1071: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1072: /* strcpy (strloc, strloc +strlen(chain));*/
1073: }
1074: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1075: return out;
1076: }
1077:
1078:
1.145 brouard 1079: char *cutl(char *blocc, char *alocc, char *in, char occ)
1080: {
1.187 brouard 1081: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1.145 brouard 1082: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187 brouard 1083: gives blocc="abcdef" and alocc="ghi2j".
1.145 brouard 1084: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1085: */
1.160 brouard 1086: char *s, *t;
1.145 brouard 1087: t=in;s=in;
1088: while ((*in != occ) && (*in != '\0')){
1089: *alocc++ = *in++;
1090: }
1091: if( *in == occ){
1092: *(alocc)='\0';
1093: s=++in;
1094: }
1095:
1096: if (s == t) {/* occ not found */
1097: *(alocc-(in-s))='\0';
1098: in=s;
1099: }
1100: while ( *in != '\0'){
1101: *blocc++ = *in++;
1102: }
1103:
1104: *blocc='\0';
1105: return t;
1106: }
1.137 brouard 1107: char *cutv(char *blocc, char *alocc, char *in, char occ)
1108: {
1.187 brouard 1109: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1.137 brouard 1110: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1111: gives blocc="abcdef2ghi" and alocc="j".
1112: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1113: */
1114: char *s, *t;
1115: t=in;s=in;
1116: while (*in != '\0'){
1117: while( *in == occ){
1118: *blocc++ = *in++;
1119: s=in;
1120: }
1121: *blocc++ = *in++;
1122: }
1123: if (s == t) /* occ not found */
1124: *(blocc-(in-s))='\0';
1125: else
1126: *(blocc-(in-s)-1)='\0';
1127: in=s;
1128: while ( *in != '\0'){
1129: *alocc++ = *in++;
1130: }
1131:
1132: *alocc='\0';
1133: return s;
1134: }
1135:
1.126 brouard 1136: int nbocc(char *s, char occ)
1137: {
1138: int i,j=0;
1139: int lg=20;
1140: i=0;
1141: lg=strlen(s);
1142: for(i=0; i<= lg; i++) {
1143: if (s[i] == occ ) j++;
1144: }
1145: return j;
1146: }
1147:
1.137 brouard 1148: /* void cutv(char *u,char *v, char*t, char occ) */
1149: /* { */
1150: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1151: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1152: /* gives u="abcdef2ghi" and v="j" *\/ */
1153: /* int i,lg,j,p=0; */
1154: /* i=0; */
1155: /* lg=strlen(t); */
1156: /* for(j=0; j<=lg-1; j++) { */
1157: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1158: /* } */
1.126 brouard 1159:
1.137 brouard 1160: /* for(j=0; j<p; j++) { */
1161: /* (u[j] = t[j]); */
1162: /* } */
1163: /* u[p]='\0'; */
1.126 brouard 1164:
1.137 brouard 1165: /* for(j=0; j<= lg; j++) { */
1166: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1167: /* } */
1168: /* } */
1.126 brouard 1169:
1.160 brouard 1170: #ifdef _WIN32
1171: char * strsep(char **pp, const char *delim)
1172: {
1173: char *p, *q;
1174:
1175: if ((p = *pp) == NULL)
1176: return 0;
1177: if ((q = strpbrk (p, delim)) != NULL)
1178: {
1179: *pp = q + 1;
1180: *q = '\0';
1181: }
1182: else
1183: *pp = 0;
1184: return p;
1185: }
1186: #endif
1187:
1.126 brouard 1188: /********************** nrerror ********************/
1189:
1190: void nrerror(char error_text[])
1191: {
1192: fprintf(stderr,"ERREUR ...\n");
1193: fprintf(stderr,"%s\n",error_text);
1194: exit(EXIT_FAILURE);
1195: }
1196: /*********************** vector *******************/
1197: double *vector(int nl, int nh)
1198: {
1199: double *v;
1200: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1201: if (!v) nrerror("allocation failure in vector");
1202: return v-nl+NR_END;
1203: }
1204:
1205: /************************ free vector ******************/
1206: void free_vector(double*v, int nl, int nh)
1207: {
1208: free((FREE_ARG)(v+nl-NR_END));
1209: }
1210:
1211: /************************ivector *******************************/
1212: int *ivector(long nl,long nh)
1213: {
1214: int *v;
1215: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1216: if (!v) nrerror("allocation failure in ivector");
1217: return v-nl+NR_END;
1218: }
1219:
1220: /******************free ivector **************************/
1221: void free_ivector(int *v, long nl, long nh)
1222: {
1223: free((FREE_ARG)(v+nl-NR_END));
1224: }
1225:
1226: /************************lvector *******************************/
1227: long *lvector(long nl,long nh)
1228: {
1229: long *v;
1230: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1231: if (!v) nrerror("allocation failure in ivector");
1232: return v-nl+NR_END;
1233: }
1234:
1235: /******************free lvector **************************/
1236: void free_lvector(long *v, long nl, long nh)
1237: {
1238: free((FREE_ARG)(v+nl-NR_END));
1239: }
1240:
1241: /******************* imatrix *******************************/
1242: int **imatrix(long nrl, long nrh, long ncl, long nch)
1243: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1244: {
1245: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1246: int **m;
1247:
1248: /* allocate pointers to rows */
1249: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1250: if (!m) nrerror("allocation failure 1 in matrix()");
1251: m += NR_END;
1252: m -= nrl;
1253:
1254:
1255: /* allocate rows and set pointers to them */
1256: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1257: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1258: m[nrl] += NR_END;
1259: m[nrl] -= ncl;
1260:
1261: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1262:
1263: /* return pointer to array of pointers to rows */
1264: return m;
1265: }
1266:
1267: /****************** free_imatrix *************************/
1268: void free_imatrix(m,nrl,nrh,ncl,nch)
1269: int **m;
1270: long nch,ncl,nrh,nrl;
1271: /* free an int matrix allocated by imatrix() */
1272: {
1273: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1274: free((FREE_ARG) (m+nrl-NR_END));
1275: }
1276:
1277: /******************* matrix *******************************/
1278: double **matrix(long nrl, long nrh, long ncl, long nch)
1279: {
1280: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1281: double **m;
1282:
1283: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1284: if (!m) nrerror("allocation failure 1 in matrix()");
1285: m += NR_END;
1286: m -= nrl;
1287:
1288: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1289: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1290: m[nrl] += NR_END;
1291: m[nrl] -= ncl;
1292:
1293: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1294: return m;
1.145 brouard 1295: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1296: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1297: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1298: */
1299: }
1300:
1301: /*************************free matrix ************************/
1302: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1303: {
1304: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1305: free((FREE_ARG)(m+nrl-NR_END));
1306: }
1307:
1308: /******************* ma3x *******************************/
1309: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1310: {
1311: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1312: double ***m;
1313:
1314: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1315: if (!m) nrerror("allocation failure 1 in matrix()");
1316: m += NR_END;
1317: m -= nrl;
1318:
1319: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1320: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1321: m[nrl] += NR_END;
1322: m[nrl] -= ncl;
1323:
1324: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1325:
1326: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1327: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1328: m[nrl][ncl] += NR_END;
1329: m[nrl][ncl] -= nll;
1330: for (j=ncl+1; j<=nch; j++)
1331: m[nrl][j]=m[nrl][j-1]+nlay;
1332:
1333: for (i=nrl+1; i<=nrh; i++) {
1334: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1335: for (j=ncl+1; j<=nch; j++)
1336: m[i][j]=m[i][j-1]+nlay;
1337: }
1338: return m;
1339: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1340: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1341: */
1342: }
1343:
1344: /*************************free ma3x ************************/
1345: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1346: {
1347: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1348: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1349: free((FREE_ARG)(m+nrl-NR_END));
1350: }
1351:
1352: /*************** function subdirf ***********/
1353: char *subdirf(char fileres[])
1354: {
1355: /* Caution optionfilefiname is hidden */
1356: strcpy(tmpout,optionfilefiname);
1357: strcat(tmpout,"/"); /* Add to the right */
1358: strcat(tmpout,fileres);
1359: return tmpout;
1360: }
1361:
1362: /*************** function subdirf2 ***********/
1363: char *subdirf2(char fileres[], char *preop)
1364: {
1365:
1366: /* Caution optionfilefiname is hidden */
1367: strcpy(tmpout,optionfilefiname);
1368: strcat(tmpout,"/");
1369: strcat(tmpout,preop);
1370: strcat(tmpout,fileres);
1371: return tmpout;
1372: }
1373:
1374: /*************** function subdirf3 ***********/
1375: char *subdirf3(char fileres[], char *preop, char *preop2)
1376: {
1377:
1378: /* Caution optionfilefiname is hidden */
1379: strcpy(tmpout,optionfilefiname);
1380: strcat(tmpout,"/");
1381: strcat(tmpout,preop);
1382: strcat(tmpout,preop2);
1383: strcat(tmpout,fileres);
1384: return tmpout;
1385: }
1386:
1.162 brouard 1387: char *asc_diff_time(long time_sec, char ascdiff[])
1388: {
1389: long sec_left, days, hours, minutes;
1390: days = (time_sec) / (60*60*24);
1391: sec_left = (time_sec) % (60*60*24);
1392: hours = (sec_left) / (60*60) ;
1393: sec_left = (sec_left) %(60*60);
1394: minutes = (sec_left) /60;
1395: sec_left = (sec_left) % (60);
1396: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1397: return ascdiff;
1398: }
1399:
1.126 brouard 1400: /***************** f1dim *************************/
1401: extern int ncom;
1402: extern double *pcom,*xicom;
1403: extern double (*nrfunc)(double []);
1404:
1405: double f1dim(double x)
1406: {
1407: int j;
1408: double f;
1409: double *xt;
1410:
1411: xt=vector(1,ncom);
1412: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1413: f=(*nrfunc)(xt);
1414: free_vector(xt,1,ncom);
1415: return f;
1416: }
1417:
1418: /*****************brent *************************/
1419: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1.187 brouard 1420: {
1421: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1422: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1423: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1424: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1425: * returned function value.
1426: */
1.126 brouard 1427: int iter;
1428: double a,b,d,etemp;
1.159 brouard 1429: double fu=0,fv,fw,fx;
1.164 brouard 1430: double ftemp=0.;
1.126 brouard 1431: double p,q,r,tol1,tol2,u,v,w,x,xm;
1432: double e=0.0;
1433:
1434: a=(ax < cx ? ax : cx);
1435: b=(ax > cx ? ax : cx);
1436: x=w=v=bx;
1437: fw=fv=fx=(*f)(x);
1438: for (iter=1;iter<=ITMAX;iter++) {
1439: xm=0.5*(a+b);
1440: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1441: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1442: printf(".");fflush(stdout);
1443: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1444: #ifdef DEBUGBRENT
1.126 brouard 1445: 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);
1446: 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);
1447: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1448: #endif
1449: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1450: *xmin=x;
1451: return fx;
1452: }
1453: ftemp=fu;
1454: if (fabs(e) > tol1) {
1455: r=(x-w)*(fx-fv);
1456: q=(x-v)*(fx-fw);
1457: p=(x-v)*q-(x-w)*r;
1458: q=2.0*(q-r);
1459: if (q > 0.0) p = -p;
1460: q=fabs(q);
1461: etemp=e;
1462: e=d;
1463: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1464: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1465: else {
1466: d=p/q;
1467: u=x+d;
1468: if (u-a < tol2 || b-u < tol2)
1469: d=SIGN(tol1,xm-x);
1470: }
1471: } else {
1472: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1473: }
1474: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1475: fu=(*f)(u);
1476: if (fu <= fx) {
1477: if (u >= x) a=x; else b=x;
1478: SHFT(v,w,x,u)
1.183 brouard 1479: SHFT(fv,fw,fx,fu)
1480: } else {
1481: if (u < x) a=u; else b=u;
1482: if (fu <= fw || w == x) {
1483: v=w;
1484: w=u;
1485: fv=fw;
1486: fw=fu;
1487: } else if (fu <= fv || v == x || v == w) {
1488: v=u;
1489: fv=fu;
1490: }
1491: }
1.126 brouard 1492: }
1493: nrerror("Too many iterations in brent");
1494: *xmin=x;
1495: return fx;
1496: }
1497:
1498: /****************** mnbrak ***********************/
1499:
1500: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1501: double (*func)(double))
1.183 brouard 1502: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1503: the downhill direction (defined by the function as evaluated at the initial points) and returns
1504: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1505: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1506: */
1.126 brouard 1507: double ulim,u,r,q, dum;
1508: double fu;
1.187 brouard 1509:
1510: double scale=10.;
1511: int iterscale=0;
1512:
1513: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1514: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1515:
1516:
1517: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1518: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1519: /* *bx = *ax - (*ax - *bx)/scale; */
1520: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1521: /* } */
1522:
1.126 brouard 1523: if (*fb > *fa) {
1524: SHFT(dum,*ax,*bx,dum)
1.183 brouard 1525: SHFT(dum,*fb,*fa,dum)
1526: }
1.126 brouard 1527: *cx=(*bx)+GOLD*(*bx-*ax);
1528: *fc=(*func)(*cx);
1.183 brouard 1529: #ifdef DEBUG
1530: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1531: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1532: #endif
1533: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126 brouard 1534: r=(*bx-*ax)*(*fb-*fc);
1535: q=(*bx-*cx)*(*fb-*fa);
1536: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.183 brouard 1537: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1538: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1539: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126 brouard 1540: fu=(*func)(u);
1.163 brouard 1541: #ifdef DEBUG
1542: /* f(x)=A(x-u)**2+f(u) */
1543: double A, fparabu;
1544: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1545: fparabu= *fa - A*(*ax-u)*(*ax-u);
1546: 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);
1547: 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 1548: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1549: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1550: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1551: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163 brouard 1552: #endif
1.184 brouard 1553: #ifdef MNBRAKORIGINAL
1.183 brouard 1554: #else
1.191 brouard 1555: /* if (fu > *fc) { */
1556: /* #ifdef DEBUG */
1557: /* printf("mnbrak4 fu > fc \n"); */
1558: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1559: /* #endif */
1560: /* /\* 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 *\\/ *\/ */
1561: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1562: /* dum=u; /\* Shifting c and u *\/ */
1563: /* u = *cx; */
1564: /* *cx = dum; */
1565: /* dum = fu; */
1566: /* fu = *fc; */
1567: /* *fc =dum; */
1568: /* } else { /\* end *\/ */
1569: /* #ifdef DEBUG */
1570: /* printf("mnbrak3 fu < fc \n"); */
1571: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1572: /* #endif */
1573: /* dum=u; /\* Shifting c and u *\/ */
1574: /* u = *cx; */
1575: /* *cx = dum; */
1576: /* dum = fu; */
1577: /* fu = *fc; */
1578: /* *fc =dum; */
1579: /* } */
1.183 brouard 1580: #ifdef DEBUG
1.191 brouard 1581: printf("mnbrak34 fu < or >= fc \n");
1582: fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183 brouard 1583: #endif
1.191 brouard 1584: dum=u; /* Shifting c and u */
1585: u = *cx;
1586: *cx = dum;
1587: dum = fu;
1588: fu = *fc;
1589: *fc =dum;
1.183 brouard 1590: #endif
1.162 brouard 1591: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183 brouard 1592: #ifdef DEBUG
1593: printf("mnbrak2 u after c but before ulim\n");
1594: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1595: #endif
1.126 brouard 1596: fu=(*func)(u);
1597: if (fu < *fc) {
1.183 brouard 1598: #ifdef DEBUG
1599: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1600: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1601: #endif
1.126 brouard 1602: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1.183 brouard 1603: SHFT(*fb,*fc,fu,(*func)(u))
1604: }
1.162 brouard 1605: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183 brouard 1606: #ifdef DEBUG
1607: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1608: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1609: #endif
1.126 brouard 1610: u=ulim;
1611: fu=(*func)(u);
1.183 brouard 1612: } else { /* u could be left to b (if r > q parabola has a maximum) */
1613: #ifdef DEBUG
1614: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1615: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1616: #endif
1.126 brouard 1617: u=(*cx)+GOLD*(*cx-*bx);
1618: fu=(*func)(u);
1.183 brouard 1619: } /* end tests */
1.126 brouard 1620: SHFT(*ax,*bx,*cx,u)
1.183 brouard 1621: SHFT(*fa,*fb,*fc,fu)
1622: #ifdef DEBUG
1623: 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);
1624: 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);
1625: #endif
1626: } /* 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 1627: }
1628:
1629: /*************** linmin ************************/
1.162 brouard 1630: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1631: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1632: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1633: the value of func at the returned location p . This is actually all accomplished by calling the
1634: routines mnbrak and brent .*/
1.126 brouard 1635: int ncom;
1636: double *pcom,*xicom;
1637: double (*nrfunc)(double []);
1638:
1639: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1640: {
1641: double brent(double ax, double bx, double cx,
1642: double (*f)(double), double tol, double *xmin);
1643: double f1dim(double x);
1644: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1645: double *fc, double (*func)(double));
1646: int j;
1647: double xx,xmin,bx,ax;
1648: double fx,fb,fa;
1.187 brouard 1649:
1.203 brouard 1650: #ifdef LINMINORIGINAL
1651: #else
1652: double scale=10., axs, xxs; /* Scale added for infinity */
1653: #endif
1654:
1.126 brouard 1655: ncom=n;
1656: pcom=vector(1,n);
1657: xicom=vector(1,n);
1658: nrfunc=func;
1659: for (j=1;j<=n;j++) {
1660: pcom[j]=p[j];
1.202 brouard 1661: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126 brouard 1662: }
1.187 brouard 1663:
1.203 brouard 1664: #ifdef LINMINORIGINAL
1665: xx=1.;
1666: #else
1667: axs=0.0;
1668: xxs=1.;
1669: do{
1670: xx= xxs;
1671: #endif
1.187 brouard 1672: ax=0.;
1673: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1674: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1675: /* 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)) */
1676: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1677: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1678: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1679: /* 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 1680: #ifdef LINMINORIGINAL
1681: #else
1682: if (fx != fx){
1683: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1684: printf("|");
1685: fprintf(ficlog,"|");
1686: #ifdef DEBUGLINMIN
1687: 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);
1688: #endif
1689: }
1690: }while(fx != fx);
1691: #endif
1692:
1.191 brouard 1693: #ifdef DEBUGLINMIN
1694: 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 1695: 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 1696: #endif
1.187 brouard 1697: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1698: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1699: /* fmin = f(p[j] + xmin * xi[j]) */
1700: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1701: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126 brouard 1702: #ifdef DEBUG
1703: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1704: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1705: #endif
1.191 brouard 1706: #ifdef DEBUGLINMIN
1707: printf("linmin end ");
1.202 brouard 1708: fprintf(ficlog,"linmin end ");
1.191 brouard 1709: #endif
1.126 brouard 1710: for (j=1;j<=n;j++) {
1.203 brouard 1711: #ifdef LINMINORIGINAL
1712: xi[j] *= xmin;
1713: #else
1714: #ifdef DEBUGLINMIN
1715: if(xxs <1.0)
1716: printf(" before xi[%d]=%12.8f", j,xi[j]);
1717: #endif
1718: 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) */
1719: #ifdef DEBUGLINMIN
1720: if(xxs <1.0)
1721: 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 );
1722: #endif
1723: #endif
1.187 brouard 1724: p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126 brouard 1725: }
1.191 brouard 1726: #ifdef DEBUGLINMIN
1.203 brouard 1727: printf("\n");
1.191 brouard 1728: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202 brouard 1729: 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 1730: for (j=1;j<=n;j++) {
1.202 brouard 1731: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1732: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1733: if(j % ncovmodel == 0){
1.191 brouard 1734: printf("\n");
1.202 brouard 1735: fprintf(ficlog,"\n");
1736: }
1.191 brouard 1737: }
1.203 brouard 1738: #else
1.191 brouard 1739: #endif
1.126 brouard 1740: free_vector(xicom,1,n);
1741: free_vector(pcom,1,n);
1742: }
1743:
1744:
1745: /*************** powell ************************/
1.162 brouard 1746: /*
1747: Minimization of a function func of n variables. Input consists of an initial starting point
1748: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1749: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1750: such that failure to decrease by more than this amount on one iteration signals doneness. On
1751: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1752: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1753: */
1.126 brouard 1754: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1755: double (*func)(double []))
1756: {
1757: void linmin(double p[], double xi[], int n, double *fret,
1758: double (*func)(double []));
1759: int i,ibig,j;
1760: double del,t,*pt,*ptt,*xit;
1.181 brouard 1761: double directest;
1.126 brouard 1762: double fp,fptt;
1763: double *xits;
1764: int niterf, itmp;
1765:
1766: pt=vector(1,n);
1767: ptt=vector(1,n);
1768: xit=vector(1,n);
1769: xits=vector(1,n);
1770: *fret=(*func)(p);
1771: for (j=1;j<=n;j++) pt[j]=p[j];
1.202 brouard 1772: rcurr_time = time(NULL);
1.126 brouard 1773: for (*iter=1;;++(*iter)) {
1.187 brouard 1774: fp=(*fret); /* From former iteration or initial value */
1.126 brouard 1775: ibig=0;
1776: del=0.0;
1.157 brouard 1777: rlast_time=rcurr_time;
1778: /* (void) gettimeofday(&curr_time,&tzp); */
1779: rcurr_time = time(NULL);
1780: curr_time = *localtime(&rcurr_time);
1781: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1782: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1783: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192 brouard 1784: for (i=1;i<=n;i++) {
1.126 brouard 1785: printf(" %d %.12f",i, p[i]);
1786: fprintf(ficlog," %d %.12lf",i, p[i]);
1787: fprintf(ficrespow," %.12lf", p[i]);
1788: }
1789: printf("\n");
1790: fprintf(ficlog,"\n");
1791: fprintf(ficrespow,"\n");fflush(ficrespow);
1792: if(*iter <=3){
1.157 brouard 1793: tml = *localtime(&rcurr_time);
1794: strcpy(strcurr,asctime(&tml));
1795: rforecast_time=rcurr_time;
1.126 brouard 1796: itmp = strlen(strcurr);
1797: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1798: strcurr[itmp-1]='\0';
1.162 brouard 1799: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1800: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1801: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1802: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1803: forecast_time = *localtime(&rforecast_time);
1804: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1805: itmp = strlen(strfor);
1806: if(strfor[itmp-1]=='\n')
1807: strfor[itmp-1]='\0';
1.157 brouard 1808: 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);
1809: 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 1810: }
1811: }
1.187 brouard 1812: for (i=1;i<=n;i++) { /* For each direction i */
1813: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126 brouard 1814: fptt=(*fret);
1815: #ifdef DEBUG
1.203 brouard 1816: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1817: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1818: #endif
1.203 brouard 1819: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126 brouard 1820: fprintf(ficlog,"%d",i);fflush(ficlog);
1.188 brouard 1821: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1822: /* Outputs are fret(new point p) p is updated and xit rescaled */
1823: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1824: /* because that direction will be replaced unless the gain del is small */
1825: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1826: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1827: /* with the new direction. */
1.126 brouard 1828: del=fabs(fptt-(*fret));
1829: ibig=i;
1830: }
1831: #ifdef DEBUG
1832: printf("%d %.12e",i,(*fret));
1833: fprintf(ficlog,"%d %.12e",i,(*fret));
1834: for (j=1;j<=n;j++) {
1835: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1836: printf(" x(%d)=%.12e",j,xit[j]);
1837: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1838: }
1839: for(j=1;j<=n;j++) {
1.162 brouard 1840: printf(" p(%d)=%.12e",j,p[j]);
1841: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1842: }
1843: printf("\n");
1844: fprintf(ficlog,"\n");
1845: #endif
1.187 brouard 1846: } /* end loop on each direction i */
1847: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1.188 brouard 1848: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1.187 brouard 1849: /* New value of last point Pn is not computed, P(n-1) */
1.182 brouard 1850: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188 brouard 1851: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1852: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1853: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1854: /* decreased of more than 3.84 */
1855: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1856: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1857: /* By adding 10 parameters more the gain should be 18.31 */
1858:
1859: /* Starting the program with initial values given by a former maximization will simply change */
1860: /* the scales of the directions and the directions, because the are reset to canonical directions */
1861: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1862: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1.126 brouard 1863: #ifdef DEBUG
1864: int k[2],l;
1865: k[0]=1;
1866: k[1]=-1;
1867: printf("Max: %.12e",(*func)(p));
1868: fprintf(ficlog,"Max: %.12e",(*func)(p));
1869: for (j=1;j<=n;j++) {
1870: printf(" %.12e",p[j]);
1871: fprintf(ficlog," %.12e",p[j]);
1872: }
1873: printf("\n");
1874: fprintf(ficlog,"\n");
1875: for(l=0;l<=1;l++) {
1876: for (j=1;j<=n;j++) {
1877: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1878: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1879: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1880: }
1881: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1882: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1883: }
1884: #endif
1885:
1886:
1887: free_vector(xit,1,n);
1888: free_vector(xits,1,n);
1889: free_vector(ptt,1,n);
1890: free_vector(pt,1,n);
1891: return;
1.192 brouard 1892: } /* enough precision */
1.126 brouard 1893: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.181 brouard 1894: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126 brouard 1895: ptt[j]=2.0*p[j]-pt[j];
1896: xit[j]=p[j]-pt[j];
1897: pt[j]=p[j];
1898: }
1.181 brouard 1899: fptt=(*func)(ptt); /* f_3 */
1.192 brouard 1900: #ifdef POWELLF1F3
1901: #else
1.161 brouard 1902: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192 brouard 1903: #endif
1.162 brouard 1904: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1905: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1906: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1907: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1908: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181 brouard 1909: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161 brouard 1910: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183 brouard 1911: #ifdef NRCORIGINAL
1912: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1913: #else
1914: 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 1915: t= t- del*SQR(fp-fptt);
1.183 brouard 1916: #endif
1.202 brouard 1917: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161 brouard 1918: #ifdef DEBUG
1.181 brouard 1919: 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);
1920: 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 1921: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1922: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1923: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1924: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1925: 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);
1926: 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);
1927: #endif
1.183 brouard 1928: #ifdef POWELLORIGINAL
1929: if (t < 0.0) { /* Then we use it for new direction */
1930: #else
1.182 brouard 1931: if (directest*t < 0.0) { /* Contradiction between both tests */
1.202 brouard 1932: 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 1933: 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 1934: 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 1935: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1936: }
1.181 brouard 1937: if (directest < 0.0) { /* Then we use it for new direction */
1938: #endif
1.191 brouard 1939: #ifdef DEBUGLINMIN
1940: printf("Before linmin in direction P%d-P0\n",n);
1941: for (j=1;j<=n;j++) {
1.202 brouard 1942: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1943: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1944: if(j % ncovmodel == 0){
1.191 brouard 1945: printf("\n");
1.202 brouard 1946: fprintf(ficlog,"\n");
1947: }
1.191 brouard 1948: }
1949: #endif
1.187 brouard 1950: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191 brouard 1951: #ifdef DEBUGLINMIN
1952: for (j=1;j<=n;j++) {
1953: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202 brouard 1954: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1955: if(j % ncovmodel == 0){
1.191 brouard 1956: printf("\n");
1.202 brouard 1957: fprintf(ficlog,"\n");
1958: }
1.191 brouard 1959: }
1960: #endif
1.126 brouard 1961: for (j=1;j<=n;j++) {
1.181 brouard 1962: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1963: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1.126 brouard 1964: }
1.181 brouard 1965: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1966: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1967:
1.126 brouard 1968: #ifdef DEBUG
1.164 brouard 1969: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1970: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1971: for(j=1;j<=n;j++){
1972: printf(" %.12e",xit[j]);
1973: fprintf(ficlog," %.12e",xit[j]);
1974: }
1975: printf("\n");
1976: fprintf(ficlog,"\n");
1977: #endif
1.192 brouard 1978: } /* end of t or directest negative */
1979: #ifdef POWELLF1F3
1980: #else
1.162 brouard 1981: } /* end if (fptt < fp) */
1.192 brouard 1982: #endif
1983: } /* loop iteration */
1.126 brouard 1984: }
1985:
1986: /**** Prevalence limit (stable or period prevalence) ****************/
1987:
1.203 brouard 1988: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126 brouard 1989: {
1990: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203 brouard 1991: matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206 brouard 1992: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
1993: /* Wx is row vector: population in state 1, population in state 2, population dead */
1994: /* or prevalence in state 1, prevalence in state 2, 0 */
1995: /* newm is the matrix after multiplications, its rows are identical at a factor */
1996: /* Initial matrix pimij */
1997: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
1998: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
1999: /* 0, 0 , 1} */
2000: /*
2001: * and after some iteration: */
2002: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2003: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2004: /* 0, 0 , 1} */
2005: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2006: /* {0.51571254859325999, 0.4842874514067399, */
2007: /* 0.51326036147820708, 0.48673963852179264} */
2008: /* If we start from prlim again, prlim tends to a constant matrix */
2009:
1.126 brouard 2010: int i, ii,j,k;
1.209 brouard 2011: double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145 brouard 2012: /* double **matprod2(); */ /* test */
1.131 brouard 2013: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 2014: double **newm;
1.209 brouard 2015: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203 brouard 2016: int ncvloop=0;
1.169 brouard 2017:
1.209 brouard 2018: min=vector(1,nlstate);
2019: max=vector(1,nlstate);
2020: meandiff=vector(1,nlstate);
2021:
1.126 brouard 2022: for (ii=1;ii<=nlstate+ndeath;ii++)
2023: for (j=1;j<=nlstate+ndeath;j++){
2024: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2025: }
1.169 brouard 2026:
2027: cov[1]=1.;
2028:
2029: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202 brouard 2030: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126 brouard 2031: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202 brouard 2032: ncvloop++;
1.126 brouard 2033: newm=savm;
2034: /* Covariates have to be included here again */
1.138 brouard 2035: cov[2]=agefin;
1.187 brouard 2036: if(nagesqr==1)
2037: cov[3]= agefin*agefin;;
1.138 brouard 2038: for (k=1; k<=cptcovn;k++) {
1.200 brouard 2039: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2040: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198 brouard 2041: /* 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 2042: }
1.186 brouard 2043: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 2044: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2045: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186 brouard 2046: for (k=1; k<=cptcovprod;k++) /* Useless */
1.200 brouard 2047: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2048: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138 brouard 2049:
2050: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2051: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2052: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 2053: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2054: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 2055: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 2056:
1.126 brouard 2057: savm=oldm;
2058: oldm=newm;
1.209 brouard 2059:
2060: for(j=1; j<=nlstate; j++){
2061: max[j]=0.;
2062: min[j]=1.;
2063: }
2064: for(i=1;i<=nlstate;i++){
2065: sumnew=0;
2066: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2067: for(j=1; j<=nlstate; j++){
2068: prlim[i][j]= newm[i][j]/(1-sumnew);
2069: max[j]=FMAX(max[j],prlim[i][j]);
2070: min[j]=FMIN(min[j],prlim[i][j]);
2071: }
2072: }
2073:
1.126 brouard 2074: maxmax=0.;
1.209 brouard 2075: for(j=1; j<=nlstate; j++){
2076: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2077: maxmax=FMAX(maxmax,meandiff[j]);
2078: /* 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 2079: } /* j loop */
1.203 brouard 2080: *ncvyear= (int)age- (int)agefin;
1.208 brouard 2081: /* 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 2082: if(maxmax < ftolpl){
1.209 brouard 2083: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2084: free_vector(min,1,nlstate);
2085: free_vector(max,1,nlstate);
2086: free_vector(meandiff,1,nlstate);
1.126 brouard 2087: return prlim;
2088: }
1.169 brouard 2089: } /* age loop */
1.208 brouard 2090: /* After some age loop it doesn't converge */
1.209 brouard 2091: 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 2092: 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 2093: /* 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); */
2094: free_vector(min,1,nlstate);
2095: free_vector(max,1,nlstate);
2096: free_vector(meandiff,1,nlstate);
1.208 brouard 2097:
1.169 brouard 2098: return prlim; /* should not reach here */
1.126 brouard 2099: }
2100:
2101: /*************** transition probabilities ***************/
2102:
2103: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2104: {
1.138 brouard 2105: /* According to parameters values stored in x and the covariate's values stored in cov,
2106: computes the probability to be observed in state j being in state i by appying the
2107: model to the ncovmodel covariates (including constant and age).
2108: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2109: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2110: ncth covariate in the global vector x is given by the formula:
2111: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2112: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2113: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2114: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2115: Outputs ps[i][j] the probability to be observed in j being in j according to
2116: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2117: */
2118: double s1, lnpijopii;
1.126 brouard 2119: /*double t34;*/
1.164 brouard 2120: int i,j, nc, ii, jj;
1.126 brouard 2121:
2122: for(i=1; i<= nlstate; i++){
2123: for(j=1; j<i;j++){
1.138 brouard 2124: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2125: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2126: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2127: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2128: }
1.138 brouard 2129: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2130: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 2131: }
2132: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 2133: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2134: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2135: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2136: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 2137: }
1.138 brouard 2138: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 2139: }
2140: }
2141:
2142: for(i=1; i<= nlstate; i++){
2143: s1=0;
1.131 brouard 2144: for(j=1; j<i; j++){
1.138 brouard 2145: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2146: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2147: }
2148: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 2149: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 2150: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2151: }
1.138 brouard 2152: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 2153: ps[i][i]=1./(s1+1.);
1.138 brouard 2154: /* Computing other pijs */
1.126 brouard 2155: for(j=1; j<i; j++)
2156: ps[i][j]= exp(ps[i][j])*ps[i][i];
2157: for(j=i+1; j<=nlstate+ndeath; j++)
2158: ps[i][j]= exp(ps[i][j])*ps[i][i];
2159: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2160: } /* end i */
2161:
2162: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2163: for(jj=1; jj<= nlstate+ndeath; jj++){
2164: ps[ii][jj]=0;
2165: ps[ii][ii]=1;
2166: }
2167: }
2168:
1.145 brouard 2169:
2170: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2171: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2172: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2173: /* } */
2174: /* printf("\n "); */
2175: /* } */
2176: /* printf("\n ");printf("%lf ",cov[2]);*/
2177: /*
1.126 brouard 2178: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2179: goto end;*/
2180: return ps;
2181: }
2182:
2183: /**************** Product of 2 matrices ******************/
2184:
1.145 brouard 2185: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 2186: {
2187: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2188: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2189: /* in, b, out are matrice of pointers which should have been initialized
2190: before: only the contents of out is modified. The function returns
2191: a pointer to pointers identical to out */
1.145 brouard 2192: int i, j, k;
1.126 brouard 2193: for(i=nrl; i<= nrh; i++)
1.145 brouard 2194: for(k=ncolol; k<=ncoloh; k++){
2195: out[i][k]=0.;
2196: for(j=ncl; j<=nch; j++)
2197: out[i][k] +=in[i][j]*b[j][k];
2198: }
1.126 brouard 2199: return out;
2200: }
2201:
2202:
2203: /************* Higher Matrix Product ***************/
2204:
2205: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2206: {
2207: /* Computes the transition matrix starting at age 'age' over
2208: 'nhstepm*hstepm*stepm' months (i.e. until
2209: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2210: nhstepm*hstepm matrices.
2211: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2212: (typically every 2 years instead of every month which is too big
2213: for the memory).
2214: Model is determined by parameters x and covariates have to be
2215: included manually here.
2216:
2217: */
2218:
2219: int i, j, d, h, k;
1.131 brouard 2220: double **out, cov[NCOVMAX+1];
1.126 brouard 2221: double **newm;
1.187 brouard 2222: double agexact;
1.126 brouard 2223:
2224: /* Hstepm could be zero and should return the unit matrix */
2225: for (i=1;i<=nlstate+ndeath;i++)
2226: for (j=1;j<=nlstate+ndeath;j++){
2227: oldm[i][j]=(i==j ? 1.0 : 0.0);
2228: po[i][j][0]=(i==j ? 1.0 : 0.0);
2229: }
2230: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2231: for(h=1; h <=nhstepm; h++){
2232: for(d=1; d <=hstepm; d++){
2233: newm=savm;
2234: /* Covariates have to be included here again */
2235: cov[1]=1.;
1.187 brouard 2236: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2237: cov[2]=agexact;
2238: if(nagesqr==1)
2239: cov[3]= agexact*agexact;
1.131 brouard 2240: for (k=1; k<=cptcovn;k++)
1.200 brouard 2241: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2242: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186 brouard 2243: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2244: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 2245: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2246: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145 brouard 2247: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200 brouard 2248: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2249: /* 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 2250:
2251:
2252: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2253: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2254: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2255: pmij(pmmij,cov,ncovmodel,x,nlstate));
2256: savm=oldm;
2257: oldm=newm;
2258: }
2259: for(i=1; i<=nlstate+ndeath; i++)
2260: for(j=1;j<=nlstate+ndeath;j++) {
2261: po[i][j][h]=newm[i][j];
1.128 brouard 2262: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 2263: }
1.128 brouard 2264: /*printf("h=%d ",h);*/
1.126 brouard 2265: } /* end h */
1.128 brouard 2266: /* printf("\n H=%d \n",h); */
1.126 brouard 2267: return po;
2268: }
2269:
1.162 brouard 2270: #ifdef NLOPT
2271: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2272: double fret;
2273: double *xt;
2274: int j;
2275: myfunc_data *d2 = (myfunc_data *) pd;
2276: /* xt = (p1-1); */
2277: xt=vector(1,n);
2278: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2279:
2280: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2281: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2282: printf("Function = %.12lf ",fret);
2283: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2284: printf("\n");
2285: free_vector(xt,1,n);
2286: return fret;
2287: }
2288: #endif
1.126 brouard 2289:
2290: /*************** log-likelihood *************/
2291: double func( double *x)
2292: {
2293: int i, ii, j, k, mi, d, kk;
1.131 brouard 2294: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2295: double **out;
2296: double sw; /* Sum of weights */
2297: double lli; /* Individual log likelihood */
2298: int s1, s2;
2299: double bbh, survp;
2300: long ipmx;
1.187 brouard 2301: double agexact;
1.126 brouard 2302: /*extern weight */
2303: /* We are differentiating ll according to initial status */
2304: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2305: /*for(i=1;i<imx;i++)
2306: printf(" %d\n",s[4][i]);
2307: */
1.162 brouard 2308:
2309: ++countcallfunc;
2310:
1.126 brouard 2311: cov[1]=1.;
2312:
2313: for(k=1; k<=nlstate; k++) ll[k]=0.;
2314:
2315: if(mle==1){
2316: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 2317: /* Computes the values of the ncovmodel covariates of the model
2318: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2319: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2320: to be observed in j being in i according to the model.
2321: */
1.145 brouard 2322: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187 brouard 2323: cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145 brouard 2324: }
1.137 brouard 2325: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 2326: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 2327: has been calculated etc */
1.126 brouard 2328: for(mi=1; mi<= wav[i]-1; mi++){
2329: for (ii=1;ii<=nlstate+ndeath;ii++)
2330: for (j=1;j<=nlstate+ndeath;j++){
2331: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2332: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2333: }
2334: for(d=0; d<dh[mi][i]; d++){
2335: newm=savm;
1.187 brouard 2336: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2337: cov[2]=agexact;
2338: if(nagesqr==1)
2339: cov[3]= agexact*agexact;
1.126 brouard 2340: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2341: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 2342: }
2343: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2344: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2345: savm=oldm;
2346: oldm=newm;
2347: } /* end mult */
2348:
2349: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2350: /* But now since version 0.9 we anticipate for bias at large stepm.
2351: * If stepm is larger than one month (smallest stepm) and if the exact delay
2352: * (in months) between two waves is not a multiple of stepm, we rounded to
2353: * the nearest (and in case of equal distance, to the lowest) interval but now
2354: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2355: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2356: * probability in order to take into account the bias as a fraction of the way
2357: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2358: * -stepm/2 to stepm/2 .
2359: * For stepm=1 the results are the same as for previous versions of Imach.
2360: * For stepm > 1 the results are less biased than in previous versions.
2361: */
2362: s1=s[mw[mi][i]][i];
2363: s2=s[mw[mi+1][i]][i];
2364: bbh=(double)bh[mi][i]/(double)stepm;
2365: /* bias bh is positive if real duration
2366: * is higher than the multiple of stepm and negative otherwise.
2367: */
2368: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2369: if( s2 > nlstate){
2370: /* i.e. if s2 is a death state and if the date of death is known
2371: then the contribution to the likelihood is the probability to
2372: die between last step unit time and current step unit time,
2373: which is also equal to probability to die before dh
2374: minus probability to die before dh-stepm .
2375: In version up to 0.92 likelihood was computed
2376: as if date of death was unknown. Death was treated as any other
2377: health state: the date of the interview describes the actual state
2378: and not the date of a change in health state. The former idea was
2379: to consider that at each interview the state was recorded
2380: (healthy, disable or death) and IMaCh was corrected; but when we
2381: introduced the exact date of death then we should have modified
2382: the contribution of an exact death to the likelihood. This new
2383: contribution is smaller and very dependent of the step unit
2384: stepm. It is no more the probability to die between last interview
2385: and month of death but the probability to survive from last
2386: interview up to one month before death multiplied by the
2387: probability to die within a month. Thanks to Chris
2388: Jackson for correcting this bug. Former versions increased
2389: mortality artificially. The bad side is that we add another loop
2390: which slows down the processing. The difference can be up to 10%
2391: lower mortality.
2392: */
1.183 brouard 2393: /* If, at the beginning of the maximization mostly, the
2394: cumulative probability or probability to be dead is
2395: constant (ie = 1) over time d, the difference is equal to
2396: 0. out[s1][3] = savm[s1][3]: probability, being at state
2397: s1 at precedent wave, to be dead a month before current
2398: wave is equal to probability, being at state s1 at
2399: precedent wave, to be dead at mont of the current
2400: wave. Then the observed probability (that this person died)
2401: is null according to current estimated parameter. In fact,
2402: it should be very low but not zero otherwise the log go to
2403: infinity.
2404: */
2405: /* #ifdef INFINITYORIGINAL */
2406: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2407: /* #else */
2408: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2409: /* lli=log(mytinydouble); */
2410: /* else */
2411: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2412: /* #endif */
2413: lli=log(out[s1][s2] - savm[s1][s2]);
1.126 brouard 2414:
2415: } else if (s2==-2) {
2416: for (j=1,survp=0. ; j<=nlstate; j++)
2417: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2418: /*survp += out[s1][j]; */
2419: lli= log(survp);
2420: }
2421:
2422: else if (s2==-4) {
2423: for (j=3,survp=0. ; j<=nlstate; j++)
2424: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2425: lli= log(survp);
2426: }
2427:
2428: else if (s2==-5) {
2429: for (j=1,survp=0. ; j<=2; j++)
2430: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2431: lli= log(survp);
2432: }
2433:
2434: else{
2435: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2436: /* 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 */
2437: }
2438: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2439: /*if(lli ==000.0)*/
2440: /*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); */
2441: ipmx +=1;
2442: sw += weight[i];
2443: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183 brouard 2444: /* if (lli < log(mytinydouble)){ */
2445: /* 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); */
2446: /* 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]); */
2447: /* } */
1.126 brouard 2448: } /* end of wave */
2449: } /* end of individual */
2450: } else if(mle==2){
2451: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2452: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2453: for(mi=1; mi<= wav[i]-1; mi++){
2454: for (ii=1;ii<=nlstate+ndeath;ii++)
2455: for (j=1;j<=nlstate+ndeath;j++){
2456: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2457: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2458: }
2459: for(d=0; d<=dh[mi][i]; d++){
2460: newm=savm;
1.187 brouard 2461: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2462: cov[2]=agexact;
2463: if(nagesqr==1)
2464: cov[3]= agexact*agexact;
1.126 brouard 2465: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2466: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2467: }
2468: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2469: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2470: savm=oldm;
2471: oldm=newm;
2472: } /* end mult */
2473:
2474: s1=s[mw[mi][i]][i];
2475: s2=s[mw[mi+1][i]][i];
2476: bbh=(double)bh[mi][i]/(double)stepm;
2477: 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 */
2478: ipmx +=1;
2479: sw += weight[i];
2480: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2481: } /* end of wave */
2482: } /* end of individual */
2483: } else if(mle==3){ /* exponential inter-extrapolation */
2484: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2485: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2486: for(mi=1; mi<= wav[i]-1; mi++){
2487: for (ii=1;ii<=nlstate+ndeath;ii++)
2488: for (j=1;j<=nlstate+ndeath;j++){
2489: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2490: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2491: }
2492: for(d=0; d<dh[mi][i]; d++){
2493: newm=savm;
1.187 brouard 2494: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2495: cov[2]=agexact;
2496: if(nagesqr==1)
2497: cov[3]= agexact*agexact;
1.126 brouard 2498: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2499: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2500: }
2501: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2502: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2503: savm=oldm;
2504: oldm=newm;
2505: } /* end mult */
2506:
2507: s1=s[mw[mi][i]][i];
2508: s2=s[mw[mi+1][i]][i];
2509: bbh=(double)bh[mi][i]/(double)stepm;
2510: 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 */
2511: ipmx +=1;
2512: sw += weight[i];
2513: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2514: } /* end of wave */
2515: } /* end of individual */
2516: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2517: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2518: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2519: for(mi=1; mi<= wav[i]-1; mi++){
2520: for (ii=1;ii<=nlstate+ndeath;ii++)
2521: for (j=1;j<=nlstate+ndeath;j++){
2522: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2523: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2524: }
2525: for(d=0; d<dh[mi][i]; d++){
2526: newm=savm;
1.187 brouard 2527: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2528: cov[2]=agexact;
2529: if(nagesqr==1)
2530: cov[3]= agexact*agexact;
1.126 brouard 2531: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2532: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2533: }
2534:
2535: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2536: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2537: savm=oldm;
2538: oldm=newm;
2539: } /* end mult */
2540:
2541: s1=s[mw[mi][i]][i];
2542: s2=s[mw[mi+1][i]][i];
2543: if( s2 > nlstate){
2544: lli=log(out[s1][s2] - savm[s1][s2]);
2545: }else{
2546: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2547: }
2548: ipmx +=1;
2549: sw += weight[i];
2550: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2551: /* 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]); */
2552: } /* end of wave */
2553: } /* end of individual */
2554: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2555: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2556: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2557: for(mi=1; mi<= wav[i]-1; mi++){
2558: for (ii=1;ii<=nlstate+ndeath;ii++)
2559: for (j=1;j<=nlstate+ndeath;j++){
2560: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2561: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2562: }
2563: for(d=0; d<dh[mi][i]; d++){
2564: newm=savm;
1.187 brouard 2565: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2566: cov[2]=agexact;
2567: if(nagesqr==1)
2568: cov[3]= agexact*agexact;
1.126 brouard 2569: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2570: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2571: }
2572:
2573: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2574: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2575: savm=oldm;
2576: oldm=newm;
2577: } /* end mult */
2578:
2579: s1=s[mw[mi][i]][i];
2580: s2=s[mw[mi+1][i]][i];
2581: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2582: ipmx +=1;
2583: sw += weight[i];
2584: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2585: /*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]);*/
2586: } /* end of wave */
2587: } /* end of individual */
2588: } /* End of if */
2589: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2590: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2591: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2592: return -l;
2593: }
2594:
2595: /*************** log-likelihood *************/
2596: double funcone( double *x)
2597: {
2598: /* Same as likeli but slower because of a lot of printf and if */
2599: int i, ii, j, k, mi, d, kk;
1.131 brouard 2600: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2601: double **out;
2602: double lli; /* Individual log likelihood */
2603: double llt;
2604: int s1, s2;
2605: double bbh, survp;
1.187 brouard 2606: double agexact;
1.126 brouard 2607: /*extern weight */
2608: /* We are differentiating ll according to initial status */
2609: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2610: /*for(i=1;i<imx;i++)
2611: printf(" %d\n",s[4][i]);
2612: */
2613: cov[1]=1.;
2614:
2615: for(k=1; k<=nlstate; k++) ll[k]=0.;
2616:
2617: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187 brouard 2618: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126 brouard 2619: for(mi=1; mi<= wav[i]-1; mi++){
2620: for (ii=1;ii<=nlstate+ndeath;ii++)
2621: for (j=1;j<=nlstate+ndeath;j++){
2622: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2623: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2624: }
2625: for(d=0; d<dh[mi][i]; d++){
2626: newm=savm;
1.187 brouard 2627: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2628: cov[2]=agexact;
2629: if(nagesqr==1)
2630: cov[3]= agexact*agexact;
1.126 brouard 2631: for (kk=1; kk<=cptcovage;kk++) {
1.187 brouard 2632: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126 brouard 2633: }
1.187 brouard 2634:
1.145 brouard 2635: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2636: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2637: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2638: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2639: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2640: savm=oldm;
2641: oldm=newm;
2642: } /* end mult */
2643:
2644: s1=s[mw[mi][i]][i];
2645: s2=s[mw[mi+1][i]][i];
2646: bbh=(double)bh[mi][i]/(double)stepm;
2647: /* bias is positive if real duration
2648: * is higher than the multiple of stepm and negative otherwise.
2649: */
2650: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2651: lli=log(out[s1][s2] - savm[s1][s2]);
2652: } else if (s2==-2) {
2653: for (j=1,survp=0. ; j<=nlstate; j++)
2654: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2655: lli= log(survp);
2656: }else if (mle==1){
2657: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2658: } else if(mle==2){
2659: 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 */
2660: } else if(mle==3){ /* exponential inter-extrapolation */
2661: 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 */
2662: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2663: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2664: } else{ /* mle=0 back to 1 */
2665: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2666: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2667: } /* End of if */
2668: ipmx +=1;
2669: sw += weight[i];
2670: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2671: /*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 2672: if(globpr){
1.205 brouard 2673: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126 brouard 2674: %11.6f %11.6f %11.6f ", \
1.205 brouard 2675: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126 brouard 2676: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2677: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2678: llt +=ll[k]*gipmx/gsw;
2679: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2680: }
2681: fprintf(ficresilk," %10.6f\n", -llt);
2682: }
2683: } /* end of wave */
2684: } /* end of individual */
2685: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2686: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2687: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2688: if(globpr==0){ /* First time we count the contributions and weights */
2689: gipmx=ipmx;
2690: gsw=sw;
2691: }
2692: return -l;
2693: }
2694:
2695:
2696: /*************** function likelione ***********/
2697: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2698: {
2699: /* This routine should help understanding what is done with
2700: the selection of individuals/waves and
2701: to check the exact contribution to the likelihood.
2702: Plotting could be done.
2703: */
2704: int k;
2705:
2706: if(*globpri !=0){ /* Just counts and sums, no printings */
1.201 brouard 2707: strcpy(fileresilk,"ILK_");
1.202 brouard 2708: strcat(fileresilk,fileresu);
1.126 brouard 2709: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2710: printf("Problem with resultfile: %s\n", fileresilk);
2711: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2712: }
1.205 brouard 2713: 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 2714: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126 brouard 2715: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2716: for(k=1; k<=nlstate; k++)
2717: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2718: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2719: }
2720:
2721: *fretone=(*funcone)(p);
2722: if(*globpri !=0){
2723: fclose(ficresilk);
1.205 brouard 2724: if (mle ==0)
2725: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2726: else if(mle >=1)
2727: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2728: 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 2729:
1.208 brouard 2730:
2731: for (k=1; k<= nlstate ; k++) {
1.211 brouard 2732: 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 2733: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2734: }
1.207 brouard 2735: 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 2736: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207 brouard 2737: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204 brouard 2738: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207 brouard 2739: fflush(fichtm);
1.205 brouard 2740: }
1.126 brouard 2741: return;
2742: }
2743:
2744:
2745: /*********** Maximum Likelihood Estimation ***************/
2746:
2747: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2748: {
1.165 brouard 2749: int i,j, iter=0;
1.126 brouard 2750: double **xi;
2751: double fret;
2752: double fretone; /* Only one call to likelihood */
2753: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2754:
2755: #ifdef NLOPT
2756: int creturn;
2757: nlopt_opt opt;
2758: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2759: double *lb;
2760: double minf; /* the minimum objective value, upon return */
2761: double * p1; /* Shifted parameters from 0 instead of 1 */
2762: myfunc_data dinst, *d = &dinst;
2763: #endif
2764:
2765:
1.126 brouard 2766: xi=matrix(1,npar,1,npar);
2767: for (i=1;i<=npar;i++)
2768: for (j=1;j<=npar;j++)
2769: xi[i][j]=(i==j ? 1.0 : 0.0);
2770: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.201 brouard 2771: strcpy(filerespow,"POW_");
1.126 brouard 2772: strcat(filerespow,fileres);
2773: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2774: printf("Problem with resultfile: %s\n", filerespow);
2775: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2776: }
2777: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2778: for (i=1;i<=nlstate;i++)
2779: for(j=1;j<=nlstate+ndeath;j++)
2780: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2781: fprintf(ficrespow,"\n");
1.162 brouard 2782: #ifdef POWELL
1.126 brouard 2783: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2784: #endif
1.126 brouard 2785:
1.162 brouard 2786: #ifdef NLOPT
2787: #ifdef NEWUOA
2788: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2789: #else
2790: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2791: #endif
2792: lb=vector(0,npar-1);
2793: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2794: nlopt_set_lower_bounds(opt, lb);
2795: nlopt_set_initial_step1(opt, 0.1);
2796:
2797: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2798: d->function = func;
2799: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2800: nlopt_set_min_objective(opt, myfunc, d);
2801: nlopt_set_xtol_rel(opt, ftol);
2802: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2803: printf("nlopt failed! %d\n",creturn);
2804: }
2805: else {
2806: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2807: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2808: iter=1; /* not equal */
2809: }
2810: nlopt_destroy(opt);
2811: #endif
1.126 brouard 2812: free_matrix(xi,1,npar,1,npar);
2813: fclose(ficrespow);
1.203 brouard 2814: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2815: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180 brouard 2816: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2817:
2818: }
2819:
2820: /**** Computes Hessian and covariance matrix ***/
1.203 brouard 2821: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126 brouard 2822: {
2823: double **a,**y,*x,pd;
1.203 brouard 2824: /* double **hess; */
1.164 brouard 2825: int i, j;
1.126 brouard 2826: int *indx;
2827:
2828: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203 brouard 2829: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126 brouard 2830: void lubksb(double **a, int npar, int *indx, double b[]) ;
2831: void ludcmp(double **a, int npar, int *indx, double *d) ;
2832: double gompertz(double p[]);
1.203 brouard 2833: /* hess=matrix(1,npar,1,npar); */
1.126 brouard 2834:
2835: printf("\nCalculation of the hessian matrix. Wait...\n");
2836: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2837: for (i=1;i<=npar;i++){
1.203 brouard 2838: printf("%d-",i);fflush(stdout);
2839: fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126 brouard 2840:
2841: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2842:
2843: /* printf(" %f ",p[i]);
2844: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2845: }
2846:
2847: for (i=1;i<=npar;i++) {
2848: for (j=1;j<=npar;j++) {
2849: if (j>i) {
1.203 brouard 2850: printf(".%d-%d",i,j);fflush(stdout);
2851: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2852: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126 brouard 2853:
2854: hess[j][i]=hess[i][j];
2855: /*printf(" %lf ",hess[i][j]);*/
2856: }
2857: }
2858: }
2859: printf("\n");
2860: fprintf(ficlog,"\n");
2861:
2862: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2863: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2864:
2865: a=matrix(1,npar,1,npar);
2866: y=matrix(1,npar,1,npar);
2867: x=vector(1,npar);
2868: indx=ivector(1,npar);
2869: for (i=1;i<=npar;i++)
2870: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2871: ludcmp(a,npar,indx,&pd);
2872:
2873: for (j=1;j<=npar;j++) {
2874: for (i=1;i<=npar;i++) x[i]=0;
2875: x[j]=1;
2876: lubksb(a,npar,indx,x);
2877: for (i=1;i<=npar;i++){
2878: matcov[i][j]=x[i];
2879: }
2880: }
2881:
2882: printf("\n#Hessian matrix#\n");
2883: fprintf(ficlog,"\n#Hessian matrix#\n");
2884: for (i=1;i<=npar;i++) {
2885: for (j=1;j<=npar;j++) {
1.203 brouard 2886: printf("%.6e ",hess[i][j]);
2887: fprintf(ficlog,"%.6e ",hess[i][j]);
1.126 brouard 2888: }
2889: printf("\n");
2890: fprintf(ficlog,"\n");
2891: }
2892:
1.203 brouard 2893: /* printf("\n#Covariance matrix#\n"); */
2894: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2895: /* for (i=1;i<=npar;i++) { */
2896: /* for (j=1;j<=npar;j++) { */
2897: /* printf("%.6e ",matcov[i][j]); */
2898: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2899: /* } */
2900: /* printf("\n"); */
2901: /* fprintf(ficlog,"\n"); */
2902: /* } */
2903:
1.126 brouard 2904: /* Recompute Inverse */
1.203 brouard 2905: /* for (i=1;i<=npar;i++) */
2906: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2907: /* ludcmp(a,npar,indx,&pd); */
2908:
2909: /* printf("\n#Hessian matrix recomputed#\n"); */
2910:
2911: /* for (j=1;j<=npar;j++) { */
2912: /* for (i=1;i<=npar;i++) x[i]=0; */
2913: /* x[j]=1; */
2914: /* lubksb(a,npar,indx,x); */
2915: /* for (i=1;i<=npar;i++){ */
2916: /* y[i][j]=x[i]; */
2917: /* printf("%.3e ",y[i][j]); */
2918: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2919: /* } */
2920: /* printf("\n"); */
2921: /* fprintf(ficlog,"\n"); */
2922: /* } */
2923:
2924: /* Verifying the inverse matrix */
2925: #ifdef DEBUGHESS
2926: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126 brouard 2927:
1.203 brouard 2928: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2929: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126 brouard 2930:
2931: for (j=1;j<=npar;j++) {
2932: for (i=1;i<=npar;i++){
1.203 brouard 2933: printf("%.2f ",y[i][j]);
2934: fprintf(ficlog,"%.2f ",y[i][j]);
1.126 brouard 2935: }
2936: printf("\n");
2937: fprintf(ficlog,"\n");
2938: }
1.203 brouard 2939: #endif
1.126 brouard 2940:
2941: free_matrix(a,1,npar,1,npar);
2942: free_matrix(y,1,npar,1,npar);
2943: free_vector(x,1,npar);
2944: free_ivector(indx,1,npar);
1.203 brouard 2945: /* free_matrix(hess,1,npar,1,npar); */
1.126 brouard 2946:
2947:
2948: }
2949:
2950: /*************** hessian matrix ****************/
2951: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203 brouard 2952: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126 brouard 2953: int i;
2954: int l=1, lmax=20;
1.203 brouard 2955: double k1,k2, res, fx;
1.132 brouard 2956: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2957: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2958: int k=0,kmax=10;
2959: double l1;
2960:
2961: fx=func(x);
2962: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2963: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2964: l1=pow(10,l);
2965: delts=delt;
2966: for(k=1 ; k <kmax; k=k+1){
2967: delt = delta*(l1*k);
2968: p2[theta]=x[theta] +delt;
1.145 brouard 2969: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2970: p2[theta]=x[theta]-delt;
2971: k2=func(p2)-fx;
2972: /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203 brouard 2973: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126 brouard 2974:
1.203 brouard 2975: #ifdef DEBUGHESSII
1.126 brouard 2976: 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);
2977: 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);
2978: #endif
2979: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2980: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2981: k=kmax;
2982: }
2983: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2984: k=kmax; l=lmax*10;
1.126 brouard 2985: }
2986: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2987: delts=delt;
2988: }
1.203 brouard 2989: } /* End loop k */
1.126 brouard 2990: }
2991: delti[theta]=delts;
2992: return res;
2993:
2994: }
2995:
1.203 brouard 2996: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126 brouard 2997: {
2998: int i;
1.164 brouard 2999: int l=1, lmax=20;
1.126 brouard 3000: double k1,k2,k3,k4,res,fx;
1.132 brouard 3001: double p2[MAXPARM+1];
1.203 brouard 3002: int k, kmax=1;
3003: double v1, v2, cv12, lc1, lc2;
1.208 brouard 3004:
3005: int firstime=0;
1.203 brouard 3006:
1.126 brouard 3007: fx=func(x);
1.203 brouard 3008: for (k=1; k<=kmax; k=k+10) {
1.126 brouard 3009: for (i=1;i<=npar;i++) p2[i]=x[i];
1.203 brouard 3010: p2[thetai]=x[thetai]+delti[thetai]*k;
3011: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 3012: k1=func(p2)-fx;
3013:
1.203 brouard 3014: p2[thetai]=x[thetai]+delti[thetai]*k;
3015: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 3016: k2=func(p2)-fx;
3017:
1.203 brouard 3018: p2[thetai]=x[thetai]-delti[thetai]*k;
3019: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126 brouard 3020: k3=func(p2)-fx;
3021:
1.203 brouard 3022: p2[thetai]=x[thetai]-delti[thetai]*k;
3023: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126 brouard 3024: k4=func(p2)-fx;
1.203 brouard 3025: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3026: if(k1*k2*k3*k4 <0.){
1.208 brouard 3027: firstime=1;
1.203 brouard 3028: kmax=kmax+10;
1.208 brouard 3029: }
3030: if(kmax >=10 || firstime ==1){
1.203 brouard 3031: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3032: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3033: 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);
3034: 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);
3035: }
3036: #ifdef DEBUGHESSIJ
3037: v1=hess[thetai][thetai];
3038: v2=hess[thetaj][thetaj];
3039: cv12=res;
3040: /* Computing eigen value of Hessian matrix */
3041: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3042: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3043: if ((lc2 <0) || (lc1 <0) ){
3044: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3045: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3046: 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);
3047: 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);
3048: }
1.126 brouard 3049: #endif
3050: }
3051: return res;
3052: }
3053:
1.203 brouard 3054: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3055: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3056: /* { */
3057: /* int i; */
3058: /* int l=1, lmax=20; */
3059: /* double k1,k2,k3,k4,res,fx; */
3060: /* double p2[MAXPARM+1]; */
3061: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3062: /* int k=0,kmax=10; */
3063: /* double l1; */
3064:
3065: /* fx=func(x); */
3066: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3067: /* l1=pow(10,l); */
3068: /* delts=delt; */
3069: /* for(k=1 ; k <kmax; k=k+1){ */
3070: /* delt = delti*(l1*k); */
3071: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3072: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3073: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3074: /* k1=func(p2)-fx; */
3075:
3076: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3077: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3078: /* k2=func(p2)-fx; */
3079:
3080: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3081: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3082: /* k3=func(p2)-fx; */
3083:
3084: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3085: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3086: /* k4=func(p2)-fx; */
3087: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3088: /* #ifdef DEBUGHESSIJ */
3089: /* 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); */
3090: /* 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); */
3091: /* #endif */
3092: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3093: /* k=kmax; */
3094: /* } */
3095: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3096: /* k=kmax; l=lmax*10; */
3097: /* } */
3098: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3099: /* delts=delt; */
3100: /* } */
3101: /* } /\* End loop k *\/ */
3102: /* } */
3103: /* delti[theta]=delts; */
3104: /* return res; */
3105: /* } */
3106:
3107:
1.126 brouard 3108: /************** Inverse of matrix **************/
3109: void ludcmp(double **a, int n, int *indx, double *d)
3110: {
3111: int i,imax,j,k;
3112: double big,dum,sum,temp;
3113: double *vv;
3114:
3115: vv=vector(1,n);
3116: *d=1.0;
3117: for (i=1;i<=n;i++) {
3118: big=0.0;
3119: for (j=1;j<=n;j++)
3120: if ((temp=fabs(a[i][j])) > big) big=temp;
3121: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3122: vv[i]=1.0/big;
3123: }
3124: for (j=1;j<=n;j++) {
3125: for (i=1;i<j;i++) {
3126: sum=a[i][j];
3127: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3128: a[i][j]=sum;
3129: }
3130: big=0.0;
3131: for (i=j;i<=n;i++) {
3132: sum=a[i][j];
3133: for (k=1;k<j;k++)
3134: sum -= a[i][k]*a[k][j];
3135: a[i][j]=sum;
3136: if ( (dum=vv[i]*fabs(sum)) >= big) {
3137: big=dum;
3138: imax=i;
3139: }
3140: }
3141: if (j != imax) {
3142: for (k=1;k<=n;k++) {
3143: dum=a[imax][k];
3144: a[imax][k]=a[j][k];
3145: a[j][k]=dum;
3146: }
3147: *d = -(*d);
3148: vv[imax]=vv[j];
3149: }
3150: indx[j]=imax;
3151: if (a[j][j] == 0.0) a[j][j]=TINY;
3152: if (j != n) {
3153: dum=1.0/(a[j][j]);
3154: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3155: }
3156: }
3157: free_vector(vv,1,n); /* Doesn't work */
3158: ;
3159: }
3160:
3161: void lubksb(double **a, int n, int *indx, double b[])
3162: {
3163: int i,ii=0,ip,j;
3164: double sum;
3165:
3166: for (i=1;i<=n;i++) {
3167: ip=indx[i];
3168: sum=b[ip];
3169: b[ip]=b[i];
3170: if (ii)
3171: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3172: else if (sum) ii=i;
3173: b[i]=sum;
3174: }
3175: for (i=n;i>=1;i--) {
3176: sum=b[i];
3177: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3178: b[i]=sum/a[i][i];
3179: }
3180: }
3181:
3182: void pstamp(FILE *fichier)
3183: {
1.196 brouard 3184: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126 brouard 3185: }
3186:
3187: /************ Frequencies ********************/
3188: 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[])
3189: { /* Some frequencies */
3190:
1.164 brouard 3191: int i, m, jk, j1, bool, z1,j;
1.126 brouard 3192: int first;
3193: double ***freq; /* Frequencies */
3194: double *pp, **prop;
3195: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3196: char fileresp[FILENAMELENGTH];
3197:
3198: pp=vector(1,nlstate);
3199: prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201 brouard 3200: strcpy(fileresp,"P_");
3201: strcat(fileresp,fileresu);
1.126 brouard 3202: if((ficresp=fopen(fileresp,"w"))==NULL) {
3203: printf("Problem with prevalence resultfile: %s\n", fileresp);
3204: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3205: exit(0);
3206: }
3207: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3208: j1=0;
3209:
3210: j=cptcoveff;
3211: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3212:
3213: first=1;
3214:
1.169 brouard 3215: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3216: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3217: /* j1++; */
1.145 brouard 3218: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 3219: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3220: scanf("%d", i);*/
3221: for (i=-5; i<=nlstate+ndeath; i++)
3222: for (jk=-5; jk<=nlstate+ndeath; jk++)
3223: for(m=iagemin; m <= iagemax+3; m++)
3224: freq[i][jk][m]=0;
1.143 brouard 3225:
3226: for (i=1; i<=nlstate; i++)
3227: for(m=iagemin; m <= iagemax+3; m++)
3228: prop[i][m]=0;
1.126 brouard 3229:
3230: dateintsum=0;
3231: k2cpt=0;
3232: for (i=1; i<=imx; i++) {
3233: bool=1;
1.210 brouard 3234: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144 brouard 3235: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3236: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145 brouard 3237: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 3238: bool=0;
1.198 brouard 3239: /* 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",
3240: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3241: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3242: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144 brouard 3243: }
1.210 brouard 3244: } /* cptcovn > 0 */
1.144 brouard 3245:
1.126 brouard 3246: if (bool==1){
3247: for(m=firstpass; m<=lastpass; m++){
3248: k2=anint[m][i]+(mint[m][i]/12.);
3249: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3250: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3251: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3252: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
3253: if (m<lastpass) {
3254: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3255: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3256: }
3257:
1.210 brouard 3258: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
1.126 brouard 3259: dateintsum=dateintsum+k2;
3260: k2cpt++;
1.210 brouard 3261: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.126 brouard 3262: }
3263: /*}*/
1.210 brouard 3264: } /* end m */
3265: } /* end bool */
3266: } /* end i = 1 to imx */
1.126 brouard 3267:
3268: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3269: pstamp(ficresp);
3270: if (cptcovn>0) {
3271: fprintf(ficresp, "\n#********** Variable ");
1.198 brouard 3272: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 3273: fprintf(ficresp, "**********\n#");
1.143 brouard 3274: fprintf(ficlog, "\n#********** Variable ");
1.198 brouard 3275: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143 brouard 3276: fprintf(ficlog, "**********\n#");
1.126 brouard 3277: }
3278: for(i=1; i<=nlstate;i++)
3279: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3280: fprintf(ficresp, "\n");
3281:
3282: for(i=iagemin; i <= iagemax+3; i++){
3283: if(i==iagemax+3){
3284: fprintf(ficlog,"Total");
3285: }else{
3286: if(first==1){
3287: first=0;
3288: printf("See log file for details...\n");
3289: }
3290: fprintf(ficlog,"Age %d", i);
3291: }
3292: for(jk=1; jk <=nlstate ; jk++){
3293: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3294: pp[jk] += freq[jk][m][i];
3295: }
3296: for(jk=1; jk <=nlstate ; jk++){
3297: for(m=-1, pos=0; m <=0 ; m++)
3298: pos += freq[jk][m][i];
3299: if(pp[jk]>=1.e-10){
3300: if(first==1){
1.132 brouard 3301: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 3302: }
3303: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3304: }else{
3305: if(first==1)
3306: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3307: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3308: }
3309: }
3310:
3311: for(jk=1; jk <=nlstate ; jk++){
3312: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3313: pp[jk] += freq[jk][m][i];
3314: }
3315: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3316: pos += pp[jk];
3317: posprop += prop[jk][i];
3318: }
3319: for(jk=1; jk <=nlstate ; jk++){
3320: if(pos>=1.e-5){
3321: if(first==1)
3322: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3323: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3324: }else{
3325: if(first==1)
3326: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3327: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3328: }
3329: if( i <= iagemax){
3330: if(pos>=1.e-5){
3331: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3332: /*probs[i][jk][j1]= pp[jk]/pos;*/
3333: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3334: }
3335: else
3336: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3337: }
3338: }
3339:
3340: for(jk=-1; jk <=nlstate+ndeath; jk++)
3341: for(m=-1; m <=nlstate+ndeath; m++)
3342: if(freq[jk][m][i] !=0 ) {
3343: if(first==1)
3344: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3345: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3346: }
3347: if(i <= iagemax)
3348: fprintf(ficresp,"\n");
3349: if(first==1)
3350: printf("Others in log...\n");
3351: fprintf(ficlog,"\n");
1.210 brouard 3352: } /* end loop i */
1.145 brouard 3353: /*}*/
1.210 brouard 3354: } /* end j1 */
1.126 brouard 3355: dateintmean=dateintsum/k2cpt;
3356:
3357: fclose(ficresp);
3358: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3359: free_vector(pp,1,nlstate);
3360: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3361: /* End of Freq */
3362: }
3363:
3364: /************ Prevalence ********************/
3365: 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)
3366: {
3367: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3368: in each health status at the date of interview (if between dateprev1 and dateprev2).
3369: We still use firstpass and lastpass as another selection.
3370: */
3371:
1.164 brouard 3372: int i, m, jk, j1, bool, z1,j;
3373:
3374: double **prop;
3375: double posprop;
1.126 brouard 3376: double y2; /* in fractional years */
3377: int iagemin, iagemax;
1.145 brouard 3378: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 3379:
3380: iagemin= (int) agemin;
3381: iagemax= (int) agemax;
3382: /*pp=vector(1,nlstate);*/
3383: prop=matrix(1,nlstate,iagemin,iagemax+3);
3384: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3385: j1=0;
3386:
1.145 brouard 3387: /*j=cptcoveff;*/
1.126 brouard 3388: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3389:
1.145 brouard 3390: first=1;
3391: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3392: /*for(i1=1; i1<=ncodemax[k1];i1++){
3393: j1++;*/
1.126 brouard 3394:
3395: for (i=1; i<=nlstate; i++)
3396: for(m=iagemin; m <= iagemax+3; m++)
3397: prop[i][m]=0.0;
3398:
3399: for (i=1; i<=imx; i++) { /* Each individual */
3400: bool=1;
3401: if (cptcovn>0) {
3402: for (z1=1; z1<=cptcoveff; z1++)
1.198 brouard 3403: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
1.126 brouard 3404: bool=0;
3405: }
3406: if (bool==1) {
3407: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3408: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3409: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3410: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3411: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3412: 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);
3413: if (s[m][i]>0 && s[m][i]<=nlstate) {
3414: /*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]]);*/
3415: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3416: prop[s[m][i]][iagemax+3] += weight[i];
3417: }
3418: }
3419: } /* end selection of waves */
3420: }
3421: }
3422: for(i=iagemin; i <= iagemax+3; i++){
3423: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3424: posprop += prop[jk][i];
3425: }
1.145 brouard 3426:
1.126 brouard 3427: for(jk=1; jk <=nlstate ; jk++){
3428: if( i <= iagemax){
3429: if(posprop>=1.e-5){
3430: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 3431: } else{
3432: if(first==1){
3433: first=0;
3434: 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]);
3435: }
3436: }
1.126 brouard 3437: }
3438: }/* end jk */
3439: }/* end i */
1.145 brouard 3440: /*} *//* end i1 */
3441: } /* end j1 */
1.126 brouard 3442:
3443: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3444: /*free_vector(pp,1,nlstate);*/
3445: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3446: } /* End of prevalence */
3447:
3448: /************* Waves Concatenation ***************/
3449:
3450: 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)
3451: {
3452: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3453: Death is a valid wave (if date is known).
3454: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3455: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3456: and mw[mi+1][i]. dh depends on stepm.
3457: */
3458:
3459: int i, mi, m;
3460: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3461: double sum=0., jmean=0.;*/
3462: int first;
3463: int j, k=0,jk, ju, jl;
3464: double sum=0.;
3465: first=0;
1.164 brouard 3466: jmin=100000;
1.126 brouard 3467: jmax=-1;
3468: jmean=0.;
3469: for(i=1; i<=imx; i++){
3470: mi=0;
3471: m=firstpass;
3472: while(s[m][i] <= nlstate){
3473: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3474: mw[++mi][i]=m;
3475: if(m >=lastpass)
3476: break;
3477: else
3478: m++;
3479: }/* end while */
3480: if (s[m][i] > nlstate){
3481: mi++; /* Death is another wave */
3482: /* if(mi==0) never been interviewed correctly before death */
3483: /* Only death is a correct wave */
3484: mw[mi][i]=m;
3485: }
3486:
3487: wav[i]=mi;
3488: if(mi==0){
3489: nbwarn++;
3490: if(first==0){
3491: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3492: first=1;
3493: }
3494: if(first==1){
3495: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3496: }
3497: } /* end mi==0 */
3498: } /* End individuals */
3499:
3500: for(i=1; i<=imx; i++){
3501: for(mi=1; mi<wav[i];mi++){
3502: if (stepm <=0)
3503: dh[mi][i]=1;
3504: else{
3505: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3506: if (agedc[i] < 2*AGESUP) {
3507: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3508: if(j==0) j=1; /* Survives at least one month after exam */
3509: else if(j<0){
3510: nberr++;
3511: 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]);
3512: j=1; /* Temporary Dangerous patch */
3513: 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);
3514: 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]);
3515: 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);
3516: }
3517: k=k+1;
3518: if (j >= jmax){
3519: jmax=j;
3520: ijmax=i;
3521: }
3522: if (j <= jmin){
3523: jmin=j;
3524: ijmin=i;
3525: }
3526: sum=sum+j;
3527: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3528: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3529: }
3530: }
3531: else{
3532: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3533: /* 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]); */
3534:
3535: k=k+1;
3536: if (j >= jmax) {
3537: jmax=j;
3538: ijmax=i;
3539: }
3540: else if (j <= jmin){
3541: jmin=j;
3542: ijmin=i;
3543: }
3544: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3545: /*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]);*/
3546: if(j<0){
3547: nberr++;
3548: 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]);
3549: 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]);
3550: }
3551: sum=sum+j;
3552: }
3553: jk= j/stepm;
3554: jl= j -jk*stepm;
3555: ju= j -(jk+1)*stepm;
3556: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3557: if(jl==0){
3558: dh[mi][i]=jk;
3559: bh[mi][i]=0;
3560: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 3561: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 3562: dh[mi][i]=jk+1;
3563: bh[mi][i]=ju;
3564: }
3565: }else{
3566: if(jl <= -ju){
3567: dh[mi][i]=jk;
3568: bh[mi][i]=jl; /* bias is positive if real duration
3569: * is higher than the multiple of stepm and negative otherwise.
3570: */
3571: }
3572: else{
3573: dh[mi][i]=jk+1;
3574: bh[mi][i]=ju;
3575: }
3576: if(dh[mi][i]==0){
3577: dh[mi][i]=1; /* At least one step */
3578: bh[mi][i]=ju; /* At least one step */
3579: /* 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);*/
3580: }
3581: } /* end if mle */
3582: }
3583: } /* end wave */
3584: }
3585: jmean=sum/k;
3586: 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 3587: 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 3588: }
3589:
3590: /*********** Tricode ****************************/
1.145 brouard 3591: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 3592: {
1.144 brouard 3593: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3594: /* 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 3595: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 3596: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 3597: * nbcode[Tvar[j]][1]=
1.144 brouard 3598: */
1.130 brouard 3599:
1.145 brouard 3600: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 3601: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 3602: int cptcode=0; /* Modality max of covariates j */
3603: int modmincovj=0; /* Modality min of covariates j */
3604:
3605:
1.126 brouard 3606: cptcoveff=0;
3607:
1.144 brouard 3608: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 3609:
1.145 brouard 3610: /* Loop on covariates without age and products */
1.186 brouard 3611: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192 brouard 3612: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186 brouard 3613: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
1.136 brouard 3614: modality of this covariate Vj*/
1.145 brouard 3615: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3616: * If product of Vn*Vm, still boolean *:
3617: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3618: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3619: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 3620: modality of the nth covariate of individual i. */
1.145 brouard 3621: if (ij > modmaxcovj)
3622: modmaxcovj=ij;
3623: else if (ij < modmincovj)
3624: modmincovj=ij;
3625: if ((ij < -1) && (ij > NCOVMAX)){
3626: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3627: exit(1);
3628: }else
1.136 brouard 3629: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 3630: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 3631: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 3632: /* getting the maximum value of the modality of the covariate
3633: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3634: female is 1, then modmaxcovj=1.*/
1.192 brouard 3635: } /* end for loop on individuals i */
1.145 brouard 3636: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192 brouard 3637: 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 3638: cptcode=modmaxcovj;
1.137 brouard 3639: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 3640: /*for (i=0; i<=cptcode; i++) {*/
1.192 brouard 3641: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3642: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3643: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3644: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3645: if( k != -1){
3646: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3647: covariate for which somebody answered excluding
3648: undefined. Usually 2: 0 and 1. */
3649: }
3650: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3651: covariate for which somebody answered including
3652: undefined. Usually 3: -1, 0 and 1. */
1.145 brouard 3653: }
3654: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3655: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 3656: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 3657:
1.136 brouard 3658: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186 brouard 3659: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3660: 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 3661: modmincovj=3; modmaxcovj = 7;
1.186 brouard 3662: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3663: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3664: defining two dummy variables: variables V1_1 and V1_2.
1.145 brouard 3665: nbcode[Tvar[j]][ij]=k;
3666: nbcode[Tvar[j]][1]=0;
3667: nbcode[Tvar[j]][2]=1;
3668: nbcode[Tvar[j]][3]=2;
1.197 brouard 3669: To be continued (not working yet).
1.145 brouard 3670: */
1.197 brouard 3671: ij=0; /* ij is similar to i but can jump over null modalities */
3672: 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*/
3673: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192 brouard 3674: break;
3675: }
3676: ij++;
1.197 brouard 3677: 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 3678: cptcode = ij; /* New max modality for covar j */
3679: } /* end of loop on modality i=-1 to 1 or more */
3680:
3681: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3682: /* /\*recode from 0 *\/ */
3683: /* k is a modality. If we have model=V1+V1*sex */
3684: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3685: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3686: /* } */
3687: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3688: /* if (ij > ncodemax[j]) { */
3689: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3690: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3691: /* break; */
3692: /* } */
3693: /* } /\* end of loop on modality k *\/ */
1.137 brouard 3694: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3695:
1.145 brouard 3696: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3697:
1.187 brouard 3698: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
1.145 brouard 3699: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3700: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.187 brouard 3701: Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145 brouard 3702: }
1.126 brouard 3703:
1.192 brouard 3704: ij=0;
1.145 brouard 3705: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3706: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3707: if((Ndum[i]!=0) && (i<=ncovcol)){
1.192 brouard 3708: ij++;
1.145 brouard 3709: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3710: Tvaraff[ij]=i; /*For printing (unclear) */
1.192 brouard 3711: }else{
3712: /* Tvaraff[ij]=0; */
3713: }
1.126 brouard 3714: }
1.192 brouard 3715: /* ij--; */
1.144 brouard 3716: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3717:
1.126 brouard 3718: }
3719:
1.145 brouard 3720:
1.126 brouard 3721: /*********** Health Expectancies ****************/
3722:
1.127 brouard 3723: 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 3724:
3725: {
3726: /* Health expectancies, no variances */
1.164 brouard 3727: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3728: int nhstepma, nstepma; /* Decreasing with age */
3729: double age, agelim, hf;
3730: double ***p3mat;
3731: double eip;
3732:
3733: pstamp(ficreseij);
3734: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3735: fprintf(ficreseij,"# Age");
3736: for(i=1; i<=nlstate;i++){
3737: for(j=1; j<=nlstate;j++){
3738: fprintf(ficreseij," e%1d%1d ",i,j);
3739: }
3740: fprintf(ficreseij," e%1d. ",i);
3741: }
3742: fprintf(ficreseij,"\n");
3743:
3744:
3745: if(estepm < stepm){
3746: printf ("Problem %d lower than %d\n",estepm, stepm);
3747: }
3748: else hstepm=estepm;
3749: /* We compute the life expectancy from trapezoids spaced every estepm months
3750: * This is mainly to measure the difference between two models: for example
3751: * if stepm=24 months pijx are given only every 2 years and by summing them
3752: * we are calculating an estimate of the Life Expectancy assuming a linear
3753: * progression in between and thus overestimating or underestimating according
3754: * to the curvature of the survival function. If, for the same date, we
3755: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3756: * to compare the new estimate of Life expectancy with the same linear
3757: * hypothesis. A more precise result, taking into account a more precise
3758: * curvature will be obtained if estepm is as small as stepm. */
3759:
3760: /* For example we decided to compute the life expectancy with the smallest unit */
3761: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3762: nhstepm is the number of hstepm from age to agelim
3763: nstepm is the number of stepm from age to agelin.
3764: Look at hpijx to understand the reason of that which relies in memory size
3765: and note for a fixed period like estepm months */
3766: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3767: survival function given by stepm (the optimization length). Unfortunately it
3768: means that if the survival funtion is printed only each two years of age and if
3769: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3770: results. So we changed our mind and took the option of the best precision.
3771: */
3772: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3773:
3774: agelim=AGESUP;
3775: /* If stepm=6 months */
3776: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3777: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3778:
3779: /* nhstepm age range expressed in number of stepm */
3780: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3781: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3782: /* if (stepm >= YEARM) hstepm=1;*/
3783: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3784: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3785:
3786: for (age=bage; age<=fage; age ++){
3787: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3788: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3789: /* if (stepm >= YEARM) hstepm=1;*/
3790: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3791:
3792: /* If stepm=6 months */
3793: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3794: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3795:
3796: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3797:
3798: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3799:
3800: printf("%d|",(int)age);fflush(stdout);
3801: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3802:
3803: /* Computing expectancies */
3804: for(i=1; i<=nlstate;i++)
3805: for(j=1; j<=nlstate;j++)
3806: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3807: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3808:
3809: /* 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]);*/
3810:
3811: }
3812:
3813: fprintf(ficreseij,"%3.0f",age );
3814: for(i=1; i<=nlstate;i++){
3815: eip=0;
3816: for(j=1; j<=nlstate;j++){
3817: eip +=eij[i][j][(int)age];
3818: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3819: }
3820: fprintf(ficreseij,"%9.4f", eip );
3821: }
3822: fprintf(ficreseij,"\n");
3823:
3824: }
3825: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3826: printf("\n");
3827: fprintf(ficlog,"\n");
3828:
3829: }
3830:
1.127 brouard 3831: 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 3832:
3833: {
3834: /* Covariances of health expectancies eij and of total life expectancies according
3835: to initial status i, ei. .
3836: */
3837: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3838: int nhstepma, nstepma; /* Decreasing with age */
3839: double age, agelim, hf;
3840: double ***p3matp, ***p3matm, ***varhe;
3841: double **dnewm,**doldm;
3842: double *xp, *xm;
3843: double **gp, **gm;
3844: double ***gradg, ***trgradg;
3845: int theta;
3846:
3847: double eip, vip;
3848:
3849: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3850: xp=vector(1,npar);
3851: xm=vector(1,npar);
3852: dnewm=matrix(1,nlstate*nlstate,1,npar);
3853: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3854:
3855: pstamp(ficresstdeij);
3856: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3857: fprintf(ficresstdeij,"# Age");
3858: for(i=1; i<=nlstate;i++){
3859: for(j=1; j<=nlstate;j++)
3860: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3861: fprintf(ficresstdeij," e%1d. ",i);
3862: }
3863: fprintf(ficresstdeij,"\n");
3864:
3865: pstamp(ficrescveij);
3866: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3867: fprintf(ficrescveij,"# Age");
3868: for(i=1; i<=nlstate;i++)
3869: for(j=1; j<=nlstate;j++){
3870: cptj= (j-1)*nlstate+i;
3871: for(i2=1; i2<=nlstate;i2++)
3872: for(j2=1; j2<=nlstate;j2++){
3873: cptj2= (j2-1)*nlstate+i2;
3874: if(cptj2 <= cptj)
3875: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3876: }
3877: }
3878: fprintf(ficrescveij,"\n");
3879:
3880: if(estepm < stepm){
3881: printf ("Problem %d lower than %d\n",estepm, stepm);
3882: }
3883: else hstepm=estepm;
3884: /* We compute the life expectancy from trapezoids spaced every estepm months
3885: * This is mainly to measure the difference between two models: for example
3886: * if stepm=24 months pijx are given only every 2 years and by summing them
3887: * we are calculating an estimate of the Life Expectancy assuming a linear
3888: * progression in between and thus overestimating or underestimating according
3889: * to the curvature of the survival function. If, for the same date, we
3890: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3891: * to compare the new estimate of Life expectancy with the same linear
3892: * hypothesis. A more precise result, taking into account a more precise
3893: * curvature will be obtained if estepm is as small as stepm. */
3894:
3895: /* For example we decided to compute the life expectancy with the smallest unit */
3896: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3897: nhstepm is the number of hstepm from age to agelim
3898: nstepm is the number of stepm from age to agelin.
3899: Look at hpijx to understand the reason of that which relies in memory size
3900: and note for a fixed period like estepm months */
3901: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3902: survival function given by stepm (the optimization length). Unfortunately it
3903: means that if the survival funtion is printed only each two years of age and if
3904: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3905: results. So we changed our mind and took the option of the best precision.
3906: */
3907: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3908:
3909: /* If stepm=6 months */
3910: /* nhstepm age range expressed in number of stepm */
3911: agelim=AGESUP;
3912: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3913: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3914: /* if (stepm >= YEARM) hstepm=1;*/
3915: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3916:
3917: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3918: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3919: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3920: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3921: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3922: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3923:
3924: for (age=bage; age<=fage; age ++){
3925: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3926: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3927: /* if (stepm >= YEARM) hstepm=1;*/
3928: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3929:
3930: /* If stepm=6 months */
3931: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3932: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3933:
3934: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3935:
3936: /* Computing Variances of health expectancies */
3937: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3938: decrease memory allocation */
3939: for(theta=1; theta <=npar; theta++){
3940: for(i=1; i<=npar; i++){
3941: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3942: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3943: }
3944: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3945: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3946:
3947: for(j=1; j<= nlstate; j++){
3948: for(i=1; i<=nlstate; i++){
3949: for(h=0; h<=nhstepm-1; h++){
3950: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3951: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3952: }
3953: }
3954: }
3955:
3956: for(ij=1; ij<= nlstate*nlstate; ij++)
3957: for(h=0; h<=nhstepm-1; h++){
3958: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3959: }
3960: }/* End theta */
3961:
3962:
3963: for(h=0; h<=nhstepm-1; h++)
3964: for(j=1; j<=nlstate*nlstate;j++)
3965: for(theta=1; theta <=npar; theta++)
3966: trgradg[h][j][theta]=gradg[h][theta][j];
3967:
3968:
3969: for(ij=1;ij<=nlstate*nlstate;ij++)
3970: for(ji=1;ji<=nlstate*nlstate;ji++)
3971: varhe[ij][ji][(int)age] =0.;
3972:
3973: printf("%d|",(int)age);fflush(stdout);
3974: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3975: for(h=0;h<=nhstepm-1;h++){
3976: for(k=0;k<=nhstepm-1;k++){
3977: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3978: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3979: for(ij=1;ij<=nlstate*nlstate;ij++)
3980: for(ji=1;ji<=nlstate*nlstate;ji++)
3981: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3982: }
3983: }
3984:
3985: /* Computing expectancies */
3986: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3987: for(i=1; i<=nlstate;i++)
3988: for(j=1; j<=nlstate;j++)
3989: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3990: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3991:
3992: /* 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]);*/
3993:
3994: }
3995:
3996: fprintf(ficresstdeij,"%3.0f",age );
3997: for(i=1; i<=nlstate;i++){
3998: eip=0.;
3999: vip=0.;
4000: for(j=1; j<=nlstate;j++){
4001: eip += eij[i][j][(int)age];
4002: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4003: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4004: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4005: }
4006: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4007: }
4008: fprintf(ficresstdeij,"\n");
4009:
4010: fprintf(ficrescveij,"%3.0f",age );
4011: for(i=1; i<=nlstate;i++)
4012: for(j=1; j<=nlstate;j++){
4013: cptj= (j-1)*nlstate+i;
4014: for(i2=1; i2<=nlstate;i2++)
4015: for(j2=1; j2<=nlstate;j2++){
4016: cptj2= (j2-1)*nlstate+i2;
4017: if(cptj2 <= cptj)
4018: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4019: }
4020: }
4021: fprintf(ficrescveij,"\n");
4022:
4023: }
4024: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4025: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4026: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4027: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4028: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4029: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4030: printf("\n");
4031: fprintf(ficlog,"\n");
4032:
4033: free_vector(xm,1,npar);
4034: free_vector(xp,1,npar);
4035: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4036: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4037: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4038: }
4039:
4040: /************ Variance ******************/
1.209 brouard 4041: 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 4042: {
4043: /* Variance of health expectancies */
4044: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4045: /* double **newm;*/
1.169 brouard 4046: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4047:
4048: int movingaverage();
1.126 brouard 4049: double **dnewm,**doldm;
4050: double **dnewmp,**doldmp;
4051: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 4052: int k;
1.126 brouard 4053: double *xp;
4054: double **gp, **gm; /* for var eij */
4055: double ***gradg, ***trgradg; /*for var eij */
4056: double **gradgp, **trgradgp; /* for var p point j */
4057: double *gpp, *gmp; /* for var p point j */
4058: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4059: double ***p3mat;
4060: double age,agelim, hf;
4061: double ***mobaverage;
4062: int theta;
4063: char digit[4];
4064: char digitp[25];
4065:
4066: char fileresprobmorprev[FILENAMELENGTH];
4067:
4068: if(popbased==1){
4069: if(mobilav!=0)
1.201 brouard 4070: strcpy(digitp,"-POPULBASED-MOBILAV_");
4071: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126 brouard 4072: }
4073: else
1.201 brouard 4074: strcpy(digitp,"-STABLBASED_");
1.126 brouard 4075:
4076: if (mobilav!=0) {
4077: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4078: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4079: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4080: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4081: }
4082: }
4083:
1.201 brouard 4084: strcpy(fileresprobmorprev,"PRMORPREV-");
1.126 brouard 4085: sprintf(digit,"%-d",ij);
4086: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4087: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4088: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202 brouard 4089: strcat(fileresprobmorprev,fileresu);
1.126 brouard 4090: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4091: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4092: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4093: }
4094: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4095: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4096: pstamp(ficresprobmorprev);
4097: 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);
4098: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4099: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4100: fprintf(ficresprobmorprev," p.%-d SE",j);
4101: for(i=1; i<=nlstate;i++)
4102: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4103: }
4104: fprintf(ficresprobmorprev,"\n");
1.208 brouard 4105:
1.126 brouard 4106: fprintf(ficgp,"\n# Routine varevsij");
1.200 brouard 4107: fprintf(ficgp,"\nunset title \n");
4108: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126 brouard 4109: 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");
4110: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4111: /* } */
4112: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4113: pstamp(ficresvij);
4114: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4115: if(popbased==1)
1.128 brouard 4116: 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 4117: else
4118: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4119: fprintf(ficresvij,"# Age");
4120: for(i=1; i<=nlstate;i++)
4121: for(j=1; j<=nlstate;j++)
4122: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4123: fprintf(ficresvij,"\n");
4124:
4125: xp=vector(1,npar);
4126: dnewm=matrix(1,nlstate,1,npar);
4127: doldm=matrix(1,nlstate,1,nlstate);
4128: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4129: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4130:
4131: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4132: gpp=vector(nlstate+1,nlstate+ndeath);
4133: gmp=vector(nlstate+1,nlstate+ndeath);
4134: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4135:
4136: if(estepm < stepm){
4137: printf ("Problem %d lower than %d\n",estepm, stepm);
4138: }
4139: else hstepm=estepm;
4140: /* For example we decided to compute the life expectancy with the smallest unit */
4141: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4142: nhstepm is the number of hstepm from age to agelim
1.208 brouard 4143: nstepm is the number of stepm from age to agelim.
1.209 brouard 4144: Look at function hpijx to understand why because of memory size limitations,
1.208 brouard 4145: we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126 brouard 4146: survival function given by stepm (the optimization length). Unfortunately it
4147: means that if the survival funtion is printed every two years of age and if
4148: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4149: results. So we changed our mind and took the option of the best precision.
4150: */
4151: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4152: agelim = AGESUP;
4153: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4154: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4155: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4156: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4157: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4158: gp=matrix(0,nhstepm,1,nlstate);
4159: gm=matrix(0,nhstepm,1,nlstate);
4160:
4161:
4162: for(theta=1; theta <=npar; theta++){
4163: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4164: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4165: }
1.209 brouard 4166:
4167: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126 brouard 4168:
4169: if (popbased==1) {
4170: if(mobilav ==0){
4171: for(i=1; i<=nlstate;i++)
4172: prlim[i][i]=probs[(int)age][i][ij];
4173: }else{ /* mobilav */
4174: for(i=1; i<=nlstate;i++)
4175: prlim[i][i]=mobaverage[(int)age][i][ij];
4176: }
4177: }
4178:
1.209 brouard 4179: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126 brouard 4180: for(j=1; j<= nlstate; j++){
4181: for(h=0; h<=nhstepm; h++){
4182: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4183: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4184: }
4185: }
1.209 brouard 4186: /* Next for computing probability of death (h=1 means
1.126 brouard 4187: computed over hstepm matrices product = hstepm*stepm months)
4188: as a weighted average of prlim.
4189: */
4190: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4191: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4192: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4193: }
4194: /* end probability of death */
4195:
4196: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4197: xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209 brouard 4198:
4199: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126 brouard 4200:
4201: if (popbased==1) {
4202: if(mobilav ==0){
4203: for(i=1; i<=nlstate;i++)
4204: prlim[i][i]=probs[(int)age][i][ij];
4205: }else{ /* mobilav */
4206: for(i=1; i<=nlstate;i++)
4207: prlim[i][i]=mobaverage[(int)age][i][ij];
4208: }
4209: }
4210:
1.209 brouard 4211: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4212:
1.128 brouard 4213: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 4214: for(h=0; h<=nhstepm; h++){
4215: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4216: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4217: }
4218: }
4219: /* This for computing probability of death (h=1 means
4220: computed over hstepm matrices product = hstepm*stepm months)
4221: as a weighted average of prlim.
4222: */
4223: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4224: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4225: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4226: }
4227: /* end probability of death */
4228:
4229: for(j=1; j<= nlstate; j++) /* vareij */
4230: for(h=0; h<=nhstepm; h++){
4231: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4232: }
4233:
4234: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4235: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4236: }
4237:
4238: } /* End theta */
4239:
4240: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4241:
4242: for(h=0; h<=nhstepm; h++) /* veij */
4243: for(j=1; j<=nlstate;j++)
4244: for(theta=1; theta <=npar; theta++)
4245: trgradg[h][j][theta]=gradg[h][theta][j];
4246:
4247: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4248: for(theta=1; theta <=npar; theta++)
4249: trgradgp[j][theta]=gradgp[theta][j];
4250:
4251:
4252: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4253: for(i=1;i<=nlstate;i++)
4254: for(j=1;j<=nlstate;j++)
4255: vareij[i][j][(int)age] =0.;
4256:
4257: for(h=0;h<=nhstepm;h++){
4258: for(k=0;k<=nhstepm;k++){
4259: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4260: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4261: for(i=1;i<=nlstate;i++)
4262: for(j=1;j<=nlstate;j++)
4263: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4264: }
4265: }
4266:
4267: /* pptj */
4268: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4269: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4270: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4271: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4272: varppt[j][i]=doldmp[j][i];
4273: /* end ppptj */
4274: /* x centered again */
1.209 brouard 4275:
4276: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126 brouard 4277:
4278: if (popbased==1) {
4279: if(mobilav ==0){
4280: for(i=1; i<=nlstate;i++)
4281: prlim[i][i]=probs[(int)age][i][ij];
4282: }else{ /* mobilav */
4283: for(i=1; i<=nlstate;i++)
4284: prlim[i][i]=mobaverage[(int)age][i][ij];
4285: }
4286: }
4287:
4288: /* This for computing probability of death (h=1 means
4289: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4290: as a weighted average of prlim.
4291: */
1.209 brouard 4292: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
1.126 brouard 4293: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4294: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4295: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4296: }
4297: /* end probability of death */
4298:
4299: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4300: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4301: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4302: for(i=1; i<=nlstate;i++){
4303: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4304: }
4305: }
4306: fprintf(ficresprobmorprev,"\n");
4307:
4308: fprintf(ficresvij,"%.0f ",age );
4309: for(i=1; i<=nlstate;i++)
4310: for(j=1; j<=nlstate;j++){
4311: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4312: }
4313: fprintf(ficresvij,"\n");
4314: free_matrix(gp,0,nhstepm,1,nlstate);
4315: free_matrix(gm,0,nhstepm,1,nlstate);
4316: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4317: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4318: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4319: } /* End age */
4320: free_vector(gpp,nlstate+1,nlstate+ndeath);
4321: free_vector(gmp,nlstate+1,nlstate+ndeath);
4322: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4323: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199 brouard 4324: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4325: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126 brouard 4326: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 4327: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201 brouard 4328: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4329: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4330: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4331: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 4332: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 4333: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 4334: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 4335: 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 4336: 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 4337: /* 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 4338: */
1.199 brouard 4339: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201 brouard 4340: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126 brouard 4341:
4342: free_vector(xp,1,npar);
4343: free_matrix(doldm,1,nlstate,1,nlstate);
4344: free_matrix(dnewm,1,nlstate,1,npar);
4345: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4346: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4347: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4348: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4349: fclose(ficresprobmorprev);
4350: fflush(ficgp);
4351: fflush(fichtm);
4352: } /* end varevsij */
4353:
4354: /************ Variance of prevlim ******************/
1.209 brouard 4355: 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 4356: {
1.205 brouard 4357: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126 brouard 4358: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 4359:
1.126 brouard 4360: double **dnewm,**doldm;
4361: int i, j, nhstepm, hstepm;
4362: double *xp;
4363: double *gp, *gm;
4364: double **gradg, **trgradg;
1.208 brouard 4365: double **mgm, **mgp;
1.126 brouard 4366: double age,agelim;
4367: int theta;
4368:
4369: pstamp(ficresvpl);
4370: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4371: fprintf(ficresvpl,"# Age");
4372: for(i=1; i<=nlstate;i++)
4373: fprintf(ficresvpl," %1d-%1d",i,i);
4374: fprintf(ficresvpl,"\n");
4375:
4376: xp=vector(1,npar);
4377: dnewm=matrix(1,nlstate,1,npar);
4378: doldm=matrix(1,nlstate,1,nlstate);
4379:
4380: hstepm=1*YEARM; /* Every year of age */
4381: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4382: agelim = AGESUP;
4383: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4384: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4385: if (stepm >= YEARM) hstepm=1;
4386: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4387: gradg=matrix(1,npar,1,nlstate);
1.208 brouard 4388: mgp=matrix(1,npar,1,nlstate);
4389: mgm=matrix(1,npar,1,nlstate);
1.126 brouard 4390: gp=vector(1,nlstate);
4391: gm=vector(1,nlstate);
4392:
4393: for(theta=1; theta <=npar; theta++){
4394: for(i=1; i<=npar; i++){ /* Computes gradient */
4395: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4396: }
1.209 brouard 4397: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4398: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4399: else
4400: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208 brouard 4401: for(i=1;i<=nlstate;i++){
1.126 brouard 4402: gp[i] = prlim[i][i];
1.208 brouard 4403: mgp[theta][i] = prlim[i][i];
4404: }
1.126 brouard 4405: for(i=1; i<=npar; i++) /* Computes gradient */
4406: xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209 brouard 4407: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4408: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4409: else
4410: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208 brouard 4411: for(i=1;i<=nlstate;i++){
1.126 brouard 4412: gm[i] = prlim[i][i];
1.208 brouard 4413: mgm[theta][i] = prlim[i][i];
4414: }
1.126 brouard 4415: for(i=1;i<=nlstate;i++)
4416: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209 brouard 4417: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126 brouard 4418: } /* End theta */
4419:
4420: trgradg =matrix(1,nlstate,1,npar);
4421:
4422: for(j=1; j<=nlstate;j++)
4423: for(theta=1; theta <=npar; theta++)
4424: trgradg[j][theta]=gradg[theta][j];
1.209 brouard 4425: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4426: /* printf("\nmgm mgp %d ",(int)age); */
4427: /* for(j=1; j<=nlstate;j++){ */
4428: /* printf(" %d ",j); */
4429: /* for(theta=1; theta <=npar; theta++) */
4430: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4431: /* printf("\n "); */
4432: /* } */
4433: /* } */
4434: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4435: /* printf("\n gradg %d ",(int)age); */
4436: /* for(j=1; j<=nlstate;j++){ */
4437: /* printf("%d ",j); */
4438: /* for(theta=1; theta <=npar; theta++) */
4439: /* printf("%d %lf ",theta,gradg[theta][j]); */
4440: /* printf("\n "); */
4441: /* } */
4442: /* } */
1.126 brouard 4443:
4444: for(i=1;i<=nlstate;i++)
4445: varpl[i][(int)age] =0.;
1.209 brouard 4446: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
1.205 brouard 4447: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4448: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4449: }else{
1.126 brouard 4450: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4451: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205 brouard 4452: }
1.126 brouard 4453: for(i=1;i<=nlstate;i++)
4454: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4455:
4456: fprintf(ficresvpl,"%.0f ",age );
4457: for(i=1; i<=nlstate;i++)
4458: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4459: fprintf(ficresvpl,"\n");
4460: free_vector(gp,1,nlstate);
4461: free_vector(gm,1,nlstate);
1.208 brouard 4462: free_matrix(mgm,1,npar,1,nlstate);
4463: free_matrix(mgp,1,npar,1,nlstate);
1.126 brouard 4464: free_matrix(gradg,1,npar,1,nlstate);
4465: free_matrix(trgradg,1,nlstate,1,npar);
4466: } /* End age */
4467:
4468: free_vector(xp,1,npar);
4469: free_matrix(doldm,1,nlstate,1,npar);
4470: free_matrix(dnewm,1,nlstate,1,nlstate);
4471:
4472: }
4473:
4474: /************ Variance of one-step probabilities ******************/
4475: 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[])
4476: {
1.164 brouard 4477: int i, j=0, k1, l1, tj;
1.126 brouard 4478: int k2, l2, j1, z1;
1.164 brouard 4479: int k=0, l;
1.145 brouard 4480: int first=1, first1, first2;
1.126 brouard 4481: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4482: double **dnewm,**doldm;
4483: double *xp;
4484: double *gp, *gm;
4485: double **gradg, **trgradg;
4486: double **mu;
1.164 brouard 4487: double age, cov[NCOVMAX+1];
1.126 brouard 4488: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4489: int theta;
4490: char fileresprob[FILENAMELENGTH];
4491: char fileresprobcov[FILENAMELENGTH];
4492: char fileresprobcor[FILENAMELENGTH];
4493: double ***varpij;
4494:
1.201 brouard 4495: strcpy(fileresprob,"PROB_");
1.126 brouard 4496: strcat(fileresprob,fileres);
4497: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4498: printf("Problem with resultfile: %s\n", fileresprob);
4499: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4500: }
1.201 brouard 4501: strcpy(fileresprobcov,"PROBCOV_");
1.202 brouard 4502: strcat(fileresprobcov,fileresu);
1.126 brouard 4503: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4504: printf("Problem with resultfile: %s\n", fileresprobcov);
4505: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4506: }
1.201 brouard 4507: strcpy(fileresprobcor,"PROBCOR_");
1.202 brouard 4508: strcat(fileresprobcor,fileresu);
1.126 brouard 4509: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4510: printf("Problem with resultfile: %s\n", fileresprobcor);
4511: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4512: }
4513: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4514: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4515: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4516: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4517: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4518: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4519: pstamp(ficresprob);
4520: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4521: fprintf(ficresprob,"# Age");
4522: pstamp(ficresprobcov);
4523: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4524: fprintf(ficresprobcov,"# Age");
4525: pstamp(ficresprobcor);
4526: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4527: fprintf(ficresprobcor,"# Age");
4528:
4529:
4530: for(i=1; i<=nlstate;i++)
4531: for(j=1; j<=(nlstate+ndeath);j++){
4532: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4533: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4534: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4535: }
4536: /* fprintf(ficresprob,"\n");
4537: fprintf(ficresprobcov,"\n");
4538: fprintf(ficresprobcor,"\n");
4539: */
1.131 brouard 4540: xp=vector(1,npar);
1.126 brouard 4541: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4542: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4543: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4544: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4545: first=1;
4546: fprintf(ficgp,"\n# Routine varprob");
4547: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4548: fprintf(fichtm,"\n");
4549:
1.200 brouard 4550: 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 4551: 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);
4552: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126 brouard 4553: and drawn. It helps understanding how is the covariance between two incidences.\
4554: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4555: 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. \
4556: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4557: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4558: standard deviations wide on each axis. <br>\
4559: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4560: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4561: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4562:
4563: cov[1]=1;
1.145 brouard 4564: /* tj=cptcoveff; */
4565: tj = (int) pow(2,cptcoveff);
1.126 brouard 4566: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4567: j1=0;
1.145 brouard 4568: for(j1=1; j1<=tj;j1++){
4569: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4570: /*j1++;*/
1.126 brouard 4571: if (cptcovn>0) {
4572: fprintf(ficresprob, "\n#********** Variable ");
1.198 brouard 4573: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4574: fprintf(ficresprob, "**********\n#\n");
4575: fprintf(ficresprobcov, "\n#********** Variable ");
1.198 brouard 4576: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4577: fprintf(ficresprobcov, "**********\n#\n");
4578:
4579: fprintf(ficgp, "\n#********** Variable ");
1.198 brouard 4580: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4581: fprintf(ficgp, "**********\n#\n");
4582:
4583:
4584: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
1.198 brouard 4585: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4586: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4587:
4588: fprintf(ficresprobcor, "\n#********** Variable ");
1.198 brouard 4589: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126 brouard 4590: fprintf(ficresprobcor, "**********\n#");
4591: }
4592:
1.145 brouard 4593: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4594: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4595: gp=vector(1,(nlstate)*(nlstate+ndeath));
4596: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 4597: for (age=bage; age<=fage; age ++){
4598: cov[2]=age;
1.187 brouard 4599: if(nagesqr==1)
4600: cov[3]= age*age;
1.126 brouard 4601: for (k=1; k<=cptcovn;k++) {
1.200 brouard 4602: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4603: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145 brouard 4604: * 1 1 1 1 1
4605: * 2 2 1 1 1
4606: * 3 1 2 1 1
4607: */
4608: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 4609: }
1.186 brouard 4610: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200 brouard 4611: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126 brouard 4612: for (k=1; k<=cptcovprod;k++)
1.200 brouard 4613: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126 brouard 4614:
4615:
4616: for(theta=1; theta <=npar; theta++){
4617: for(i=1; i<=npar; i++)
4618: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4619:
4620: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4621:
4622: k=0;
4623: for(i=1; i<= (nlstate); i++){
4624: for(j=1; j<=(nlstate+ndeath);j++){
4625: k=k+1;
4626: gp[k]=pmmij[i][j];
4627: }
4628: }
4629:
4630: for(i=1; i<=npar; i++)
4631: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4632:
4633: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4634: k=0;
4635: for(i=1; i<=(nlstate); i++){
4636: for(j=1; j<=(nlstate+ndeath);j++){
4637: k=k+1;
4638: gm[k]=pmmij[i][j];
4639: }
4640: }
4641:
4642: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4643: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4644: }
4645:
4646: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4647: for(theta=1; theta <=npar; theta++)
4648: trgradg[j][theta]=gradg[theta][j];
4649:
4650: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4651: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4652:
4653: pmij(pmmij,cov,ncovmodel,x,nlstate);
4654:
4655: k=0;
4656: for(i=1; i<=(nlstate); i++){
4657: for(j=1; j<=(nlstate+ndeath);j++){
4658: k=k+1;
4659: mu[k][(int) age]=pmmij[i][j];
4660: }
4661: }
4662: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4663: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4664: varpij[i][j][(int)age] = doldm[i][j];
4665:
4666: /*printf("\n%d ",(int)age);
4667: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4668: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4669: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4670: }*/
4671:
4672: fprintf(ficresprob,"\n%d ",(int)age);
4673: fprintf(ficresprobcov,"\n%d ",(int)age);
4674: fprintf(ficresprobcor,"\n%d ",(int)age);
4675:
4676: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4677: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4678: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4679: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4680: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4681: }
4682: i=0;
4683: for (k=1; k<=(nlstate);k++){
4684: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 4685: i++;
1.126 brouard 4686: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4687: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4688: for (j=1; j<=i;j++){
1.145 brouard 4689: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 4690: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4691: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4692: }
4693: }
4694: }/* end of loop for state */
4695: } /* end of loop for age */
1.145 brouard 4696: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4697: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4698: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4699: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4700:
1.126 brouard 4701: /* Confidence intervalle of pij */
4702: /*
1.131 brouard 4703: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 4704: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4705: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4706: 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);
4707: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4708: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4709: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4710: */
4711:
4712: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 4713: first1=1;first2=2;
1.126 brouard 4714: for (k2=1; k2<=(nlstate);k2++){
4715: for (l2=1; l2<=(nlstate+ndeath);l2++){
4716: if(l2==k2) continue;
4717: j=(k2-1)*(nlstate+ndeath)+l2;
4718: for (k1=1; k1<=(nlstate);k1++){
4719: for (l1=1; l1<=(nlstate+ndeath);l1++){
4720: if(l1==k1) continue;
4721: i=(k1-1)*(nlstate+ndeath)+l1;
4722: if(i<=j) continue;
4723: for (age=bage; age<=fage; age ++){
4724: if ((int)age %5==0){
4725: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4726: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4727: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4728: mu1=mu[i][(int) age]/stepm*YEARM ;
4729: mu2=mu[j][(int) age]/stepm*YEARM;
4730: c12=cv12/sqrt(v1*v2);
4731: /* Computing eigen value of matrix of covariance */
4732: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4733: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4734: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4735: if(first2==1){
4736: first1=0;
4737: 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);
4738: }
4739: 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);
4740: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4741: /* lc2=fabs(lc2); */
1.135 brouard 4742: }
4743:
1.126 brouard 4744: /* Eigen vectors */
4745: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4746: /*v21=sqrt(1.-v11*v11); *//* error */
4747: v21=(lc1-v1)/cv12*v11;
4748: v12=-v21;
4749: v22=v11;
4750: tnalp=v21/v11;
4751: if(first1==1){
4752: first1=0;
4753: 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);
4754: }
4755: 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);
4756: /*printf(fignu*/
4757: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4758: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4759: if(first==1){
4760: first=0;
1.200 brouard 4761: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126 brouard 4762: fprintf(ficgp,"\nset parametric;unset label");
4763: 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 4764: fprintf(ficgp,"\nset ter svg size 640, 480");
1.126 brouard 4765: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201 brouard 4766: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4767: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4768: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4769: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4770: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4771: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201 brouard 4772: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126 brouard 4773: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4774: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4775: 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",\
4776: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4777: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4778: }else{
4779: first=0;
4780: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4781: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4782: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4783: 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",\
4784: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4785: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4786: }/* if first */
4787: } /* age mod 5 */
4788: } /* end loop age */
1.201 brouard 4789: 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 4790: first=1;
4791: } /*l12 */
4792: } /* k12 */
4793: } /*l1 */
4794: }/* k1 */
1.169 brouard 4795: /* } */ /* loop covariates */
1.126 brouard 4796: }
4797: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4798: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4799: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4800: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4801: free_vector(xp,1,npar);
4802: fclose(ficresprob);
4803: fclose(ficresprobcov);
4804: fclose(ficresprobcor);
4805: fflush(ficgp);
4806: fflush(fichtmcov);
4807: }
4808:
4809:
4810: /******************* Printing html file ***********/
1.201 brouard 4811: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 4812: int lastpass, int stepm, int weightopt, char model[],\
4813: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211 brouard 4814: int popforecast, int prevfcast, int estepm , \
1.126 brouard 4815: double jprev1, double mprev1,double anprev1, \
4816: double jprev2, double mprev2,double anprev2){
4817: int jj1, k1, i1, cpt;
4818:
4819: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4820: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4821: </ul>");
4822: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4823: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201 brouard 4824: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126 brouard 4825: fprintf(fichtm,"\
4826: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201 brouard 4827: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126 brouard 4828: fprintf(fichtm,"\
4829: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4830: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126 brouard 4831: fprintf(fichtm,"\
1.211 brouard 4832: - (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 4833: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4834: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211 brouard 4835: if(prevfcast==1){
4836: fprintf(fichtm,"\
4837: - Prevalence projections by age and states: \
1.201 brouard 4838: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211 brouard 4839: }
1.126 brouard 4840:
4841: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4842:
1.145 brouard 4843: m=pow(2,cptcoveff);
1.126 brouard 4844: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4845:
4846: jj1=0;
4847: for(k1=1; k1<=m;k1++){
1.192 brouard 4848: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4849: jj1++;
4850: if (cptcovn > 0) {
4851: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192 brouard 4852: for (cpt=1; cpt<=cptcoveff;cpt++){
1.198 brouard 4853: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4854: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192 brouard 4855: }
1.126 brouard 4856: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4857: }
1.201 brouard 4858: /* aij, bij */
1.211 brouard 4859: 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> \
4860: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4861: /* Pij */
1.211 brouard 4862: 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 4863: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126 brouard 4864: /* Quasi-incidences */
1.211 brouard 4865: 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 4866: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211 brouard 4867: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
4868: 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 4869: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4870: /* Survival functions (period) in state j */
4871: for(cpt=1; cpt<=nlstate;cpt++){
4872: 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> \
4873: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4874: }
4875: /* State specific survival functions (period) */
4876: for(cpt=1; cpt<=nlstate;cpt++){
1.208 brouard 4877: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201 brouard 4878: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4879: <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);
4880: }
4881: /* Period (stable) prevalence in each health state */
4882: for(cpt=1; cpt<=nlstate;cpt++){
4883: 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> \
4884: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4885: }
1.211 brouard 4886: if(prevfcast==1){
4887: /* Projection of prevalence up to period (stable) prevalence in each health state */
4888: for(cpt=1; cpt<=nlstate;cpt++){
4889: fprintf(fichtm,"<br>\n- Projection of prevalece 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> \
4890: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
4891: }
4892: }
4893:
1.126 brouard 4894: for(cpt=1; cpt<=nlstate;cpt++) {
1.205 brouard 4895: 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 4896: <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 4897: }
1.192 brouard 4898: /* } /\* end i1 *\/ */
1.126 brouard 4899: }/* End k1 */
4900: fprintf(fichtm,"</ul>");
4901:
4902: fprintf(fichtm,"\
4903: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193 brouard 4904: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203 brouard 4905: - 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 4906: But because parameters are usually highly correlated (a higher incidence of disability \
4907: and a higher incidence of recovery can give very close observed transition) it might \
4908: be very useful to look not only at linear confidence intervals estimated from the \
4909: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4910: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4911: covariance matrix of the one-step probabilities. \
4912: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126 brouard 4913:
1.193 brouard 4914: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4915: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126 brouard 4916: fprintf(fichtm,"\
4917: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4918: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126 brouard 4919:
4920: fprintf(fichtm,"\
4921: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201 brouard 4922: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126 brouard 4923: fprintf(fichtm,"\
4924: - 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): \
4925: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4926: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126 brouard 4927: fprintf(fichtm,"\
4928: - (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): \
4929: <a href=\"%s\">%s</a> <br>\n</li>",
1.201 brouard 4930: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126 brouard 4931: fprintf(fichtm,"\
1.128 brouard 4932: - 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 4933: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126 brouard 4934: fprintf(fichtm,"\
1.128 brouard 4935: - 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 4936: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126 brouard 4937: fprintf(fichtm,"\
4938: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201 brouard 4939: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126 brouard 4940:
4941: /* if(popforecast==1) fprintf(fichtm,"\n */
4942: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4943: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4944: /* <br>",fileres,fileres,fileres,fileres); */
4945: /* else */
4946: /* 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); */
4947: fflush(fichtm);
4948: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4949:
1.145 brouard 4950: m=pow(2,cptcoveff);
1.126 brouard 4951: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4952:
4953: jj1=0;
4954: for(k1=1; k1<=m;k1++){
1.192 brouard 4955: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126 brouard 4956: jj1++;
4957: if (cptcovn > 0) {
4958: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4959: for (cpt=1; cpt<=cptcoveff;cpt++)
1.198 brouard 4960: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126 brouard 4961: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4962: }
4963: for(cpt=1; cpt<=nlstate;cpt++) {
4964: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205 brouard 4965: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
4966: <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 4967: }
4968: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4969: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4970: true period expectancies (those weighted with period prevalences are also\
4971: drawn in addition to the population based expectancies computed using\
1.205 brouard 4972: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
4973: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192 brouard 4974: /* } /\* end i1 *\/ */
1.126 brouard 4975: }/* End k1 */
4976: fprintf(fichtm,"</ul>");
4977: fflush(fichtm);
4978: }
4979:
4980: /******************* Gnuplot file **************/
1.211 brouard 4981: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126 brouard 4982:
4983: char dirfileres[132],optfileres[132];
1.164 brouard 4984: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211 brouard 4985: int lv=0, vlv=0, kl=0;
1.130 brouard 4986: int ng=0;
1.201 brouard 4987: int vpopbased;
1.126 brouard 4988: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4989: /* printf("Problem with file %s",optionfilegnuplot); */
4990: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4991: /* } */
4992:
4993: /*#ifdef windows */
4994: fprintf(ficgp,"cd \"%s\" \n",pathc);
4995: /*#endif */
4996: m=pow(2,cptcoveff);
4997:
1.202 brouard 4998: /* Contribution to likelihood */
4999: /* Plot the probability implied in the likelihood */
5000: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5001: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5002: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205 brouard 5003: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204 brouard 5004: /* nice for mle=4 plot by number of matrix products.
1.202 brouard 5005: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5006: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5007: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204 brouard 5008: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 brouard 5009: 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 5010: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.205 brouard 5011: 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 5012: for (i=1; i<= nlstate ; i ++) {
5013: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205 brouard 5014: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5015: 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 5016: for (j=2; j<= nlstate+ndeath ; j ++) {
1.205 brouard 5017: 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 5018: }
5019: fprintf(ficgp,";\nset out; unset ylabel;\n");
5020: }
5021: /* 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 */
5022: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5023: /* 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 5024: fprintf(ficgp,"\nset out;unset log\n");
1.202 brouard 5025: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5026:
1.126 brouard 5027: strcpy(dirfileres,optionfilefiname);
5028: strcpy(optfileres,"vpl");
5029: /* 1eme*/
1.211 brouard 5030: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5031: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5032: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5033: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5034: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5035: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5036: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5037: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5038: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5039: vlv= nbcode[Tvaraff[lv]][lv];
5040: fprintf(ficgp," V%d=%d ",k,vlv);
5041: }
5042: fprintf(ficgp,"\n#\n");
5043:
1.201 brouard 5044: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5045: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126 brouard 5046: fprintf(ficgp,"set xlabel \"Age\" \n\
5047: set ylabel \"Probability\" \n\
1.199 brouard 5048: set ter svg size 640, 480\n\
1.201 brouard 5049: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126 brouard 5050:
5051: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5052: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5053: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5054: }
1.201 brouard 5055: 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 5056: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5057: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5058: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5059: }
1.201 brouard 5060: 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 5061: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 5062: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5063: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 5064: }
1.201 brouard 5065: 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));
5066: fprintf(ficgp,"\nset out \n");
5067: } /* k1 */
5068: } /* cpt */
1.126 brouard 5069: /*2 eme*/
5070: for (k1=1; k1<= m ; k1 ++) {
1.211 brouard 5071: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5072: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5073: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5074: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5075: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5076: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5077: vlv= nbcode[Tvaraff[lv]][lv];
5078: fprintf(ficgp," V%d=%d ",k,vlv);
5079: }
5080: fprintf(ficgp,"\n#\n");
5081:
1.201 brouard 5082: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5083: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5084: if(vpopbased==0)
5085: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5086: else
5087: fprintf(ficgp,"\nreplot ");
5088: for (i=1; i<= nlstate+1 ; i ++) {
5089: k=2*i;
5090: 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);
5091: for (j=1; j<= nlstate+1 ; j ++) {
5092: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5093: else fprintf(ficgp," %%*lf (%%*lf)");
5094: }
5095: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5096: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5097: 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);
5098: for (j=1; j<= nlstate+1 ; j ++) {
5099: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5100: else fprintf(ficgp," %%*lf (%%*lf)");
5101: }
5102: fprintf(ficgp,"\" t\"\" w l lt 0,");
5103: 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);
5104: for (j=1; j<= nlstate+1 ; j ++) {
5105: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5106: else fprintf(ficgp," %%*lf (%%*lf)");
5107: }
5108: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5109: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5110: } /* state */
5111: } /* vpopbased */
5112: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5113: } /* k1 */
1.211 brouard 5114:
5115:
1.126 brouard 5116: /*3eme*/
5117: for (k1=1; k1<= m ; k1 ++) {
5118: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211 brouard 5119: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5120: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5121: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5122: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5123: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5124: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5125: vlv= nbcode[Tvaraff[lv]][lv];
5126: fprintf(ficgp," V%d=%d ",k,vlv);
5127: }
5128: fprintf(ficgp,"\n#\n");
5129:
1.126 brouard 5130: /* k=2+nlstate*(2*cpt-2); */
5131: k=2+(nlstate+1)*(cpt-1);
1.201 brouard 5132: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199 brouard 5133: fprintf(ficgp,"set ter svg size 640, 480\n\
1.201 brouard 5134: 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 5135: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5136: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5137: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5138: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5139: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5140: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5141:
5142: */
5143: for (i=1; i< nlstate ; i ++) {
1.201 brouard 5144: 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 5145: /* 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);*/
5146:
5147: }
1.201 brouard 5148: 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 5149: }
5150: }
5151:
1.201 brouard 5152: /* Survival functions (period) from state i in state j by initial state i */
5153: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5154: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211 brouard 5155: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5156: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5157: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5158: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5159: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5160: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5161: vlv= nbcode[Tvaraff[lv]][lv];
5162: fprintf(ficgp," V%d=%d ",k,vlv);
5163: }
5164: fprintf(ficgp,"\n#\n");
5165:
1.201 brouard 5166: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5167: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5168: set ter svg size 640, 480\n\
5169: unset log y\n\
5170: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5171: k=3;
1.201 brouard 5172: for (i=1; i<= nlstate ; i ++){
5173: if(i==1)
5174: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5175: else
5176: fprintf(ficgp,", '' ");
5177: l=(nlstate+ndeath)*(i-1)+1;
5178: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5179: for (j=2; j<= nlstate+ndeath ; j ++)
5180: fprintf(ficgp,"+$%d",k+l+j-1);
5181: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5182: } /* nlstate */
5183: fprintf(ficgp,"\nset out\n");
5184: } /* end cpt state*/
5185: } /* end covariate */
5186:
5187: /* Survival functions (period) from state i in state j by final state j */
1.202 brouard 5188: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201 brouard 5189: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5190: 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 5191: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5192: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5193: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5194: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5195: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5196: vlv= nbcode[Tvaraff[lv]][lv];
5197: fprintf(ficgp," V%d=%d ",k,vlv);
5198: }
5199: fprintf(ficgp,"\n#\n");
5200:
1.201 brouard 5201: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5202: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5203: set ter svg size 640, 480\n\
5204: unset log y\n\
5205: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5206: k=3;
1.201 brouard 5207: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5208: if(j==1)
5209: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5210: else
5211: fprintf(ficgp,", '' ");
5212: l=(nlstate+ndeath)*(cpt-1) +j;
5213: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5214: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5215: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5216: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5217: } /* nlstate */
5218: fprintf(ficgp,", '' ");
5219: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5220: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5221: l=(nlstate+ndeath)*(cpt-1) +j;
5222: if(j < nlstate)
5223: fprintf(ficgp,"$%d +",k+l);
5224: else
5225: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5226: }
5227: fprintf(ficgp,"\nset out\n");
5228: } /* end cpt state*/
5229: } /* end covariate */
5230:
1.202 brouard 5231: /* CV preval stable (period) for each covariate */
1.211 brouard 5232: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153 brouard 5233: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211 brouard 5234: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5235: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5236: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5237: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5238: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5239: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5240: vlv= nbcode[Tvaraff[lv]][lv];
5241: fprintf(ficgp," V%d=%d ",k,vlv);
5242: }
5243: fprintf(ficgp,"\n#\n");
5244:
1.201 brouard 5245: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126 brouard 5246: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199 brouard 5247: set ter svg size 640, 480\n\
1.126 brouard 5248: unset log y\n\
1.153 brouard 5249: plot [%.f:%.f] ", ageminpar, agemaxpar);
1.211 brouard 5250: k=3; /* Offset */
1.153 brouard 5251: for (i=1; i<= nlstate ; i ++){
5252: if(i==1)
1.201 brouard 5253: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153 brouard 5254: else
5255: fprintf(ficgp,", '' ");
1.154 brouard 5256: l=(nlstate+ndeath)*(i-1)+1;
5257: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201 brouard 5258: for (j=2; j<= nlstate ; j ++)
5259: fprintf(ficgp,"+$%d",k+l+j-1);
1.153 brouard 5260: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5261: } /* nlstate */
1.201 brouard 5262: fprintf(ficgp,"\nset out\n");
1.153 brouard 5263: } /* end cpt state*/
5264: } /* end covariate */
1.201 brouard 5265:
1.211 brouard 5266: if(prevfcast==1){
5267: /* Projection from cross-sectional to stable (period) for each covariate */
5268:
5269: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5270: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5271: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5272: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5273: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5274: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5275: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5276: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5277: vlv= nbcode[Tvaraff[lv]][lv];
5278: fprintf(ficgp," V%d=%d ",k,vlv);
5279: }
5280: fprintf(ficgp,"\n#\n");
5281:
5282: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
5283: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
5284: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
5285: set ter svg size 640, 480\n\
5286: unset log y\n\
5287: plot [%.f:%.f] ", ageminpar, agemaxpar);
5288: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
5289: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5290: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5291: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5292: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5293: if(i==1){
5294: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
5295: }else{
5296: fprintf(ficgp,",\\\n '' ");
5297: }
5298: if(cptcoveff ==0){ /* No covariate */
5299: fprintf(ficgp," u 2:("); /* Age is in 2 */
5300: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
5301: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
5302: if(i==nlstate+1)
5303: fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
5304: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,cpt );
5305: else
5306: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
5307: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5308: }else{
5309: fprintf(ficgp,"u 6:(("); /* Age is in 6 */
5310: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5311: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5312: kl=0;
5313: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
5314: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5315: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5316: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5317: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5318: vlv= nbcode[Tvaraff[lv]][lv];
5319: kl++;
5320: /* 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 *\/ */
5321: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5322: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5323: /* '' 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*/
5324: if(k==cptcoveff)
5325: if(i==nlstate+1)
5326: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5327: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,cpt );
5328: else
5329: 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], \
5330: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5331: else{
5332: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
5333: kl++;
5334: }
5335: } /* end covariate */
5336: } /* end if covariate */
5337: } /* nlstate */
5338: fprintf(ficgp,"\nset out\n");
5339: } /* end cpt state*/
5340: } /* end covariate */
5341: } /* End if prevfcast */
5342:
5343:
1.126 brouard 5344: /* proba elementaires */
1.187 brouard 5345: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126 brouard 5346: for(i=1,jk=1; i <=nlstate; i++){
1.187 brouard 5347: fprintf(ficgp,"# initial state %d\n",i);
1.126 brouard 5348: for(k=1; k <=(nlstate+ndeath); k++){
5349: if (k != i) {
1.187 brouard 5350: fprintf(ficgp,"# current state %d\n",k);
1.126 brouard 5351: for(j=1; j <=ncovmodel; j++){
1.187 brouard 5352: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126 brouard 5353: jk++;
5354: }
1.187 brouard 5355: fprintf(ficgp,"\n");
1.126 brouard 5356: }
5357: }
5358: }
1.187 brouard 5359: fprintf(ficgp,"##############\n#\n");
5360:
1.145 brouard 5361: /*goto avoid;*/
1.200 brouard 5362: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187 brouard 5363: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5364: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5365: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5366: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5367: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5368: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5369: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5370: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5371: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5372: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5373: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5374: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5375: fprintf(ficgp,"#\n");
1.201 brouard 5376: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187 brouard 5377: fprintf(ficgp,"# ng=%d\n",ng);
5378: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126 brouard 5379: for(jk=1; jk <=m; jk++) {
1.187 brouard 5380: fprintf(ficgp,"# jk=%d\n",jk);
1.201 brouard 5381: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5382: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5383: if (ng==1){
5384: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5385: fprintf(ficgp,"\nunset log y");
5386: }else if (ng==2){
5387: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5388: fprintf(ficgp,"\nset log y");
5389: }else if (ng==3){
1.126 brouard 5390: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201 brouard 5391: fprintf(ficgp,"\nset log y");
5392: }else
5393: fprintf(ficgp,"\nunset title ");
5394: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 5395: i=1;
5396: for(k2=1; k2<=nlstate; k2++) {
5397: k3=i;
5398: for(k=1; k<=(nlstate+ndeath); k++) {
5399: if (k != k2){
1.201 brouard 5400: switch( ng) {
5401: case 1:
1.187 brouard 5402: if(nagesqr==0)
1.201 brouard 5403: fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187 brouard 5404: else /* nagesqr =1 */
1.201 brouard 5405: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5406: break;
5407: case 2: /* ng=2 */
1.187 brouard 5408: if(nagesqr==0)
5409: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5410: else /* nagesqr =1 */
1.201 brouard 5411: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5412: break;
5413: case 3:
5414: if(nagesqr==0)
5415: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5416: else /* nagesqr =1 */
5417: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5418: break;
5419: }
1.141 brouard 5420: ij=1;/* To be checked else nbcode[0][0] wrong */
1.187 brouard 5421: for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197 brouard 5422: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5423: if(ij <=cptcovage) { /* Bug valgrind */
5424: if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200 brouard 5425: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5426: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197 brouard 5427: ij++;
5428: }
1.186 brouard 5429: }
5430: else
1.198 brouard 5431: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126 brouard 5432: }
1.201 brouard 5433: if(ng != 1){
5434: fprintf(ficgp,")/(1");
1.126 brouard 5435:
1.201 brouard 5436: for(k1=1; k1 <=nlstate; k1++){
5437: if(nagesqr==0)
5438: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5439: else /* nagesqr =1 */
5440: 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);
5441:
5442: ij=1;
5443: for(j=3; j <=ncovmodel-nagesqr; j++){
5444: if(ij <=cptcovage) { /* Bug valgrind */
5445: if((j-2)==Tage[ij]) { /* Bug valgrind */
5446: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5447: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5448: ij++;
5449: }
1.197 brouard 5450: }
1.201 brouard 5451: else
5452: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186 brouard 5453: }
1.201 brouard 5454: fprintf(ficgp,")");
1.126 brouard 5455: }
5456: fprintf(ficgp,")");
1.201 brouard 5457: if(ng ==2)
5458: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5459: else /* ng= 3 */
5460: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5461: }else{ /* end ng <> 1 */
5462: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126 brouard 5463: }
5464: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5465: i=i+ncovmodel;
5466: }
5467: } /* end k */
5468: } /* end k2 */
1.201 brouard 5469: fprintf(ficgp,"\n set out\n");
1.126 brouard 5470: } /* end jk */
5471: } /* end ng */
1.164 brouard 5472: /* avoid: */
1.126 brouard 5473: fflush(ficgp);
5474: } /* end gnuplot */
5475:
5476:
5477: /*************** Moving average **************/
5478: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5479:
5480: int i, cpt, cptcod;
5481: int modcovmax =1;
5482: int mobilavrange, mob;
5483: double age;
5484:
5485: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5486: a covariate has 2 modalities */
5487: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5488:
5489: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5490: if(mobilav==1) mobilavrange=5; /* default */
5491: else mobilavrange=mobilav;
5492: for (age=bage; age<=fage; age++)
5493: for (i=1; i<=nlstate;i++)
5494: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5495: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5496: /* We keep the original values on the extreme ages bage, fage and for
5497: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5498: we use a 5 terms etc. until the borders are no more concerned.
5499: */
5500: for (mob=3;mob <=mobilavrange;mob=mob+2){
5501: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5502: for (i=1; i<=nlstate;i++){
5503: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5504: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5505: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5506: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5507: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5508: }
5509: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5510: }
5511: }
5512: }/* end age */
5513: }/* end mob */
5514: }else return -1;
5515: return 0;
5516: }/* End movingaverage */
5517:
5518:
5519: /************** Forecasting ******************/
1.169 brouard 5520: 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 5521: /* proj1, year, month, day of starting projection
5522: agemin, agemax range of age
5523: dateprev1 dateprev2 range of dates during which prevalence is computed
5524: anproj2 year of en of projection (same day and month as proj1).
5525: */
1.164 brouard 5526: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 5527: double agec; /* generic age */
5528: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5529: double *popeffectif,*popcount;
5530: double ***p3mat;
5531: double ***mobaverage;
5532: char fileresf[FILENAMELENGTH];
5533:
5534: agelim=AGESUP;
1.211 brouard 5535: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
5536: in each health status at the date of interview (if between dateprev1 and dateprev2).
5537: We still use firstpass and lastpass as another selection.
5538: */
1.126 brouard 5539: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5540:
1.201 brouard 5541: strcpy(fileresf,"F_");
5542: strcat(fileresf,fileresu);
1.126 brouard 5543: if((ficresf=fopen(fileresf,"w"))==NULL) {
5544: printf("Problem with forecast resultfile: %s\n", fileresf);
5545: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5546: }
5547: printf("Computing forecasting: result on file '%s' \n", fileresf);
5548: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5549:
5550: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5551:
5552: if (mobilav!=0) {
5553: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5554: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5555: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5556: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5557: }
5558: }
5559:
5560: stepsize=(int) (stepm+YEARM-1)/YEARM;
5561: if (stepm<=12) stepsize=1;
5562: if(estepm < stepm){
5563: printf ("Problem %d lower than %d\n",estepm, stepm);
5564: }
5565: else hstepm=estepm;
5566:
5567: hstepm=hstepm/stepm;
5568: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5569: fractional in yp1 */
5570: anprojmean=yp;
5571: yp2=modf((yp1*12),&yp);
5572: mprojmean=yp;
5573: yp1=modf((yp2*30.5),&yp);
5574: jprojmean=yp;
5575: if(jprojmean==0) jprojmean=1;
5576: if(mprojmean==0) jprojmean=1;
5577:
5578: i1=cptcoveff;
5579: if (cptcovn < 1){i1=1;}
5580:
5581: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5582:
5583: fprintf(ficresf,"#****** Routine prevforecast **\n");
5584:
5585: /* if (h==(int)(YEARM*yearp)){ */
5586: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5587: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5588: k=k+1;
1.211 brouard 5589: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126 brouard 5590: for(j=1;j<=cptcoveff;j++) {
1.211 brouard 5591: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5592: }
1.211 brouard 5593: fprintf(ficresf," yearproj age");
1.126 brouard 5594: for(j=1; j<=nlstate+ndeath;j++){
5595: for(i=1; i<=nlstate;i++)
5596: fprintf(ficresf," p%d%d",i,j);
5597: fprintf(ficresf," p.%d",j);
5598: }
5599: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5600: fprintf(ficresf,"\n");
5601: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5602:
5603: for (agec=fage; agec>=(ageminpar-1); agec--){
5604: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5605: nhstepm = nhstepm/hstepm;
5606: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5607: oldm=oldms;savm=savms;
5608: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5609:
5610: for (h=0; h<=nhstepm; h++){
5611: if (h*hstepm/YEARM*stepm ==yearp) {
5612: fprintf(ficresf,"\n");
5613: for(j=1;j<=cptcoveff;j++)
1.198 brouard 5614: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5615: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5616: }
5617: for(j=1; j<=nlstate+ndeath;j++) {
5618: ppij=0.;
5619: for(i=1; i<=nlstate;i++) {
5620: if (mobilav==1)
5621: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5622: else {
5623: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5624: }
5625: if (h*hstepm/YEARM*stepm== yearp) {
5626: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5627: }
5628: } /* end i */
5629: if (h*hstepm/YEARM*stepm==yearp) {
5630: fprintf(ficresf," %.3f", ppij);
5631: }
5632: }/* end j */
5633: } /* end h */
5634: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5635: } /* end agec */
5636: } /* end yearp */
5637: } /* end cptcod */
5638: } /* end cptcov */
5639:
5640: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5641:
5642: fclose(ficresf);
5643: }
5644:
5645: /************** Forecasting *****not tested NB*************/
1.169 brouard 5646: 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 5647:
5648: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5649: int *popage;
5650: double calagedatem, agelim, kk1, kk2;
5651: double *popeffectif,*popcount;
5652: double ***p3mat,***tabpop,***tabpopprev;
5653: double ***mobaverage;
5654: char filerespop[FILENAMELENGTH];
5655:
5656: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5657: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5658: agelim=AGESUP;
5659: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5660:
5661: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5662:
5663:
1.201 brouard 5664: strcpy(filerespop,"POP_");
5665: strcat(filerespop,fileresu);
1.126 brouard 5666: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5667: printf("Problem with forecast resultfile: %s\n", filerespop);
5668: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5669: }
5670: printf("Computing forecasting: result on file '%s' \n", filerespop);
5671: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5672:
5673: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5674:
5675: if (mobilav!=0) {
5676: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5677: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5678: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5679: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5680: }
5681: }
5682:
5683: stepsize=(int) (stepm+YEARM-1)/YEARM;
5684: if (stepm<=12) stepsize=1;
5685:
5686: agelim=AGESUP;
5687:
5688: hstepm=1;
5689: hstepm=hstepm/stepm;
5690:
5691: if (popforecast==1) {
5692: if((ficpop=fopen(popfile,"r"))==NULL) {
5693: printf("Problem with population file : %s\n",popfile);exit(0);
5694: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5695: }
5696: popage=ivector(0,AGESUP);
5697: popeffectif=vector(0,AGESUP);
5698: popcount=vector(0,AGESUP);
5699:
5700: i=1;
5701: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5702:
5703: imx=i;
5704: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5705: }
5706:
5707: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5708: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5709: k=k+1;
5710: fprintf(ficrespop,"\n#******");
5711: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 5712: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 5713: }
5714: fprintf(ficrespop,"******\n");
5715: fprintf(ficrespop,"# Age");
5716: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5717: if (popforecast==1) fprintf(ficrespop," [Population]");
5718:
5719: for (cpt=0; cpt<=0;cpt++) {
5720: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5721:
5722: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5723: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5724: nhstepm = nhstepm/hstepm;
5725:
5726: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5727: oldm=oldms;savm=savms;
5728: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5729:
5730: for (h=0; h<=nhstepm; h++){
5731: if (h==(int) (calagedatem+YEARM*cpt)) {
5732: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5733: }
5734: for(j=1; j<=nlstate+ndeath;j++) {
5735: kk1=0.;kk2=0;
5736: for(i=1; i<=nlstate;i++) {
5737: if (mobilav==1)
5738: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5739: else {
5740: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5741: }
5742: }
5743: if (h==(int)(calagedatem+12*cpt)){
5744: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5745: /*fprintf(ficrespop," %.3f", kk1);
5746: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5747: }
5748: }
5749: for(i=1; i<=nlstate;i++){
5750: kk1=0.;
5751: for(j=1; j<=nlstate;j++){
5752: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5753: }
5754: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5755: }
5756:
5757: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5758: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5759: }
5760: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5761: }
5762: }
5763:
5764: /******/
5765:
5766: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5767: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5768: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5769: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5770: nhstepm = nhstepm/hstepm;
5771:
5772: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5773: oldm=oldms;savm=savms;
5774: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5775: for (h=0; h<=nhstepm; h++){
5776: if (h==(int) (calagedatem+YEARM*cpt)) {
5777: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5778: }
5779: for(j=1; j<=nlstate+ndeath;j++) {
5780: kk1=0.;kk2=0;
5781: for(i=1; i<=nlstate;i++) {
5782: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5783: }
5784: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5785: }
5786: }
5787: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5788: }
5789: }
5790: }
5791: }
5792:
5793: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5794:
5795: if (popforecast==1) {
5796: free_ivector(popage,0,AGESUP);
5797: free_vector(popeffectif,0,AGESUP);
5798: free_vector(popcount,0,AGESUP);
5799: }
5800: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5801: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5802: fclose(ficrespop);
5803: } /* End of popforecast */
5804:
5805: int fileappend(FILE *fichier, char *optionfich)
5806: {
5807: if((fichier=fopen(optionfich,"a"))==NULL) {
5808: printf("Problem with file: %s\n", optionfich);
5809: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5810: return (0);
5811: }
5812: fflush(fichier);
5813: return (1);
5814: }
5815:
5816:
5817: /**************** function prwizard **********************/
5818: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5819: {
5820:
5821: /* Wizard to print covariance matrix template */
5822:
1.164 brouard 5823: char ca[32], cb[32];
5824: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 5825: int numlinepar;
5826:
5827: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5828: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5829: for(i=1; i <=nlstate; i++){
5830: jj=0;
5831: for(j=1; j <=nlstate+ndeath; j++){
5832: if(j==i) continue;
5833: jj++;
5834: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5835: printf("%1d%1d",i,j);
5836: fprintf(ficparo,"%1d%1d",i,j);
5837: for(k=1; k<=ncovmodel;k++){
5838: /* printf(" %lf",param[i][j][k]); */
5839: /* fprintf(ficparo," %lf",param[i][j][k]); */
5840: printf(" 0.");
5841: fprintf(ficparo," 0.");
5842: }
5843: printf("\n");
5844: fprintf(ficparo,"\n");
5845: }
5846: }
5847: printf("# Scales (for hessian or gradient estimation)\n");
5848: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5849: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5850: for(i=1; i <=nlstate; i++){
5851: jj=0;
5852: for(j=1; j <=nlstate+ndeath; j++){
5853: if(j==i) continue;
5854: jj++;
5855: fprintf(ficparo,"%1d%1d",i,j);
5856: printf("%1d%1d",i,j);
5857: fflush(stdout);
5858: for(k=1; k<=ncovmodel;k++){
5859: /* printf(" %le",delti3[i][j][k]); */
5860: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5861: printf(" 0.");
5862: fprintf(ficparo," 0.");
5863: }
5864: numlinepar++;
5865: printf("\n");
5866: fprintf(ficparo,"\n");
5867: }
5868: }
5869: printf("# Covariance matrix\n");
5870: /* # 121 Var(a12)\n\ */
5871: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5872: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5873: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5874: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5875: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5876: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5877: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5878: fflush(stdout);
5879: fprintf(ficparo,"# Covariance matrix\n");
5880: /* # 121 Var(a12)\n\ */
5881: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5882: /* # ...\n\ */
5883: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5884:
5885: for(itimes=1;itimes<=2;itimes++){
5886: jj=0;
5887: for(i=1; i <=nlstate; i++){
5888: for(j=1; j <=nlstate+ndeath; j++){
5889: if(j==i) continue;
5890: for(k=1; k<=ncovmodel;k++){
5891: jj++;
5892: ca[0]= k+'a'-1;ca[1]='\0';
5893: if(itimes==1){
5894: printf("#%1d%1d%d",i,j,k);
5895: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5896: }else{
5897: printf("%1d%1d%d",i,j,k);
5898: fprintf(ficparo,"%1d%1d%d",i,j,k);
5899: /* printf(" %.5le",matcov[i][j]); */
5900: }
5901: ll=0;
5902: for(li=1;li <=nlstate; li++){
5903: for(lj=1;lj <=nlstate+ndeath; lj++){
5904: if(lj==li) continue;
5905: for(lk=1;lk<=ncovmodel;lk++){
5906: ll++;
5907: if(ll<=jj){
5908: cb[0]= lk +'a'-1;cb[1]='\0';
5909: if(ll<jj){
5910: if(itimes==1){
5911: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5912: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5913: }else{
5914: printf(" 0.");
5915: fprintf(ficparo," 0.");
5916: }
5917: }else{
5918: if(itimes==1){
5919: printf(" Var(%s%1d%1d)",ca,i,j);
5920: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5921: }else{
5922: printf(" 0.");
5923: fprintf(ficparo," 0.");
5924: }
5925: }
5926: }
5927: } /* end lk */
5928: } /* end lj */
5929: } /* end li */
5930: printf("\n");
5931: fprintf(ficparo,"\n");
5932: numlinepar++;
5933: } /* end k*/
5934: } /*end j */
5935: } /* end i */
5936: } /* end itimes */
5937:
5938: } /* end of prwizard */
5939: /******************* Gompertz Likelihood ******************************/
5940: double gompertz(double x[])
5941: {
5942: double A,B,L=0.0,sump=0.,num=0.;
5943: int i,n=0; /* n is the size of the sample */
5944:
5945: for (i=0;i<=imx-1 ; i++) {
5946: sump=sump+weight[i];
5947: /* sump=sump+1;*/
5948: num=num+1;
5949: }
5950:
5951:
5952: /* for (i=0; i<=imx; i++)
5953: 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]);*/
5954:
5955: for (i=1;i<=imx ; i++)
5956: {
5957: if (cens[i] == 1 && wav[i]>1)
5958: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5959:
5960: if (cens[i] == 0 && wav[i]>1)
5961: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5962: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5963:
5964: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5965: if (wav[i] > 1 ) { /* ??? */
5966: L=L+A*weight[i];
5967: /* 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]);*/
5968: }
5969: }
5970:
5971: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5972:
5973: return -2*L*num/sump;
5974: }
5975:
1.136 brouard 5976: #ifdef GSL
5977: /******************* Gompertz_f Likelihood ******************************/
5978: double gompertz_f(const gsl_vector *v, void *params)
5979: {
5980: double A,B,LL=0.0,sump=0.,num=0.;
5981: double *x= (double *) v->data;
5982: int i,n=0; /* n is the size of the sample */
5983:
5984: for (i=0;i<=imx-1 ; i++) {
5985: sump=sump+weight[i];
5986: /* sump=sump+1;*/
5987: num=num+1;
5988: }
5989:
5990:
5991: /* for (i=0; i<=imx; i++)
5992: 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]);*/
5993: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5994: for (i=1;i<=imx ; i++)
5995: {
5996: if (cens[i] == 1 && wav[i]>1)
5997: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5998:
5999: if (cens[i] == 0 && wav[i]>1)
6000: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6001: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6002:
6003: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6004: if (wav[i] > 1 ) { /* ??? */
6005: LL=LL+A*weight[i];
6006: /* 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]);*/
6007: }
6008: }
6009:
6010: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6011: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6012:
6013: return -2*LL*num/sump;
6014: }
6015: #endif
6016:
1.126 brouard 6017: /******************* Printing html file ***********/
1.201 brouard 6018: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126 brouard 6019: int lastpass, int stepm, int weightopt, char model[],\
6020: int imx, double p[],double **matcov,double agemortsup){
6021: int i,k;
6022:
6023: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
6024: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
6025: for (i=1;i<=2;i++)
6026: 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 6027: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126 brouard 6028: fprintf(fichtm,"</ul>");
6029:
6030: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
6031:
6032: 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>");
6033:
6034: for (k=agegomp;k<(agemortsup-2);k++)
6035: 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]);
6036:
6037:
6038: fflush(fichtm);
6039: }
6040:
6041: /******************* Gnuplot file **************/
1.201 brouard 6042: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126 brouard 6043:
6044: char dirfileres[132],optfileres[132];
1.164 brouard 6045:
1.126 brouard 6046: int ng;
6047:
6048:
6049: /*#ifdef windows */
6050: fprintf(ficgp,"cd \"%s\" \n",pathc);
6051: /*#endif */
6052:
6053:
6054: strcpy(dirfileres,optionfilefiname);
6055: strcpy(optfileres,"vpl");
1.199 brouard 6056: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
1.126 brouard 6057: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.199 brouard 6058: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
1.145 brouard 6059: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 6060: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
6061:
6062: }
6063:
1.136 brouard 6064: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
6065: {
1.126 brouard 6066:
1.136 brouard 6067: /*-------- data file ----------*/
6068: FILE *fic;
6069: char dummy[]=" ";
1.164 brouard 6070: int i=0, j=0, n=0;
1.136 brouard 6071: int linei, month, year,iout;
6072: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 6073: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 6074: char *stratrunc;
6075: int lstra;
1.126 brouard 6076:
6077:
1.136 brouard 6078: if((fic=fopen(datafile,"r"))==NULL) {
1.195 brouard 6079: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
6080: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136 brouard 6081: }
1.126 brouard 6082:
1.136 brouard 6083: i=1;
6084: linei=0;
6085: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
6086: linei=linei+1;
6087: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
6088: if(line[j] == '\t')
6089: line[j] = ' ';
6090: }
6091: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
6092: ;
6093: };
6094: line[j+1]=0; /* Trims blanks at end of line */
6095: if(line[0]=='#'){
6096: fprintf(ficlog,"Comment line\n%s\n",line);
6097: printf("Comment line\n%s\n",line);
6098: continue;
6099: }
6100: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 6101: strcpy(line, linetmp);
1.136 brouard 6102:
1.126 brouard 6103:
1.136 brouard 6104: for (j=maxwav;j>=1;j--){
1.137 brouard 6105: cutv(stra, strb, line, ' ');
1.136 brouard 6106: if(strb[0]=='.') { /* Missing status */
6107: lval=-1;
6108: }else{
6109: errno=0;
6110: lval=strtol(strb,&endptr,10);
6111: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
6112: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6113: 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);
6114: 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 6115: return 1;
6116: }
6117: }
6118: s[j][i]=lval;
6119:
6120: strcpy(line,stra);
6121: cutv(stra, strb,line,' ');
1.169 brouard 6122: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6123: }
1.169 brouard 6124: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 6125: month=99;
6126: year=9999;
6127: }else{
1.141 brouard 6128: 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);
6129: 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 6130: return 1;
6131: }
6132: anint[j][i]= (double) year;
6133: mint[j][i]= (double)month;
6134: strcpy(line,stra);
6135: } /* ENd Waves */
6136:
6137: cutv(stra, strb,line,' ');
1.169 brouard 6138: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6139: }
1.169 brouard 6140: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 6141: month=99;
6142: year=9999;
6143: }else{
1.141 brouard 6144: 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);
6145: 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 6146: return 1;
6147: }
6148: andc[i]=(double) year;
6149: moisdc[i]=(double) month;
6150: strcpy(line,stra);
6151:
6152: cutv(stra, strb,line,' ');
1.169 brouard 6153: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 6154: }
1.169 brouard 6155: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 6156: month=99;
6157: year=9999;
6158: }else{
1.141 brouard 6159: 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);
6160: 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 6161: return 1;
6162: }
6163: if (year==9999) {
1.141 brouard 6164: 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);
6165: 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 6166: return 1;
1.126 brouard 6167:
1.136 brouard 6168: }
6169: annais[i]=(double)(year);
6170: moisnais[i]=(double)(month);
6171: strcpy(line,stra);
6172:
6173: cutv(stra, strb,line,' ');
6174: errno=0;
6175: dval=strtod(strb,&endptr);
6176: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6177: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6178: 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 6179: fflush(ficlog);
6180: return 1;
6181: }
6182: weight[i]=dval;
6183: strcpy(line,stra);
6184:
6185: for (j=ncovcol;j>=1;j--){
6186: cutv(stra, strb,line,' ');
6187: if(strb[0]=='.') { /* Missing status */
6188: lval=-1;
6189: }else{
6190: errno=0;
6191: lval=strtol(strb,&endptr,10);
6192: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 6193: 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);
6194: 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 6195: return 1;
6196: }
6197: }
6198: if(lval <-1 || lval >1){
1.141 brouard 6199: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 6200: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6201: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6202: For example, for multinomial values like 1, 2 and 3,\n \
6203: build V1=0 V2=0 for the reference value (1),\n \
6204: V1=1 V2=0 for (2) \n \
6205: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6206: output of IMaCh is often meaningless.\n \
6207: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 6208: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 6209: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6210: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6211: For example, for multinomial values like 1, 2 and 3,\n \
6212: build V1=0 V2=0 for the reference value (1),\n \
6213: V1=1 V2=0 for (2) \n \
6214: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6215: output of IMaCh is often meaningless.\n \
6216: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6217: return 1;
6218: }
6219: covar[j][i]=(double)(lval);
6220: strcpy(line,stra);
6221: }
6222: lstra=strlen(stra);
6223:
6224: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6225: stratrunc = &(stra[lstra-9]);
6226: num[i]=atol(stratrunc);
6227: }
6228: else
6229: num[i]=atol(stra);
6230: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6231: 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;}*/
6232:
6233: i=i+1;
6234: } /* End loop reading data */
1.126 brouard 6235:
1.136 brouard 6236: *imax=i-1; /* Number of individuals */
6237: fclose(fic);
6238:
6239: return (0);
1.164 brouard 6240: /* endread: */
1.136 brouard 6241: printf("Exiting readdata: ");
6242: fclose(fic);
6243: return (1);
1.126 brouard 6244:
6245:
6246:
1.136 brouard 6247: }
1.145 brouard 6248: void removespace(char *str) {
6249: char *p1 = str, *p2 = str;
6250: do
6251: while (*p2 == ' ')
6252: p2++;
1.169 brouard 6253: while (*p1++ == *p2++);
1.145 brouard 6254: }
6255:
6256: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187 brouard 6257: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6258: * - nagesqr = 1 if age*age in the model, otherwise 0.
6259: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6260: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145 brouard 6261: * - cptcovage number of covariates with age*products =2
6262: * - cptcovs number of simple covariates
6263: * - 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
6264: * which is a new column after the 9 (ncovcol) variables.
6265: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6266: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6267: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6268: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6269: */
1.136 brouard 6270: {
1.145 brouard 6271: int i, j, k, ks;
1.164 brouard 6272: int j1, k1, k2;
1.136 brouard 6273: char modelsav[80];
1.145 brouard 6274: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187 brouard 6275: char *strpt;
1.136 brouard 6276:
1.145 brouard 6277: /*removespace(model);*/
1.136 brouard 6278: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 6279: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137 brouard 6280: if (strstr(model,"AGE") !=0){
1.192 brouard 6281: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6282: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136 brouard 6283: return 1;
6284: }
1.141 brouard 6285: if (strstr(model,"v") !=0){
6286: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6287: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6288: return 1;
6289: }
1.187 brouard 6290: strcpy(modelsav,model);
6291: if ((strpt=strstr(model,"age*age")) !=0){
6292: printf(" strpt=%s, model=%s\n",strpt, model);
6293: if(strpt != model){
6294: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6295: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6296: corresponding column of parameters.\n",model);
6297: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192 brouard 6298: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187 brouard 6299: corresponding column of parameters.\n",model); fflush(ficlog);
6300: return 1;
6301: }
6302:
6303: nagesqr=1;
6304: if (strstr(model,"+age*age") !=0)
6305: substrchaine(modelsav, model, "+age*age");
6306: else if (strstr(model,"age*age+") !=0)
6307: substrchaine(modelsav, model, "age*age+");
6308: else
6309: substrchaine(modelsav, model, "age*age");
6310: }else
6311: nagesqr=0;
6312: if (strlen(modelsav) >1){
6313: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6314: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6315: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6316: cptcovt= j+1; /* Number of total covariates in the model, not including
6317: * cst, age and age*age
6318: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6319: /* including age products which are counted in cptcovage.
6320: * but the covariates which are products must be treated
6321: * separately: ncovn=4- 2=2 (V1+V3). */
6322: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6323: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6324:
6325:
6326: /* Design
6327: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6328: * < ncovcol=8 >
6329: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6330: * k= 1 2 3 4 5 6 7 8
6331: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6332: * covar[k,i], value of kth covariate if not including age for individual i:
6333: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6334: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6335: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6336: * Tage[++cptcovage]=k
6337: * if products, new covar are created after ncovcol with k1
6338: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6339: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6340: * 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
6341: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6342: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6343: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6344: * < ncovcol=8 >
6345: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6346: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6347: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6348: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6349: * p Tprod[1]@2={ 6, 5}
6350: *p Tvard[1][1]@4= {7, 8, 5, 6}
6351: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6352: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6353: *How to reorganize?
6354: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6355: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6356: * {2, 1, 4, 8, 5, 6, 3, 7}
6357: * Struct []
6358: */
1.145 brouard 6359:
1.187 brouard 6360: /* This loop fills the array Tvar from the string 'model'.*/
6361: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6362: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6363: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6364: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6365: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6366: /* k=1 Tvar[1]=2 (from V2) */
6367: /* k=5 Tvar[5] */
6368: /* for (k=1; k<=cptcovn;k++) { */
1.198 brouard 6369: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187 brouard 6370: /* } */
1.198 brouard 6371: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187 brouard 6372: /*
6373: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6374: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145 brouard 6375: Tvar[k]=0;
1.187 brouard 6376: cptcovage=0;
6377: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6378: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6379: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6380: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6381: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6382: /*scanf("%d",i);*/
6383: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6384: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6385: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6386: /* covar is not filled and then is empty */
6387: cptcovprod--;
6388: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6389: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6390: cptcovage++; /* Sums the number of covariates which include age as a product */
6391: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6392: /*printf("stre=%s ", stre);*/
6393: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6394: cptcovprod--;
6395: cutl(stre,strb,strc,'V');
6396: Tvar[k]=atoi(stre);
6397: cptcovage++;
6398: Tage[cptcovage]=k;
6399: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6400: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6401: cptcovn++;
6402: cptcovprodnoage++;k1++;
6403: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6404: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6405: because this model-covariate is a construction we invent a new column
6406: ncovcol + k1
6407: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6408: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6409: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6410: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6411: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6412: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6413: k2=k2+2;
6414: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6415: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6416: for (i=1; i<=lastobs;i++){
6417: /* Computes the new covariate which is a product of
6418: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6419: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6420: }
6421: } /* End age is not in the model */
6422: } /* End if model includes a product */
6423: else { /* no more sum */
6424: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6425: /* scanf("%d",i);*/
6426: cutl(strd,strc,strb,'V');
6427: ks++; /**< Number of simple covariates */
1.145 brouard 6428: cptcovn++;
1.187 brouard 6429: Tvar[k]=atoi(strd);
6430: }
6431: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6432: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6433: scanf("%d",i);*/
6434: } /* end of loop + on total covariates */
6435: } /* end if strlen(modelsave == 0) age*age might exist */
6436: } /* end if strlen(model == 0) */
1.136 brouard 6437:
6438: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6439: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6440:
6441: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6442: printf("cptcovprod=%d ", cptcovprod);
6443: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6444:
6445: scanf("%d ",i);*/
6446:
6447:
1.137 brouard 6448: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 6449: /*endread:*/
1.136 brouard 6450: printf("Exiting decodemodel: ");
6451: return (1);
6452: }
6453:
1.169 brouard 6454: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 6455: {
6456: int i, m;
6457:
6458: for (i=1; i<=imx; i++) {
6459: for(m=2; (m<= maxwav); m++) {
6460: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6461: anint[m][i]=9999;
6462: s[m][i]=-1;
6463: }
6464: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 6465: *nberr = *nberr + 1;
6466: 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);
6467: 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 6468: s[m][i]=-1;
6469: }
6470: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 6471: (*nberr)++;
1.136 brouard 6472: 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]);
6473: 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]);
6474: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6475: }
6476: }
6477: }
6478:
6479: for (i=1; i<=imx; i++) {
6480: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6481: for(m=firstpass; (m<= lastpass); m++){
6482: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6483: if (s[m][i] >= nlstate+1) {
1.169 brouard 6484: if(agedc[i]>0){
6485: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 6486: agev[m][i]=agedc[i];
6487: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 6488: }else {
1.136 brouard 6489: if ((int)andc[i]!=9999){
6490: nbwarn++;
6491: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6492: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6493: agev[m][i]=-1;
6494: }
6495: }
1.169 brouard 6496: } /* agedc > 0 */
1.136 brouard 6497: }
6498: else if(s[m][i] !=9){ /* Standard case, age in fractional
6499: years but with the precision of a month */
6500: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6501: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6502: agev[m][i]=1;
6503: else if(agev[m][i] < *agemin){
6504: *agemin=agev[m][i];
6505: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6506: }
6507: else if(agev[m][i] >*agemax){
6508: *agemax=agev[m][i];
1.156 brouard 6509: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 6510: }
6511: /*agev[m][i]=anint[m][i]-annais[i];*/
6512: /* agev[m][i] = age[i]+2*m;*/
6513: }
6514: else { /* =9 */
6515: agev[m][i]=1;
6516: s[m][i]=-1;
6517: }
6518: }
6519: else /*= 0 Unknown */
6520: agev[m][i]=1;
6521: }
6522:
6523: }
6524: for (i=1; i<=imx; i++) {
6525: for(m=firstpass; (m<=lastpass); m++){
6526: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 6527: (*nberr)++;
1.136 brouard 6528: 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);
6529: 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);
6530: return 1;
6531: }
6532: }
6533: }
6534:
6535: /*for (i=1; i<=imx; i++){
6536: for (m=firstpass; (m<lastpass); m++){
6537: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6538: }
6539:
6540: }*/
6541:
6542:
1.139 brouard 6543: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6544: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 6545:
6546: return (0);
1.164 brouard 6547: /* endread:*/
1.136 brouard 6548: printf("Exiting calandcheckages: ");
6549: return (1);
6550: }
6551:
1.172 brouard 6552: #if defined(_MSC_VER)
6553: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6554: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6555: //#include "stdafx.h"
6556: //#include <stdio.h>
6557: //#include <tchar.h>
6558: //#include <windows.h>
6559: //#include <iostream>
6560: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6561:
6562: LPFN_ISWOW64PROCESS fnIsWow64Process;
6563:
6564: BOOL IsWow64()
6565: {
6566: BOOL bIsWow64 = FALSE;
6567:
6568: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6569: // (HANDLE, PBOOL);
6570:
6571: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6572:
6573: HMODULE module = GetModuleHandle(_T("kernel32"));
6574: const char funcName[] = "IsWow64Process";
6575: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6576: GetProcAddress(module, funcName);
6577:
6578: if (NULL != fnIsWow64Process)
6579: {
6580: if (!fnIsWow64Process(GetCurrentProcess(),
6581: &bIsWow64))
6582: //throw std::exception("Unknown error");
6583: printf("Unknown error\n");
6584: }
6585: return bIsWow64 != FALSE;
6586: }
6587: #endif
1.177 brouard 6588:
1.191 brouard 6589: void syscompilerinfo(int logged)
1.167 brouard 6590: {
6591: /* #include "syscompilerinfo.h"*/
1.185 brouard 6592: /* command line Intel compiler 32bit windows, XP compatible:*/
6593: /* /GS /W3 /Gy
6594: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6595: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6596: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186 brouard 6597: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6598: */
6599: /* 64 bits */
1.185 brouard 6600: /*
6601: /GS /W3 /Gy
6602: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6603: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6604: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6605: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6606: /* Optimization are useless and O3 is slower than O2 */
6607: /*
6608: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6609: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6610: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6611: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6612: */
1.186 brouard 6613: /* Link is */ /* /OUT:"visual studio
1.185 brouard 6614: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6615: /PDB:"visual studio
6616: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6617: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6618: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6619: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6620: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6621: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6622: uiAccess='false'"
6623: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6624: /NOLOGO /TLBID:1
6625: */
1.177 brouard 6626: #if defined __INTEL_COMPILER
1.178 brouard 6627: #if defined(__GNUC__)
6628: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6629: #endif
1.177 brouard 6630: #elif defined(__GNUC__)
1.179 brouard 6631: #ifndef __APPLE__
1.174 brouard 6632: #include <gnu/libc-version.h> /* Only on gnu */
1.179 brouard 6633: #endif
1.177 brouard 6634: struct utsname sysInfo;
1.178 brouard 6635: int cross = CROSS;
6636: if (cross){
6637: printf("Cross-");
1.191 brouard 6638: if(logged) fprintf(ficlog, "Cross-");
1.178 brouard 6639: }
1.174 brouard 6640: #endif
6641:
1.171 brouard 6642: #include <stdint.h>
1.178 brouard 6643:
1.191 brouard 6644: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169 brouard 6645: #if defined(__clang__)
1.191 brouard 6646: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
1.169 brouard 6647: #endif
6648: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191 brouard 6649: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169 brouard 6650: #endif
6651: #if defined(__GNUC__) || defined(__GNUG__)
1.191 brouard 6652: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169 brouard 6653: #endif
6654: #if defined(__HP_cc) || defined(__HP_aCC)
1.191 brouard 6655: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169 brouard 6656: #endif
6657: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191 brouard 6658: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169 brouard 6659: #endif
6660: #if defined(_MSC_VER)
1.191 brouard 6661: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169 brouard 6662: #endif
6663: #if defined(__PGI)
1.191 brouard 6664: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169 brouard 6665: #endif
6666: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191 brouard 6667: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 6668: #endif
1.191 brouard 6669: printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169 brouard 6670:
1.167 brouard 6671: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6672: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6673: // Windows (x64 and x86)
1.191 brouard 6674: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167 brouard 6675: #elif __unix__ // all unices, not all compilers
6676: // Unix
1.191 brouard 6677: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167 brouard 6678: #elif __linux__
6679: // linux
1.191 brouard 6680: printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167 brouard 6681: #elif __APPLE__
1.174 brouard 6682: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191 brouard 6683: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167 brouard 6684: #endif
6685:
6686: /* __MINGW32__ */
6687: /* __CYGWIN__ */
6688: /* __MINGW64__ */
6689: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6690: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6691: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6692: /* _WIN64 // Defined for applications for Win64. */
6693: /* _M_X64 // Defined for compilations that target x64 processors. */
6694: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 6695:
1.167 brouard 6696: #if UINTPTR_MAX == 0xffffffff
1.191 brouard 6697: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167 brouard 6698: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191 brouard 6699: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167 brouard 6700: #else
1.191 brouard 6701: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167 brouard 6702: #endif
6703:
1.169 brouard 6704: #if defined(__GNUC__)
6705: # if defined(__GNUC_PATCHLEVEL__)
6706: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6707: + __GNUC_MINOR__ * 100 \
6708: + __GNUC_PATCHLEVEL__)
6709: # else
6710: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6711: + __GNUC_MINOR__ * 100)
6712: # endif
1.174 brouard 6713: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191 brouard 6714: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176 brouard 6715:
6716: if (uname(&sysInfo) != -1) {
6717: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191 brouard 6718: 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 6719: }
6720: else
6721: perror("uname() error");
1.179 brouard 6722: //#ifndef __INTEL_COMPILER
6723: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174 brouard 6724: printf("GNU libc version: %s\n", gnu_get_libc_version());
1.191 brouard 6725: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177 brouard 6726: #endif
1.169 brouard 6727: #endif
1.172 brouard 6728:
6729: // void main()
6730: // {
1.169 brouard 6731: #if defined(_MSC_VER)
1.174 brouard 6732: if (IsWow64()){
1.191 brouard 6733: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6734: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174 brouard 6735: }
6736: else{
1.191 brouard 6737: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6738: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174 brouard 6739: }
1.172 brouard 6740: // printf("\nPress Enter to continue...");
6741: // getchar();
6742: // }
6743:
1.169 brouard 6744: #endif
6745:
1.167 brouard 6746:
6747: }
1.136 brouard 6748:
1.209 brouard 6749: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180 brouard 6750: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6751: int i, j, k, i1 ;
1.202 brouard 6752: /* double ftolpl = 1.e-10; */
1.180 brouard 6753: double age, agebase, agelim;
1.203 brouard 6754: double tot;
1.180 brouard 6755:
1.202 brouard 6756: strcpy(filerespl,"PL_");
6757: strcat(filerespl,fileresu);
6758: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6759: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6760: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6761: }
6762: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6763: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6764: pstamp(ficrespl);
1.203 brouard 6765: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202 brouard 6766: fprintf(ficrespl,"#Age ");
6767: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6768: fprintf(ficrespl,"\n");
1.180 brouard 6769:
6770: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6771:
6772: agebase=ageminpar;
6773: agelim=agemaxpar;
6774:
6775: i1=pow(2,cptcoveff);
6776: if (cptcovn < 1){i1=1;}
6777:
6778: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6779: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6780: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6781: k=k+1;
6782: /* to clean */
1.198 brouard 6783: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200 brouard 6784: fprintf(ficrespl,"#******");
6785: printf("#******");
6786: fprintf(ficlog,"#******");
1.180 brouard 6787: for(j=1;j<=cptcoveff;j++) {
1.198 brouard 6788: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6789: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6790: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6791: }
6792: fprintf(ficrespl,"******\n");
6793: printf("******\n");
6794: fprintf(ficlog,"******\n");
6795:
6796: fprintf(ficrespl,"#Age ");
6797: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 6798: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180 brouard 6799: }
1.203 brouard 6800: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6801: fprintf(ficrespl,"Total Years_to_converge\n");
1.180 brouard 6802:
6803: for (age=agebase; age<=agelim; age++){
6804: /* for (age=agebase; age<=agebase; age++){ */
1.209 brouard 6805: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180 brouard 6806: fprintf(ficrespl,"%.0f ",age );
6807: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6808: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203 brouard 6809: tot=0.;
6810: for(i=1; i<=nlstate;i++){
6811: tot += prlim[i][i];
1.180 brouard 6812: fprintf(ficrespl," %.5f", prlim[i][i]);
1.203 brouard 6813: }
1.209 brouard 6814: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180 brouard 6815: } /* Age */
6816: /* was end of cptcod */
6817: } /* cptcov */
1.184 brouard 6818: return 0;
1.180 brouard 6819: }
6820:
6821: int hPijx(double *p, int bage, int fage){
6822: /*------------- h Pij x at various ages ------------*/
6823:
6824: int stepsize;
6825: int agelim;
6826: int hstepm;
6827: int nhstepm;
6828: int h, i, i1, j, k;
6829:
6830: double agedeb;
6831: double ***p3mat;
6832:
1.201 brouard 6833: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
1.180 brouard 6834: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6835: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6836: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6837: }
6838: printf("Computing pij: result on file '%s' \n", filerespij);
6839: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6840:
6841: stepsize=(int) (stepm+YEARM-1)/YEARM;
6842: /*if (stepm<=24) stepsize=2;*/
6843:
6844: agelim=AGESUP;
6845: hstepm=stepsize*YEARM; /* Every year of age */
6846: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6847:
6848: /* hstepm=1; aff par mois*/
6849: pstamp(ficrespij);
6850: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6851: i1= pow(2,cptcoveff);
1.183 brouard 6852: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6853: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6854: /* k=k+1; */
6855: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6856: fprintf(ficrespij,"\n#****** ");
6857: for(j=1;j<=cptcoveff;j++)
1.198 brouard 6858: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183 brouard 6859: fprintf(ficrespij,"******\n");
6860:
6861: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6862: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6863: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6864:
6865: /* nhstepm=nhstepm*YEARM; aff par mois*/
1.180 brouard 6866:
1.183 brouard 6867: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6868: oldm=oldms;savm=savms;
6869: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6870: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6871: for(i=1; i<=nlstate;i++)
6872: for(j=1; j<=nlstate+ndeath;j++)
6873: fprintf(ficrespij," %1d-%1d",i,j);
6874: fprintf(ficrespij,"\n");
6875: for (h=0; h<=nhstepm; h++){
6876: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6877: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180 brouard 6878: for(i=1; i<=nlstate;i++)
6879: for(j=1; j<=nlstate+ndeath;j++)
1.183 brouard 6880: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180 brouard 6881: fprintf(ficrespij,"\n");
6882: }
1.183 brouard 6883: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6884: fprintf(ficrespij,"\n");
6885: }
1.180 brouard 6886: /*}*/
6887: }
1.184 brouard 6888: return 0;
1.180 brouard 6889: }
6890:
6891:
1.136 brouard 6892: /***********************************************/
6893: /**************** Main Program *****************/
6894: /***********************************************/
6895:
6896: int main(int argc, char *argv[])
6897: {
6898: #ifdef GSL
6899: const gsl_multimin_fminimizer_type *T;
6900: size_t iteri = 0, it;
6901: int rval = GSL_CONTINUE;
6902: int status = GSL_SUCCESS;
6903: double ssval;
6904: #endif
6905: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 6906: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209 brouard 6907: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164 brouard 6908: int jj, ll, li, lj, lk;
1.136 brouard 6909: int numlinepar=0; /* Current linenumber of parameter file */
1.197 brouard 6910: int num_filled;
1.136 brouard 6911: int itimes;
6912: int NDIM=2;
6913: int vpopbased=0;
6914:
1.164 brouard 6915: char ca[32], cb[32];
1.136 brouard 6916: /* FILE *fichtm; *//* Html File */
6917: /* FILE *ficgp;*/ /*Gnuplot File */
6918: struct stat info;
1.191 brouard 6919: double agedeb=0.;
1.194 brouard 6920:
6921: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136 brouard 6922:
1.165 brouard 6923: double fret;
1.191 brouard 6924: double dum=0.; /* Dummy variable */
1.136 brouard 6925: double ***p3mat;
6926: double ***mobaverage;
1.164 brouard 6927:
6928: char line[MAXLINE];
1.197 brouard 6929: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6930:
6931: char model[MAXLINE], modeltemp[MAXLINE];
1.136 brouard 6932: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 6933: char *tok, *val; /* pathtot */
1.136 brouard 6934: int firstobs=1, lastobs=10;
1.195 brouard 6935: int c, h , cpt, c2;
1.191 brouard 6936: int jl=0;
6937: int i1, j1, jk, stepsize=0;
1.194 brouard 6938: int count=0;
6939:
1.164 brouard 6940: int *tab;
1.136 brouard 6941: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6942: int mobilav=0,popforecast=0;
1.191 brouard 6943: int hstepm=0, nhstepm=0;
1.136 brouard 6944: int agemortsup;
6945: float sumlpop=0.;
6946: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6947: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6948:
1.191 brouard 6949: double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136 brouard 6950: double ftolpl=FTOL;
6951: double **prlim;
6952: double ***param; /* Matrix of parameters */
6953: double *p;
6954: double **matcov; /* Matrix of covariance */
1.203 brouard 6955: double **hess; /* Hessian matrix */
1.136 brouard 6956: double ***delti3; /* Scale */
6957: double *delti; /* Scale */
6958: double ***eij, ***vareij;
6959: double **varpl; /* Variances of prevalence limits by age */
6960: double *epj, vepp;
1.164 brouard 6961:
1.136 brouard 6962: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6963: double **ximort;
1.145 brouard 6964: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 6965: int *dcwave;
6966:
1.164 brouard 6967: char z[1]="c";
1.136 brouard 6968:
6969: /*char *strt;*/
6970: char strtend[80];
1.126 brouard 6971:
1.164 brouard 6972:
1.126 brouard 6973: /* setlocale (LC_ALL, ""); */
6974: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6975: /* textdomain (PACKAGE); */
6976: /* setlocale (LC_CTYPE, ""); */
6977: /* setlocale (LC_MESSAGES, ""); */
6978:
6979: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 6980: rstart_time = time(NULL);
6981: /* (void) gettimeofday(&start_time,&tzp);*/
6982: start_time = *localtime(&rstart_time);
1.126 brouard 6983: curr_time=start_time;
1.157 brouard 6984: /*tml = *localtime(&start_time.tm_sec);*/
6985: /* strcpy(strstart,asctime(&tml)); */
6986: strcpy(strstart,asctime(&start_time));
1.126 brouard 6987:
6988: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 6989: /* tp.tm_sec = tp.tm_sec +86400; */
6990: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 6991: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6992: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6993: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 6994: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 6995: /* strt=asctime(&tmg); */
6996: /* printf("Time(after) =%s",strstart); */
6997: /* (void) time (&time_value);
6998: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6999: * tm = *localtime(&time_value);
7000: * strstart=asctime(&tm);
7001: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
7002: */
7003:
7004: nberr=0; /* Number of errors and warnings */
7005: nbwarn=0;
1.184 brouard 7006: #ifdef WIN32
7007: _getcwd(pathcd, size);
7008: #else
1.126 brouard 7009: getcwd(pathcd, size);
1.184 brouard 7010: #endif
1.191 brouard 7011: syscompilerinfo(0);
1.196 brouard 7012: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126 brouard 7013: if(argc <=1){
7014: printf("\nEnter the parameter file name: ");
1.205 brouard 7015: if(!fgets(pathr,FILENAMELENGTH,stdin)){
7016: printf("ERROR Empty parameter file name\n");
7017: goto end;
7018: }
1.126 brouard 7019: i=strlen(pathr);
7020: if(pathr[i-1]=='\n')
7021: pathr[i-1]='\0';
1.156 brouard 7022: i=strlen(pathr);
1.205 brouard 7023: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156 brouard 7024: pathr[i-1]='\0';
1.205 brouard 7025: }
7026: i=strlen(pathr);
7027: if( i==0 ){
7028: printf("ERROR Empty parameter file name\n");
7029: goto end;
7030: }
7031: for (tok = pathr; tok != NULL; ){
1.126 brouard 7032: printf("Pathr |%s|\n",pathr);
7033: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
7034: printf("val= |%s| pathr=%s\n",val,pathr);
7035: strcpy (pathtot, val);
7036: if(pathr[0] == '\0') break; /* Dirty */
7037: }
7038: }
7039: else{
7040: strcpy(pathtot,argv[1]);
7041: }
7042: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
7043: /*cygwin_split_path(pathtot,path,optionfile);
7044: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
7045: /* cutv(path,optionfile,pathtot,'\\');*/
7046:
7047: /* Split argv[0], imach program to get pathimach */
7048: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
7049: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7050: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7051: /* strcpy(pathimach,argv[0]); */
7052: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
7053: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
7054: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184 brouard 7055: #ifdef WIN32
7056: _chdir(path); /* Can be a relative path */
7057: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
7058: #else
1.126 brouard 7059: chdir(path); /* Can be a relative path */
1.184 brouard 7060: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
7061: #endif
7062: printf("Current directory %s!\n",pathcd);
1.126 brouard 7063: strcpy(command,"mkdir ");
7064: strcat(command,optionfilefiname);
7065: if((outcmd=system(command)) != 0){
1.169 brouard 7066: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 7067: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
7068: /* fclose(ficlog); */
7069: /* exit(1); */
7070: }
7071: /* if((imk=mkdir(optionfilefiname))<0){ */
7072: /* perror("mkdir"); */
7073: /* } */
7074:
7075: /*-------- arguments in the command line --------*/
7076:
1.186 brouard 7077: /* Main Log file */
1.126 brouard 7078: strcat(filelog, optionfilefiname);
7079: strcat(filelog,".log"); /* */
7080: if((ficlog=fopen(filelog,"w"))==NULL) {
7081: printf("Problem with logfile %s\n",filelog);
7082: goto end;
7083: }
7084: fprintf(ficlog,"Log filename:%s\n",filelog);
1.197 brouard 7085: fprintf(ficlog,"Version %s %s",version,fullversion);
1.126 brouard 7086: fprintf(ficlog,"\nEnter the parameter file name: \n");
7087: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
7088: path=%s \n\
7089: optionfile=%s\n\
7090: optionfilext=%s\n\
1.156 brouard 7091: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 7092:
1.197 brouard 7093: syscompilerinfo(1);
1.167 brouard 7094:
1.126 brouard 7095: printf("Local time (at start):%s",strstart);
7096: fprintf(ficlog,"Local time (at start): %s",strstart);
7097: fflush(ficlog);
7098: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 7099: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 7100:
7101: /* */
7102: strcpy(fileres,"r");
7103: strcat(fileres, optionfilefiname);
1.201 brouard 7104: strcat(fileresu, optionfilefiname); /* Without r in front */
1.126 brouard 7105: strcat(fileres,".txt"); /* Other files have txt extension */
1.201 brouard 7106: strcat(fileresu,".txt"); /* Other files have txt extension */
1.126 brouard 7107:
1.186 brouard 7108: /* Main ---------arguments file --------*/
1.126 brouard 7109:
7110: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 7111: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7112: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 7113: fflush(ficlog);
1.149 brouard 7114: /* goto end; */
7115: exit(70);
1.126 brouard 7116: }
7117:
7118:
7119:
7120: strcpy(filereso,"o");
1.201 brouard 7121: strcat(filereso,fileresu);
1.126 brouard 7122: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
7123: printf("Problem with Output resultfile: %s\n", filereso);
7124: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
7125: fflush(ficlog);
7126: goto end;
7127: }
7128:
7129: /* Reads comments: lines beginning with '#' */
7130: numlinepar=0;
1.197 brouard 7131:
7132: /* First parameter line */
7133: while(fgets(line, MAXLINE, ficpar)) {
7134: /* If line starts with a # it is a comment */
7135: if (line[0] == '#') {
7136: numlinepar++;
7137: fputs(line,stdout);
7138: fputs(line,ficparo);
7139: fputs(line,ficlog);
7140: continue;
7141: }else
7142: break;
7143: }
7144: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
7145: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
7146: if (num_filled != 5) {
7147: printf("Should be 5 parameters\n");
7148: }
1.126 brouard 7149: numlinepar++;
1.197 brouard 7150: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
7151: }
7152: /* Second parameter line */
7153: while(fgets(line, MAXLINE, ficpar)) {
7154: /* If line starts with a # it is a comment */
7155: if (line[0] == '#') {
7156: numlinepar++;
7157: fputs(line,stdout);
7158: fputs(line,ficparo);
7159: fputs(line,ficlog);
7160: continue;
7161: }else
7162: break;
7163: }
7164: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
7165: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7166: if (num_filled != 8) {
1.209 brouard 7167: 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");
7168: printf("but line=%s\n",line);
1.197 brouard 7169: }
7170: 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 7171: }
1.203 brouard 7172: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209 brouard 7173: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197 brouard 7174: /* Third parameter line */
7175: while(fgets(line, MAXLINE, ficpar)) {
7176: /* If line starts with a # it is a comment */
7177: if (line[0] == '#') {
7178: numlinepar++;
7179: fputs(line,stdout);
7180: fputs(line,ficparo);
7181: fputs(line,ficlog);
7182: continue;
7183: }else
7184: break;
7185: }
1.201 brouard 7186: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7187: if (num_filled == 0)
7188: model[0]='\0';
7189: else if (num_filled != 1){
1.197 brouard 7190: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7191: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7192: model[0]='\0';
7193: goto end;
7194: }
7195: else{
7196: if (model[0]=='+'){
7197: for(i=1; i<=strlen(model);i++)
7198: modeltemp[i-1]=model[i];
1.201 brouard 7199: strcpy(model,modeltemp);
1.197 brouard 7200: }
7201: }
1.199 brouard 7202: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203 brouard 7203: printf("model=1+age+%s\n",model);fflush(stdout);
1.197 brouard 7204: }
7205: /* 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); */
7206: /* numlinepar=numlinepar+3; /\* In general *\/ */
7207: /* 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 7208: 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);
7209: 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 7210: fflush(ficlog);
1.190 brouard 7211: /* if(model[0]=='#'|| model[0]== '\0'){ */
7212: if(model[0]=='#'){
1.187 brouard 7213: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7214: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7215: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7216: if(mle != -1){
7217: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7218: exit(1);
7219: }
7220: }
1.126 brouard 7221: while((c=getc(ficpar))=='#' && c!= EOF){
7222: ungetc(c,ficpar);
7223: fgets(line, MAXLINE, ficpar);
7224: numlinepar++;
1.195 brouard 7225: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7226: z[0]=line[1];
7227: }
7228: /* printf("****line [1] = %c \n",line[1]); */
1.141 brouard 7229: fputs(line, stdout);
7230: //puts(line);
1.126 brouard 7231: fputs(line,ficparo);
7232: fputs(line,ficlog);
7233: }
7234: ungetc(c,ficpar);
7235:
7236:
1.145 brouard 7237: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 7238: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7239: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7240: v1+v2*age+v2*v3 makes cptcovn = 3
7241: */
7242: if (strlen(model)>1)
1.187 brouard 7243: 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 7244: else
1.187 brouard 7245: ncovmodel=2; /* Constant and age */
1.133 brouard 7246: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7247: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 7248: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7249: 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);
7250: 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);
7251: fflush(stdout);
7252: fclose (ficlog);
7253: goto end;
7254: }
1.126 brouard 7255: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7256: delti=delti3[1][1];
7257: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7258: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7259: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191 brouard 7260: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7261: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7262: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7263: fclose (ficparo);
7264: fclose (ficlog);
7265: goto end;
7266: exit(0);
7267: }
1.186 brouard 7268: else if(mle==-3) { /* Main Wizard */
1.126 brouard 7269: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192 brouard 7270: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7271: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126 brouard 7272: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7273: matcov=matrix(1,npar,1,npar);
1.203 brouard 7274: hess=matrix(1,npar,1,npar);
1.126 brouard 7275: }
7276: else{
1.145 brouard 7277: /* Read guessed parameters */
1.126 brouard 7278: /* Reads comments: lines beginning with '#' */
7279: while((c=getc(ficpar))=='#' && c!= EOF){
7280: ungetc(c,ficpar);
7281: fgets(line, MAXLINE, ficpar);
7282: numlinepar++;
1.141 brouard 7283: fputs(line,stdout);
1.126 brouard 7284: fputs(line,ficparo);
7285: fputs(line,ficlog);
7286: }
7287: ungetc(c,ficpar);
7288:
7289: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7290: for(i=1; i <=nlstate; i++){
7291: j=0;
7292: for(jj=1; jj <=nlstate+ndeath; jj++){
7293: if(jj==i) continue;
7294: j++;
7295: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193 brouard 7296: if ((i1 != i) || (j1 != jj)){
1.126 brouard 7297: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7298: It might be a problem of design; if ncovcol and the model are correct\n \
7299: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7300: exit(1);
7301: }
7302: fprintf(ficparo,"%1d%1d",i1,j1);
7303: if(mle==1)
1.193 brouard 7304: printf("%1d%1d",i,jj);
7305: fprintf(ficlog,"%1d%1d",i,jj);
1.126 brouard 7306: for(k=1; k<=ncovmodel;k++){
7307: fscanf(ficpar," %lf",¶m[i][j][k]);
7308: if(mle==1){
7309: printf(" %lf",param[i][j][k]);
7310: fprintf(ficlog," %lf",param[i][j][k]);
7311: }
7312: else
7313: fprintf(ficlog," %lf",param[i][j][k]);
7314: fprintf(ficparo," %lf",param[i][j][k]);
7315: }
7316: fscanf(ficpar,"\n");
7317: numlinepar++;
7318: if(mle==1)
7319: printf("\n");
7320: fprintf(ficlog,"\n");
7321: fprintf(ficparo,"\n");
7322: }
7323: }
7324: fflush(ficlog);
7325:
1.145 brouard 7326: /* Reads scales values */
1.126 brouard 7327: p=param[1][1];
7328:
7329: /* Reads comments: lines beginning with '#' */
7330: while((c=getc(ficpar))=='#' && c!= EOF){
7331: ungetc(c,ficpar);
7332: fgets(line, MAXLINE, ficpar);
7333: numlinepar++;
1.141 brouard 7334: fputs(line,stdout);
1.126 brouard 7335: fputs(line,ficparo);
7336: fputs(line,ficlog);
7337: }
7338: ungetc(c,ficpar);
7339:
7340: for(i=1; i <=nlstate; i++){
7341: for(j=1; j <=nlstate+ndeath-1; j++){
7342: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 7343: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 7344: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7345: exit(1);
7346: }
7347: printf("%1d%1d",i,j);
7348: fprintf(ficparo,"%1d%1d",i1,j1);
7349: fprintf(ficlog,"%1d%1d",i1,j1);
7350: for(k=1; k<=ncovmodel;k++){
7351: fscanf(ficpar,"%le",&delti3[i][j][k]);
7352: printf(" %le",delti3[i][j][k]);
7353: fprintf(ficparo," %le",delti3[i][j][k]);
7354: fprintf(ficlog," %le",delti3[i][j][k]);
7355: }
7356: fscanf(ficpar,"\n");
7357: numlinepar++;
7358: printf("\n");
7359: fprintf(ficparo,"\n");
7360: fprintf(ficlog,"\n");
7361: }
7362: }
7363: fflush(ficlog);
7364:
1.145 brouard 7365: /* Reads covariance matrix */
1.126 brouard 7366: delti=delti3[1][1];
7367:
7368:
7369: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7370:
7371: /* Reads comments: lines beginning with '#' */
7372: while((c=getc(ficpar))=='#' && c!= EOF){
7373: ungetc(c,ficpar);
7374: fgets(line, MAXLINE, ficpar);
7375: numlinepar++;
1.141 brouard 7376: fputs(line,stdout);
1.126 brouard 7377: fputs(line,ficparo);
7378: fputs(line,ficlog);
7379: }
7380: ungetc(c,ficpar);
7381:
7382: matcov=matrix(1,npar,1,npar);
1.203 brouard 7383: hess=matrix(1,npar,1,npar);
1.131 brouard 7384: for(i=1; i <=npar; i++)
7385: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7386:
1.194 brouard 7387: /* Scans npar lines */
1.126 brouard 7388: for(i=1; i <=npar; i++){
1.194 brouard 7389: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7390: if(count != 3){
7391: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7392: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7393: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7394: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7395: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7396: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7397: exit(1);
7398: }else
1.126 brouard 7399: if(mle==1)
1.194 brouard 7400: printf("%1d%1d%1d",i1,j1,jk);
7401: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7402: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126 brouard 7403: for(j=1; j <=i; j++){
7404: fscanf(ficpar," %le",&matcov[i][j]);
7405: if(mle==1){
7406: printf(" %.5le",matcov[i][j]);
7407: }
7408: fprintf(ficlog," %.5le",matcov[i][j]);
7409: fprintf(ficparo," %.5le",matcov[i][j]);
7410: }
7411: fscanf(ficpar,"\n");
7412: numlinepar++;
7413: if(mle==1)
7414: printf("\n");
7415: fprintf(ficlog,"\n");
7416: fprintf(ficparo,"\n");
7417: }
1.194 brouard 7418: /* End of read covariance matrix npar lines */
1.126 brouard 7419: for(i=1; i <=npar; i++)
7420: for(j=i+1;j<=npar;j++)
7421: matcov[i][j]=matcov[j][i];
7422:
7423: if(mle==1)
7424: printf("\n");
7425: fprintf(ficlog,"\n");
7426:
7427: fflush(ficlog);
7428:
7429: /*-------- Rewriting parameter file ----------*/
7430: strcpy(rfileres,"r"); /* "Rparameterfile */
7431: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7432: strcat(rfileres,"."); /* */
7433: strcat(rfileres,optionfilext); /* Other files have txt extension */
7434: if((ficres =fopen(rfileres,"w"))==NULL) {
1.201 brouard 7435: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7436: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126 brouard 7437: }
7438: fprintf(ficres,"#%s\n",version);
7439: } /* End of mle != -3 */
7440:
1.186 brouard 7441: /* Main data
7442: */
1.126 brouard 7443: n= lastobs;
7444: num=lvector(1,n);
7445: moisnais=vector(1,n);
7446: annais=vector(1,n);
7447: moisdc=vector(1,n);
7448: andc=vector(1,n);
7449: agedc=vector(1,n);
7450: cod=ivector(1,n);
7451: weight=vector(1,n);
7452: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7453: mint=matrix(1,maxwav,1,n);
7454: anint=matrix(1,maxwav,1,n);
1.131 brouard 7455: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 7456: tab=ivector(1,NCOVMAX);
1.144 brouard 7457: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192 brouard 7458: 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 7459:
1.136 brouard 7460: /* Reads data from file datafile */
7461: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7462: goto end;
7463:
7464: /* Calculation of the number of parameters from char model */
1.137 brouard 7465: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7466: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7467: k=3 V4 Tvar[k=3]= 4 (from V4)
7468: k=2 V1 Tvar[k=2]= 1 (from V1)
7469: k=1 Tvar[1]=2 (from V2)
7470: */
7471: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7472: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7473: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7474: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7475: */
7476: /* For model-covariate k tells which data-covariate to use but
7477: because this model-covariate is a construction we invent a new column
7478: ncovcol + k1
7479: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7480: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 7481: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 7482: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7483: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7484: */
1.145 brouard 7485: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7486: 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 7487: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7488: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 7489: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 7490: 4 covariates (3 plus signs)
7491: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7492: */
1.136 brouard 7493:
1.186 brouard 7494: /* Main decodemodel */
7495:
1.187 brouard 7496:
1.136 brouard 7497: if(decodemodel(model, lastobs) == 1)
7498: goto end;
7499:
1.137 brouard 7500: if((double)(lastobs-imx)/(double)imx > 1.10){
7501: nbwarn++;
7502: 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);
7503: 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);
7504: }
1.136 brouard 7505: /* if(mle==1){*/
1.137 brouard 7506: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7507: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 7508: }
7509:
7510: /*-calculation of age at interview from date of interview and age at death -*/
7511: agev=matrix(1,maxwav,1,imx);
7512:
7513: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7514: goto end;
7515:
1.126 brouard 7516:
1.136 brouard 7517: agegomp=(int)agemin;
7518: free_vector(moisnais,1,n);
7519: free_vector(annais,1,n);
1.126 brouard 7520: /* free_matrix(mint,1,maxwav,1,n);
7521: free_matrix(anint,1,maxwav,1,n);*/
7522: free_vector(moisdc,1,n);
7523: free_vector(andc,1,n);
1.145 brouard 7524: /* */
7525:
1.126 brouard 7526: wav=ivector(1,imx);
7527: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7528: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7529: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7530:
7531: /* Concatenates waves */
7532: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 7533: /* */
7534:
1.126 brouard 7535: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7536:
7537: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7538: ncodemax[1]=1;
1.145 brouard 7539: Ndum =ivector(-1,NCOVMAX);
1.187 brouard 7540: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145 brouard 7541: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211 brouard 7542: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186 brouard 7543: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211 brouard 7544: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145 brouard 7545:
1.200 brouard 7546: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198 brouard 7547: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186 brouard 7548: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211 brouard 7549: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
7550: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
7551: * (currently 0 or 1) in the data.
7552: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
7553: * corresponding modality (h,j).
7554: */
7555:
1.145 brouard 7556: h=0;
7557:
7558:
7559: /*if (cptcovn > 0) */
1.126 brouard 7560:
1.145 brouard 7561:
1.126 brouard 7562: m=pow(2,cptcoveff);
7563:
1.144 brouard 7564: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211 brouard 7565: * For k=4 covariates, h goes from 1 to m=2**k
7566: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
7567: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
1.186 brouard 7568: * h\k 1 2 3 4
1.143 brouard 7569: *______________________________
7570: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7571: * 2 2 1 1 1
7572: * 3 i=2 1 2 1 1
7573: * 4 2 2 1 1
7574: * 5 i=3 1 i=2 1 2 1
7575: * 6 2 1 2 1
7576: * 7 i=4 1 2 2 1
7577: * 8 2 2 2 1
1.197 brouard 7578: * 9 i=5 1 i=3 1 i=2 1 2
7579: * 10 2 1 1 2
7580: * 11 i=6 1 2 1 2
7581: * 12 2 2 1 2
7582: * 13 i=7 1 i=4 1 2 2
7583: * 14 2 1 2 2
7584: * 15 i=8 1 2 2 2
7585: * 16 2 2 2 2
1.143 brouard 7586: */
1.212 ! brouard 7587: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211 brouard 7588: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
7589: * and the value of each covariate?
7590: * V1=1, V2=1, V3=2, V4=1 ?
7591: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
7592: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
7593: * In order to get the real value in the data, we use nbcode
7594: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
7595: * We are keeping this crazy system in order to be able (in the future?)
7596: * to have more than 2 values (0 or 1) for a covariate.
7597: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7598: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
7599: * bbbbbbbb
7600: * 76543210
7601: * h-1 00000101 (6-1=5)
7602: *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
7603: * &
7604: * 1 00000001 (1)
7605: * 00000001 = 1 & ((h-1) >> (k-1))
7606: * +1= 00000010 =2
7607: *
7608: * h=14, k=3 => h'=h-1=13, k'=k-1=2
7609: * h' 1101 =2^3+2^2+0x2^1+2^0
7610: * >>k' 11
7611: * & 00000001
7612: * = 00000001
7613: * +1 = 00000010=2 = codtabm(14,3)
7614: * Reverse h=6 and m=16?
7615: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
7616: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
7617: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
7618: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
7619: * V3=decodtabm(14,3,2**4)=2
7620: * h'=13 1101 =2^3+2^2+0x2^1+2^0
7621: *(h-1) >> (j-1) 0011 =13 >> 2
7622: * &1 000000001
7623: * = 000000001
7624: * +1= 000000010 =2
7625: * 2211
7626: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
7627: * V3=2
7628: */
7629:
1.202 brouard 7630: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7631: /* /\* printf("h=%2d ", h); *\/ */
7632: /* /\* for(k=1; k <=10; k++){ *\/ */
7633: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7634: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7635: /* /\* } *\/ */
7636: /* /\* printf("\n"); *\/ */
7637: /* } */
1.197 brouard 7638: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7639: /* 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 *\/ */
7640: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7641: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7642: /* h++; */
7643: /* if (h>m) */
7644: /* h=1; */
7645: /* codtab[h][k]=j; */
7646: /* /\* codtab[12][3]=1; *\/ */
7647: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7648: /* /\* 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]]); *\/ */
7649: /* } */
7650: /* } */
7651: /* } */
7652: /* } */
1.126 brouard 7653: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7654: codtab[1][2]=1;codtab[2][2]=2; */
1.197 brouard 7655: /* for(i=1; i <=m ;i++){ */
7656: /* for(k=1; k <=cptcovn; k++){ */
7657: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7658: /* } */
7659: /* printf("\n"); */
7660: /* } */
7661: /* scanf("%d",i);*/
1.145 brouard 7662:
7663: free_ivector(Ndum,-1,NCOVMAX);
7664:
7665:
1.126 brouard 7666:
1.186 brouard 7667: /* Initialisation of ----------- gnuplot -------------*/
1.126 brouard 7668: strcpy(optionfilegnuplot,optionfilefiname);
7669: if(mle==-3)
1.201 brouard 7670: strcat(optionfilegnuplot,"-MORT_");
1.126 brouard 7671: strcat(optionfilegnuplot,".gp");
7672:
7673: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7674: printf("Problem with file %s",optionfilegnuplot);
7675: }
7676: else{
1.204 brouard 7677: fprintf(ficgp,"\n# IMaCh-%s\n", version);
1.126 brouard 7678: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 7679: //fprintf(ficgp,"set missing 'NaNq'\n");
7680: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 7681: }
7682: /* fclose(ficgp);*/
1.186 brouard 7683:
7684:
7685: /* Initialisation of --------- index.htm --------*/
1.126 brouard 7686:
7687: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7688: if(mle==-3)
1.201 brouard 7689: strcat(optionfilehtm,"-MORT_");
1.126 brouard 7690: strcat(optionfilehtm,".htm");
7691: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 7692: printf("Problem with %s \n",optionfilehtm);
7693: exit(0);
1.126 brouard 7694: }
7695:
7696: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7697: strcat(optionfilehtmcov,"-cov.htm");
7698: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7699: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7700: }
7701: else{
7702: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7703: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7704: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126 brouard 7705: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7706: }
7707:
1.204 brouard 7708: 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é-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</a></font><br> \
7709: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7710: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126 brouard 7711: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204 brouard 7712: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126 brouard 7713: \n\
7714: <hr size=\"2\" color=\"#EC5E5E\">\
7715: <ul><li><h4>Parameter files</h4>\n\
7716: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7717: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7718: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7719: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7720: - Date and time at start: %s</ul>\n",\
7721: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7722: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7723: fileres,fileres,\
7724: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7725: fflush(fichtm);
7726:
7727: strcpy(pathr,path);
7728: strcat(pathr,optionfilefiname);
1.184 brouard 7729: #ifdef WIN32
7730: _chdir(optionfilefiname); /* Move to directory named optionfile */
7731: #else
1.126 brouard 7732: chdir(optionfilefiname); /* Move to directory named optionfile */
1.184 brouard 7733: #endif
7734:
1.126 brouard 7735:
7736: /* Calculates basic frequencies. Computes observed prevalence at single age
7737: and prints on file fileres'p'. */
7738: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7739:
7740: fprintf(fichtm,"\n");
7741: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7742: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7743: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7744: imx,agemin,agemax,jmin,jmax,jmean);
7745: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7746: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7747: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7748: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7749: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7750:
7751:
7752: /* For Powell, parameters are in a vector p[] starting at p[1]
7753: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7754: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7755:
7756: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186 brouard 7757: /* For mortality only */
1.126 brouard 7758: if (mle==-3){
1.136 brouard 7759: ximort=matrix(1,NDIM,1,NDIM);
1.186 brouard 7760: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 7761: cens=ivector(1,n);
7762: ageexmed=vector(1,n);
7763: agecens=vector(1,n);
7764: dcwave=ivector(1,n);
7765:
7766: for (i=1; i<=imx; i++){
7767: dcwave[i]=-1;
7768: for (m=firstpass; m<=lastpass; m++)
7769: if (s[m][i]>nlstate) {
7770: dcwave[i]=m;
7771: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7772: break;
7773: }
7774: }
7775:
7776: for (i=1; i<=imx; i++) {
7777: if (wav[i]>0){
7778: ageexmed[i]=agev[mw[1][i]][i];
7779: j=wav[i];
7780: agecens[i]=1.;
7781:
7782: if (ageexmed[i]> 1 && wav[i] > 0){
7783: agecens[i]=agev[mw[j][i]][i];
7784: cens[i]= 1;
7785: }else if (ageexmed[i]< 1)
7786: cens[i]= -1;
7787: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7788: cens[i]=0 ;
7789: }
7790: else cens[i]=-1;
7791: }
7792:
7793: for (i=1;i<=NDIM;i++) {
7794: for (j=1;j<=NDIM;j++)
7795: ximort[i][j]=(i == j ? 1.0 : 0.0);
7796: }
7797:
1.145 brouard 7798: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 7799: /*printf("%lf %lf", p[1], p[2]);*/
7800:
7801:
1.136 brouard 7802: #ifdef GSL
7803: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 7804: #else
1.126 brouard 7805: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 7806: #endif
1.201 brouard 7807: strcpy(filerespow,"POW-MORT_");
7808: strcat(filerespow,fileresu);
1.126 brouard 7809: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7810: printf("Problem with resultfile: %s\n", filerespow);
7811: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7812: }
1.136 brouard 7813: #ifdef GSL
7814: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 7815: #else
1.126 brouard 7816: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 7817: #endif
1.126 brouard 7818: /* for (i=1;i<=nlstate;i++)
7819: for(j=1;j<=nlstate+ndeath;j++)
7820: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7821: */
7822: fprintf(ficrespow,"\n");
1.136 brouard 7823: #ifdef GSL
7824: /* gsl starts here */
7825: T = gsl_multimin_fminimizer_nmsimplex;
7826: gsl_multimin_fminimizer *sfm = NULL;
7827: gsl_vector *ss, *x;
7828: gsl_multimin_function minex_func;
7829:
7830: /* Initial vertex size vector */
7831: ss = gsl_vector_alloc (NDIM);
7832:
7833: if (ss == NULL){
7834: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7835: }
7836: /* Set all step sizes to 1 */
7837: gsl_vector_set_all (ss, 0.001);
7838:
7839: /* Starting point */
1.126 brouard 7840:
1.136 brouard 7841: x = gsl_vector_alloc (NDIM);
7842:
7843: if (x == NULL){
7844: gsl_vector_free(ss);
7845: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7846: }
7847:
7848: /* Initialize method and iterate */
7849: /* p[1]=0.0268; p[NDIM]=0.083; */
1.186 brouard 7850: /* gsl_vector_set(x, 0, 0.0268); */
7851: /* gsl_vector_set(x, 1, 0.083); */
1.136 brouard 7852: gsl_vector_set(x, 0, p[1]);
7853: gsl_vector_set(x, 1, p[2]);
7854:
7855: minex_func.f = &gompertz_f;
7856: minex_func.n = NDIM;
7857: minex_func.params = (void *)&p; /* ??? */
7858:
7859: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7860: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7861:
7862: printf("Iterations beginning .....\n\n");
7863: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7864:
7865: iteri=0;
7866: while (rval == GSL_CONTINUE){
7867: iteri++;
7868: status = gsl_multimin_fminimizer_iterate(sfm);
7869:
7870: if (status) printf("error: %s\n", gsl_strerror (status));
7871: fflush(0);
7872:
7873: if (status)
7874: break;
7875:
7876: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7877: ssval = gsl_multimin_fminimizer_size (sfm);
7878:
7879: if (rval == GSL_SUCCESS)
7880: printf ("converged to a local maximum at\n");
7881:
7882: printf("%5d ", iteri);
7883: for (it = 0; it < NDIM; it++){
7884: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7885: }
7886: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7887: }
7888:
7889: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7890:
7891: gsl_vector_free(x); /* initial values */
7892: gsl_vector_free(ss); /* inital step size */
7893: for (it=0; it<NDIM; it++){
7894: p[it+1]=gsl_vector_get(sfm->x,it);
7895: fprintf(ficrespow," %.12lf", p[it]);
7896: }
7897: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7898: #endif
7899: #ifdef POWELL
7900: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7901: #endif
1.126 brouard 7902: fclose(ficrespow);
7903:
1.203 brouard 7904: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
1.126 brouard 7905:
7906: for(i=1; i <=NDIM; i++)
7907: for(j=i+1;j<=NDIM;j++)
7908: matcov[i][j]=matcov[j][i];
7909:
7910: printf("\nCovariance matrix\n ");
1.203 brouard 7911: fprintf(ficlog,"\nCovariance matrix\n ");
1.126 brouard 7912: for(i=1; i <=NDIM; i++) {
7913: for(j=1;j<=NDIM;j++){
7914: printf("%f ",matcov[i][j]);
1.203 brouard 7915: fprintf(ficlog,"%f ",matcov[i][j]);
1.126 brouard 7916: }
1.203 brouard 7917: printf("\n "); fprintf(ficlog,"\n ");
1.126 brouard 7918: }
7919:
7920: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193 brouard 7921: for (i=1;i<=NDIM;i++) {
1.126 brouard 7922: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193 brouard 7923: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7924: }
1.126 brouard 7925: lsurv=vector(1,AGESUP);
7926: lpop=vector(1,AGESUP);
7927: tpop=vector(1,AGESUP);
7928: lsurv[agegomp]=100000;
7929:
7930: for (k=agegomp;k<=AGESUP;k++) {
7931: agemortsup=k;
7932: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7933: }
7934:
7935: for (k=agegomp;k<agemortsup;k++)
7936: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7937:
7938: for (k=agegomp;k<agemortsup;k++){
7939: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7940: sumlpop=sumlpop+lpop[k];
7941: }
7942:
7943: tpop[agegomp]=sumlpop;
7944: for (k=agegomp;k<(agemortsup-3);k++){
7945: /* tpop[k+1]=2;*/
7946: tpop[k+1]=tpop[k]-lpop[k];
7947: }
7948:
7949:
7950: printf("\nAge lx qx dx Lx Tx e(x)\n");
7951: for (k=agegomp;k<(agemortsup-2);k++)
7952: 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]);
7953:
7954:
7955: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 7956: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7957: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7958: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7959: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7960: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7961: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7962: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7963: }else
1.201 brouard 7964: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7965: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126 brouard 7966: stepm, weightopt,\
7967: model,imx,p,matcov,agemortsup);
7968:
7969: free_vector(lsurv,1,AGESUP);
7970: free_vector(lpop,1,AGESUP);
7971: free_vector(tpop,1,AGESUP);
1.136 brouard 7972: #ifdef GSL
7973: free_ivector(cens,1,n);
7974: free_vector(agecens,1,n);
7975: free_ivector(dcwave,1,n);
7976: free_matrix(ximort,1,NDIM,1,NDIM);
7977: #endif
1.186 brouard 7978: } /* Endof if mle==-3 mortality only */
1.205 brouard 7979: /* Standard */
7980: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
7981: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7982: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132 brouard 7983: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 7984: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7985: for (k=1; k<=npar;k++)
7986: printf(" %d %8.5f",k,p[k]);
7987: printf("\n");
1.205 brouard 7988: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
7989: /* mlikeli uses func not funcone */
7990: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7991: }
7992: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
7993: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7994: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7995: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7996: }
7997: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126 brouard 7998: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7999: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8000: for (k=1; k<=npar;k++)
8001: printf(" %d %8.5f",k,p[k]);
8002: printf("\n");
8003:
8004: /*--------- results files --------------*/
1.192 brouard 8005: 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 8006:
8007:
8008: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8009: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8010: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8011: for(i=1,jk=1; i <=nlstate; i++){
8012: for(k=1; k <=(nlstate+ndeath); k++){
8013: if (k != i) {
8014: printf("%d%d ",i,k);
8015: fprintf(ficlog,"%d%d ",i,k);
8016: fprintf(ficres,"%1d%1d ",i,k);
8017: for(j=1; j <=ncovmodel; j++){
1.190 brouard 8018: printf("%12.7f ",p[jk]);
8019: fprintf(ficlog,"%12.7f ",p[jk]);
8020: fprintf(ficres,"%12.7f ",p[jk]);
1.126 brouard 8021: jk++;
8022: }
8023: printf("\n");
8024: fprintf(ficlog,"\n");
8025: fprintf(ficres,"\n");
8026: }
8027: }
8028: }
1.203 brouard 8029: if(mle != 0){
8030: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126 brouard 8031: ftolhess=ftol; /* Usually correct */
1.203 brouard 8032: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
8033: 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");
8034: 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");
8035: for(i=1,jk=1; i <=nlstate; i++){
8036: for(k=1; k <=(nlstate+ndeath); k++){
8037: if (k != i) {
8038: printf("%d%d ",i,k);
8039: fprintf(ficlog,"%d%d ",i,k);
8040: for(j=1; j <=ncovmodel; j++){
8041: 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]));
8042: 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]));
8043: jk++;
8044: }
8045: printf("\n");
8046: fprintf(ficlog,"\n");
1.193 brouard 8047: }
8048: }
8049: }
1.203 brouard 8050: } /* end of hesscov and Wald tests */
1.193 brouard 8051:
1.203 brouard 8052: /* */
1.126 brouard 8053: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
8054: printf("# Scales (for hessian or gradient estimation)\n");
8055: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
8056: for(i=1,jk=1; i <=nlstate; i++){
8057: for(j=1; j <=nlstate+ndeath; j++){
8058: if (j!=i) {
8059: fprintf(ficres,"%1d%1d",i,j);
8060: printf("%1d%1d",i,j);
8061: fprintf(ficlog,"%1d%1d",i,j);
8062: for(k=1; k<=ncovmodel;k++){
8063: printf(" %.5e",delti[jk]);
8064: fprintf(ficlog," %.5e",delti[jk]);
8065: fprintf(ficres," %.5e",delti[jk]);
8066: jk++;
8067: }
8068: printf("\n");
8069: fprintf(ficlog,"\n");
8070: fprintf(ficres,"\n");
8071: }
8072: }
8073: }
8074:
8075: 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 8076: if(mle >= 1) /* To big for the screen */
1.126 brouard 8077: 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");
8078: 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");
8079: /* # 121 Var(a12)\n\ */
8080: /* # 122 Cov(b12,a12) Var(b12)\n\ */
8081: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
8082: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
8083: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
8084: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
8085: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
8086: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
8087:
8088:
8089: /* Just to have a covariance matrix which will be more understandable
8090: even is we still don't want to manage dictionary of variables
8091: */
8092: for(itimes=1;itimes<=2;itimes++){
8093: jj=0;
8094: for(i=1; i <=nlstate; i++){
8095: for(j=1; j <=nlstate+ndeath; j++){
8096: if(j==i) continue;
8097: for(k=1; k<=ncovmodel;k++){
8098: jj++;
8099: ca[0]= k+'a'-1;ca[1]='\0';
8100: if(itimes==1){
8101: if(mle>=1)
8102: printf("#%1d%1d%d",i,j,k);
8103: fprintf(ficlog,"#%1d%1d%d",i,j,k);
8104: fprintf(ficres,"#%1d%1d%d",i,j,k);
8105: }else{
8106: if(mle>=1)
8107: printf("%1d%1d%d",i,j,k);
8108: fprintf(ficlog,"%1d%1d%d",i,j,k);
8109: fprintf(ficres,"%1d%1d%d",i,j,k);
8110: }
8111: ll=0;
8112: for(li=1;li <=nlstate; li++){
8113: for(lj=1;lj <=nlstate+ndeath; lj++){
8114: if(lj==li) continue;
8115: for(lk=1;lk<=ncovmodel;lk++){
8116: ll++;
8117: if(ll<=jj){
8118: cb[0]= lk +'a'-1;cb[1]='\0';
8119: if(ll<jj){
8120: if(itimes==1){
8121: if(mle>=1)
8122: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8123: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8124: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8125: }else{
8126: if(mle>=1)
8127: printf(" %.5e",matcov[jj][ll]);
8128: fprintf(ficlog," %.5e",matcov[jj][ll]);
8129: fprintf(ficres," %.5e",matcov[jj][ll]);
8130: }
8131: }else{
8132: if(itimes==1){
8133: if(mle>=1)
8134: printf(" Var(%s%1d%1d)",ca,i,j);
8135: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
8136: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
8137: }else{
8138: if(mle>=1)
1.203 brouard 8139: printf(" %.7e",matcov[jj][ll]);
8140: fprintf(ficlog," %.7e",matcov[jj][ll]);
8141: fprintf(ficres," %.7e",matcov[jj][ll]);
1.126 brouard 8142: }
8143: }
8144: }
8145: } /* end lk */
8146: } /* end lj */
8147: } /* end li */
8148: if(mle>=1)
8149: printf("\n");
8150: fprintf(ficlog,"\n");
8151: fprintf(ficres,"\n");
8152: numlinepar++;
8153: } /* end k*/
8154: } /*end j */
8155: } /* end i */
8156: } /* end itimes */
8157:
8158: fflush(ficlog);
8159: fflush(ficres);
1.209 brouard 8160: while(fgets(line, MAXLINE, ficpar)) {
8161: /* If line starts with a # it is a comment */
8162: if (line[0] == '#') {
8163: numlinepar++;
1.141 brouard 8164: fputs(line,stdout);
1.126 brouard 8165: fputs(line,ficparo);
1.209 brouard 8166: fputs(line,ficlog);
8167: continue;
8168: }else
8169: break;
8170: }
8171:
8172: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
8173: /* ungetc(c,ficpar); */
8174: /* fgets(line, MAXLINE, ficpar); */
8175: /* fputs(line,stdout); */
8176: /* fputs(line,ficparo); */
8177: /* } */
8178: /* ungetc(c,ficpar); */
1.126 brouard 8179:
8180: estepm=0;
1.209 brouard 8181: 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){
8182:
8183: if (num_filled != 6) {
8184: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
8185: printf("but line=%s\n",line);
8186: goto end;
8187: }
8188: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
8189: }
8190: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8191: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8192:
8193: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126 brouard 8194: if (estepm==0 || estepm < stepm) estepm=stepm;
8195: if (fage <= 2) {
8196: bage = ageminpar;
8197: fage = agemaxpar;
8198: }
8199:
8200: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211 brouard 8201: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8202: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186 brouard 8203:
8204: /* Other stuffs, more or less useful */
1.126 brouard 8205: while((c=getc(ficpar))=='#' && c!= EOF){
8206: ungetc(c,ficpar);
8207: fgets(line, MAXLINE, ficpar);
1.141 brouard 8208: fputs(line,stdout);
1.126 brouard 8209: fputs(line,ficparo);
8210: }
8211: ungetc(c,ficpar);
8212:
8213: 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);
8214: 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);
8215: 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);
8216: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8217: 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);
8218:
8219: while((c=getc(ficpar))=='#' && c!= EOF){
8220: ungetc(c,ficpar);
8221: fgets(line, MAXLINE, ficpar);
1.141 brouard 8222: fputs(line,stdout);
1.126 brouard 8223: fputs(line,ficparo);
8224: }
8225: ungetc(c,ficpar);
8226:
8227:
8228: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8229: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8230:
8231: fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193 brouard 8232: fprintf(ficlog,"pop_based=%d\n",popbased);
1.126 brouard 8233: fprintf(ficparo,"pop_based=%d\n",popbased);
8234: fprintf(ficres,"pop_based=%d\n",popbased);
8235:
8236: while((c=getc(ficpar))=='#' && c!= EOF){
8237: ungetc(c,ficpar);
8238: fgets(line, MAXLINE, ficpar);
1.141 brouard 8239: fputs(line,stdout);
1.126 brouard 8240: fputs(line,ficparo);
8241: }
8242: ungetc(c,ficpar);
8243:
8244: 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);
8245: 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);
8246: 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);
8247: 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);
8248: 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);
8249: /* day and month of proj2 are not used but only year anproj2.*/
8250:
8251:
8252:
1.145 brouard 8253: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8254: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 8255:
8256: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194 brouard 8257: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8258: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8259: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8260: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8261: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8262: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8263: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8264: }else
1.211 brouard 8265: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126 brouard 8266:
1.201 brouard 8267: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211 brouard 8268: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.126 brouard 8269: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
8270:
8271: /*------------ free_vector -------------*/
8272: /* chdir(path); */
8273:
8274: free_ivector(wav,1,imx);
8275: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
8276: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
8277: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
8278: free_lvector(num,1,n);
8279: free_vector(agedc,1,n);
8280: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8281: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8282: fclose(ficparo);
8283: fclose(ficres);
8284:
8285:
1.186 brouard 8286: /* Other results (useful)*/
8287:
8288:
1.126 brouard 8289: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.180 brouard 8290: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8291: prlim=matrix(1,nlstate,1,nlstate);
1.209 brouard 8292: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126 brouard 8293: fclose(ficrespl);
8294:
1.145 brouard 8295: #ifdef FREEEXIT2
8296: #include "freeexit2.h"
8297: #endif
8298:
1.126 brouard 8299: /*------------- h Pij x at various ages ------------*/
1.180 brouard 8300: /*#include "hpijx.h"*/
8301: hPijx(p, bage, fage);
1.145 brouard 8302: fclose(ficrespij);
1.126 brouard 8303:
1.145 brouard 8304: /*-------------- Variance of one-step probabilities---*/
8305: k=1;
1.126 brouard 8306: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8307:
8308:
8309: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8310: for(i=1;i<=AGESUP;i++)
8311: for(j=1;j<=NCOVMAX;j++)
8312: for(k=1;k<=NCOVMAX;k++)
8313: probs[i][j][k]=0.;
8314:
8315: /*---------- Forecasting ------------------*/
8316: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8317: if(prevfcast==1){
8318: /* if(stepm ==1){*/
1.201 brouard 8319: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126 brouard 8320: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8321: /* } */
8322: /* else{ */
8323: /* erreur=108; */
8324: /* 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); */
8325: /* 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); */
8326: /* } */
8327: }
1.186 brouard 8328:
8329: /* ------ Other prevalence ratios------------ */
1.126 brouard 8330:
1.127 brouard 8331: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8332:
8333: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8334: /* 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",\
8335: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8336: */
1.126 brouard 8337:
1.127 brouard 8338: if (mobilav!=0) {
8339: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8340: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8341: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8342: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8343: }
1.126 brouard 8344: }
8345:
8346:
1.127 brouard 8347: /*---------- Health expectancies, no variances ------------*/
8348:
1.201 brouard 8349: strcpy(filerese,"E_");
8350: strcat(filerese,fileresu);
1.126 brouard 8351: if((ficreseij=fopen(filerese,"w"))==NULL) {
8352: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8353: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8354: }
1.208 brouard 8355: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8356: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145 brouard 8357: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8358: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8359:
8360: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 8361: fprintf(ficreseij,"\n#****** ");
8362: for(j=1;j<=cptcoveff;j++) {
1.200 brouard 8363: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127 brouard 8364: }
8365: fprintf(ficreseij,"******\n");
8366:
8367: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8368: oldm=oldms;savm=savms;
8369: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8370:
8371: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8372: /*}*/
1.127 brouard 8373: }
8374: fclose(ficreseij);
1.208 brouard 8375: printf("done evsij\n");fflush(stdout);
8376: fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127 brouard 8377:
8378: /*---------- Health expectancies and variances ------------*/
8379:
8380:
1.201 brouard 8381: strcpy(filerest,"T_");
8382: strcat(filerest,fileresu);
1.127 brouard 8383: if((ficrest=fopen(filerest,"w"))==NULL) {
8384: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8385: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8386: }
1.208 brouard 8387: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8388: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127 brouard 8389:
1.126 brouard 8390:
1.201 brouard 8391: strcpy(fileresstde,"STDE_");
8392: strcat(fileresstde,fileresu);
1.126 brouard 8393: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8394: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8395: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8396: }
1.208 brouard 8397: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8398: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126 brouard 8399:
1.201 brouard 8400: strcpy(filerescve,"CVE_");
8401: strcat(filerescve,fileresu);
1.126 brouard 8402: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8403: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8404: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8405: }
1.208 brouard 8406: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8407: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126 brouard 8408:
1.201 brouard 8409: strcpy(fileresv,"V_");
8410: strcat(fileresv,fileresu);
1.126 brouard 8411: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8412: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8413: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8414: }
1.208 brouard 8415: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8416: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126 brouard 8417:
1.145 brouard 8418: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8419: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8420:
8421: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208 brouard 8422: fprintf(ficrest,"\n#****** ");
8423: for(j=1;j<=cptcoveff;j++)
8424: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8425: fprintf(ficrest,"******\n");
8426:
8427: fprintf(ficresstdeij,"\n#****** ");
8428: fprintf(ficrescveij,"\n#****** ");
8429: for(j=1;j<=cptcoveff;j++) {
8430: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8431: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8432: }
8433: fprintf(ficresstdeij,"******\n");
8434: fprintf(ficrescveij,"******\n");
8435:
8436: fprintf(ficresvij,"\n#****** ");
8437: for(j=1;j<=cptcoveff;j++)
8438: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8439: fprintf(ficresvij,"******\n");
8440:
8441: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8442: oldm=oldms;savm=savms;
8443: printf(" cvevsij %d, ",k);
8444: fprintf(ficlog, " cvevsij %d, ",k);
8445: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8446: printf(" end cvevsij \n ");
8447: fprintf(ficlog, " end cvevsij \n ");
8448:
8449: /*
8450: */
8451: /* goto endfree; */
8452:
8453: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8454: pstamp(ficrest);
8455:
8456:
8457: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8458: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8459: cptcod= 0; /* To be deleted */
8460: printf("varevsij %d \n",vpopbased);
8461: fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209 brouard 8462: 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 8463: 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 ");
8464: if(vpopbased==1)
8465: 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);
8466: else
8467: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8468: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8469: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8470: fprintf(ficrest,"\n");
8471: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8472: epj=vector(1,nlstate+1);
8473: printf("Computing age specific period (stable) prevalences in each health state \n");
8474: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8475: for(age=bage; age <=fage ;age++){
1.209 brouard 8476: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208 brouard 8477: if (vpopbased==1) {
8478: if(mobilav ==0){
8479: for(i=1; i<=nlstate;i++)
8480: prlim[i][i]=probs[(int)age][i][k];
8481: }else{ /* mobilav */
8482: for(i=1; i<=nlstate;i++)
8483: prlim[i][i]=mobaverage[(int)age][i][k];
1.126 brouard 8484: }
1.208 brouard 8485: }
8486:
8487: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8488: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8489: /* printf(" age %4.0f ",age); */
8490: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8491: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8492: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8493: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8494: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126 brouard 8495: }
1.208 brouard 8496: epj[nlstate+1] +=epj[j];
8497: }
8498: /* printf(" age %4.0f \n",age); */
8499:
8500: for(i=1, vepp=0.;i <=nlstate;i++)
8501: for(j=1;j <=nlstate;j++)
8502: vepp += vareij[i][j][(int)age];
8503: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8504: for(j=1;j <=nlstate;j++){
8505: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126 brouard 8506: }
1.208 brouard 8507: fprintf(ficrest,"\n");
1.126 brouard 8508: }
1.208 brouard 8509: } /* End vpopbased */
8510: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8511: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8512: free_vector(epj,1,nlstate+1);
8513: printf("done \n");fflush(stdout);
8514: fprintf(ficlog,"done\n");fflush(ficlog);
8515:
1.145 brouard 8516: /*}*/
1.208 brouard 8517: } /* End k */
1.126 brouard 8518: free_vector(weight,1,n);
1.145 brouard 8519: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 8520: free_imatrix(s,1,maxwav+1,1,n);
8521: free_matrix(anint,1,maxwav,1,n);
8522: free_matrix(mint,1,maxwav,1,n);
8523: free_ivector(cod,1,n);
8524: free_ivector(tab,1,NCOVMAX);
8525: fclose(ficresstdeij);
8526: fclose(ficrescveij);
8527: fclose(ficresvij);
8528: fclose(ficrest);
1.208 brouard 8529: printf("done Health expectancies\n");fflush(stdout);
8530: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126 brouard 8531: fclose(ficpar);
8532:
8533: /*------- Variance of period (stable) prevalence------*/
8534:
1.201 brouard 8535: strcpy(fileresvpl,"VPL_");
8536: strcat(fileresvpl,fileresu);
1.126 brouard 8537: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8538: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8539: exit(0);
8540: }
1.208 brouard 8541: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8542: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126 brouard 8543:
1.145 brouard 8544: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8545: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8546:
8547: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8548: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 8549: for(j=1;j<=cptcoveff;j++)
1.200 brouard 8550: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126 brouard 8551: fprintf(ficresvpl,"******\n");
8552:
8553: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8554: oldm=oldms;savm=savms;
1.209 brouard 8555: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126 brouard 8556: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 8557: /*}*/
1.126 brouard 8558: }
8559:
8560: fclose(ficresvpl);
1.208 brouard 8561: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8562: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126 brouard 8563:
8564: /*---------- End : free ----------------*/
8565: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8566: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8567: } /* mle==-3 arrives here for freeing */
1.164 brouard 8568: /* endfree:*/
1.141 brouard 8569: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 8570: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8571: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8572: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8573: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8574: free_matrix(covar,0,NCOVMAX,1,n);
8575: free_matrix(matcov,1,npar,1,npar);
1.203 brouard 8576: free_matrix(hess,1,npar,1,npar);
1.126 brouard 8577: /*free_vector(delti,1,npar);*/
8578: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8579: free_matrix(agev,1,maxwav,1,imx);
8580: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8581:
1.145 brouard 8582: free_ivector(ncodemax,1,NCOVMAX);
1.192 brouard 8583: free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145 brouard 8584: free_ivector(Tvar,1,NCOVMAX);
8585: free_ivector(Tprod,1,NCOVMAX);
8586: free_ivector(Tvaraff,1,NCOVMAX);
8587: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 8588:
8589: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200 brouard 8590: /* free_imatrix(codtab,1,100,1,10); */
1.126 brouard 8591: fflush(fichtm);
8592: fflush(ficgp);
8593:
8594:
8595: if((nberr >0) || (nbwarn>0)){
8596: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8597: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8598: }else{
8599: printf("End of Imach\n");
8600: fprintf(ficlog,"End of Imach\n");
8601: }
8602: printf("See log file on %s\n",filelog);
8603: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 8604: /*(void) gettimeofday(&end_time,&tzp);*/
8605: rend_time = time(NULL);
8606: end_time = *localtime(&rend_time);
8607: /* tml = *localtime(&end_time.tm_sec); */
8608: strcpy(strtend,asctime(&end_time));
1.126 brouard 8609: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8610: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 8611: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 8612:
1.157 brouard 8613: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8614: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8615: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 8616: /* printf("Total time was %d uSec.\n", total_usecs);*/
8617: /* if(fileappend(fichtm,optionfilehtm)){ */
8618: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8619: fclose(fichtm);
8620: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8621: fclose(fichtmcov);
8622: fclose(ficgp);
8623: fclose(ficlog);
8624: /*------ End -----------*/
8625:
8626:
8627: printf("Before Current directory %s!\n",pathcd);
1.184 brouard 8628: #ifdef WIN32
8629: if (_chdir(pathcd) != 0)
8630: printf("Can't move to directory %s!\n",path);
8631: if(_getcwd(pathcd,MAXLINE) > 0)
8632: #else
1.126 brouard 8633: if(chdir(pathcd) != 0)
1.184 brouard 8634: printf("Can't move to directory %s!\n", path);
8635: if (getcwd(pathcd, MAXLINE) > 0)
8636: #endif
1.126 brouard 8637: printf("Current directory %s!\n",pathcd);
8638: /*strcat(plotcmd,CHARSEPARATOR);*/
8639: sprintf(plotcmd,"gnuplot");
1.157 brouard 8640: #ifdef _WIN32
1.126 brouard 8641: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8642: #endif
8643: if(!stat(plotcmd,&info)){
1.158 brouard 8644: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8645: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 8646: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 8647: }else
8648: strcpy(pplotcmd,plotcmd);
1.157 brouard 8649: #ifdef __unix
1.126 brouard 8650: strcpy(plotcmd,GNUPLOTPROGRAM);
8651: if(!stat(plotcmd,&info)){
1.158 brouard 8652: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8653: }else
8654: strcpy(pplotcmd,plotcmd);
8655: #endif
8656: }else
8657: strcpy(pplotcmd,plotcmd);
8658:
8659: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 8660: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 8661:
8662: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 8663: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 8664: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 8665: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 8666: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 8667: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 8668: }
1.158 brouard 8669: printf(" Successful, please wait...");
1.126 brouard 8670: while (z[0] != 'q') {
8671: /* chdir(path); */
1.154 brouard 8672: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 8673: scanf("%s",z);
8674: /* if (z[0] == 'c') system("./imach"); */
8675: if (z[0] == 'e') {
1.158 brouard 8676: #ifdef __APPLE__
1.152 brouard 8677: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 8678: #elif __linux
8679: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 8680: #else
1.152 brouard 8681: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 8682: #endif
8683: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8684: system(pplotcmd);
1.126 brouard 8685: }
8686: else if (z[0] == 'g') system(plotcmd);
8687: else if (z[0] == 'q') exit(0);
8688: }
8689: end:
8690: while (z[0] != 'q') {
1.195 brouard 8691: printf("\nType q for exiting: "); fflush(stdout);
1.126 brouard 8692: scanf("%s",z);
8693: }
8694: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>