File:
[Local Repository] /
imach /
src /
imach.c
Revision
1.216:
download - view:
text,
annotated -
select for diffs
Fri Dec 18 17:32:11 2015 UTC (8 years, 8 months ago) by
brouard
Branches:
MAIN
CVS tags:
HEAD
Summary: 0.98r4 Warning and status=-2
Version 0.98r4 is now:
- displaying an error when status is -1, date of interview unknown and date of death known;
- permitting a status -2 when the vital status is unknown at a known date of right truncation.
Older changes concerning s=-2, dating from 2005 have been supersed.
1: /* $Id: imach.c,v 1.216 2015/12/18 17:32:11 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.216 2015/12/18 17:32:11 brouard
5: Summary: 0.98r4 Warning and status=-2
6:
7: Version 0.98r4 is now:
8: - displaying an error when status is -1, date of interview unknown and date of death known;
9: - permitting a status -2 when the vital status is unknown at a known date of right truncation.
10: Older changes concerning s=-2, dating from 2005 have been supersed.
11:
12: Revision 1.215 2015/12/16 08:52:24 brouard
13: Summary: 0.98r4 working
14:
15: Revision 1.214 2015/12/16 06:57:54 brouard
16: Summary: temporary not working
17:
18: Revision 1.213 2015/12/11 18:22:17 brouard
19: Summary: 0.98r4
20:
21: Revision 1.212 2015/11/21 12:47:24 brouard
22: Summary: minor typo
23:
24: Revision 1.211 2015/11/21 12:41:11 brouard
25: Summary: 0.98r3 with some graph of projected cross-sectional
26:
27: Author: Nicolas Brouard
28:
29: Revision 1.210 2015/11/18 17:41:20 brouard
30: Summary: Start working on projected prevalences
31:
32: Revision 1.209 2015/11/17 22:12:03 brouard
33: Summary: Adding ftolpl parameter
34: Author: N Brouard
35:
36: We had difficulties to get smoothed confidence intervals. It was due
37: to the period prevalence which wasn't computed accurately. The inner
38: parameter ftolpl is now an outer parameter of the .imach parameter
39: file after estepm. If ftolpl is small 1.e-4 and estepm too,
40: computation are long.
41:
42: Revision 1.208 2015/11/17 14:31:57 brouard
43: Summary: temporary
44:
45: Revision 1.207 2015/10/27 17:36:57 brouard
46: *** empty log message ***
47:
48: Revision 1.206 2015/10/24 07:14:11 brouard
49: *** empty log message ***
50:
51: Revision 1.205 2015/10/23 15:50:53 brouard
52: Summary: 0.98r3 some clarification for graphs on likelihood contributions
53:
54: Revision 1.204 2015/10/01 16:20:26 brouard
55: Summary: Some new graphs of contribution to likelihood
56:
57: Revision 1.203 2015/09/30 17:45:14 brouard
58: Summary: looking at better estimation of the hessian
59:
60: Also a better criteria for convergence to the period prevalence And
61: therefore adding the number of years needed to converge. (The
62: prevalence in any alive state shold sum to one
63:
64: Revision 1.202 2015/09/22 19:45:16 brouard
65: Summary: Adding some overall graph on contribution to likelihood. Might change
66:
67: Revision 1.201 2015/09/15 17:34:58 brouard
68: Summary: 0.98r0
69:
70: - Some new graphs like suvival functions
71: - Some bugs fixed like model=1+age+V2.
72:
73: Revision 1.200 2015/09/09 16:53:55 brouard
74: Summary: Big bug thanks to Flavia
75:
76: Even model=1+age+V2. did not work anymore
77:
78: Revision 1.199 2015/09/07 14:09:23 brouard
79: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
80:
81: Revision 1.198 2015/09/03 07:14:39 brouard
82: Summary: 0.98q5 Flavia
83:
84: Revision 1.197 2015/09/01 18:24:39 brouard
85: *** empty log message ***
86:
87: Revision 1.196 2015/08/18 23:17:52 brouard
88: Summary: 0.98q5
89:
90: Revision 1.195 2015/08/18 16:28:39 brouard
91: Summary: Adding a hack for testing purpose
92:
93: After reading the title, ftol and model lines, if the comment line has
94: a q, starting with #q, the answer at the end of the run is quit. It
95: permits to run test files in batch with ctest. The former workaround was
96: $ echo q | imach foo.imach
97:
98: Revision 1.194 2015/08/18 13:32:00 brouard
99: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
100:
101: Revision 1.193 2015/08/04 07:17:42 brouard
102: Summary: 0.98q4
103:
104: Revision 1.192 2015/07/16 16:49:02 brouard
105: Summary: Fixing some outputs
106:
107: Revision 1.191 2015/07/14 10:00:33 brouard
108: Summary: Some fixes
109:
110: Revision 1.190 2015/05/05 08:51:13 brouard
111: Summary: Adding digits in output parameters (7 digits instead of 6)
112:
113: Fix 1+age+.
114:
115: Revision 1.189 2015/04/30 14:45:16 brouard
116: Summary: 0.98q2
117:
118: Revision 1.188 2015/04/30 08:27:53 brouard
119: *** empty log message ***
120:
121: Revision 1.187 2015/04/29 09:11:15 brouard
122: *** empty log message ***
123:
124: Revision 1.186 2015/04/23 12:01:52 brouard
125: Summary: V1*age is working now, version 0.98q1
126:
127: Some codes had been disabled in order to simplify and Vn*age was
128: working in the optimization phase, ie, giving correct MLE parameters,
129: but, as usual, outputs were not correct and program core dumped.
130:
131: Revision 1.185 2015/03/11 13:26:42 brouard
132: Summary: Inclusion of compile and links command line for Intel Compiler
133:
134: Revision 1.184 2015/03/11 11:52:39 brouard
135: Summary: Back from Windows 8. Intel Compiler
136:
137: Revision 1.183 2015/03/10 20:34:32 brouard
138: Summary: 0.98q0, trying with directest, mnbrak fixed
139:
140: We use directest instead of original Powell test; probably no
141: incidence on the results, but better justifications;
142: We fixed Numerical Recipes mnbrak routine which was wrong and gave
143: wrong results.
144:
145: Revision 1.182 2015/02/12 08:19:57 brouard
146: Summary: Trying to keep directest which seems simpler and more general
147: Author: Nicolas Brouard
148:
149: Revision 1.181 2015/02/11 23:22:24 brouard
150: Summary: Comments on Powell added
151:
152: Author:
153:
154: Revision 1.180 2015/02/11 17:33:45 brouard
155: Summary: Finishing move from main to function (hpijx and prevalence_limit)
156:
157: Revision 1.179 2015/01/04 09:57:06 brouard
158: Summary: back to OS/X
159:
160: Revision 1.178 2015/01/04 09:35:48 brouard
161: *** empty log message ***
162:
163: Revision 1.177 2015/01/03 18:40:56 brouard
164: Summary: Still testing ilc32 on OSX
165:
166: Revision 1.176 2015/01/03 16:45:04 brouard
167: *** empty log message ***
168:
169: Revision 1.175 2015/01/03 16:33:42 brouard
170: *** empty log message ***
171:
172: Revision 1.174 2015/01/03 16:15:49 brouard
173: Summary: Still in cross-compilation
174:
175: Revision 1.173 2015/01/03 12:06:26 brouard
176: Summary: trying to detect cross-compilation
177:
178: Revision 1.172 2014/12/27 12:07:47 brouard
179: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
180:
181: Revision 1.171 2014/12/23 13:26:59 brouard
182: Summary: Back from Visual C
183:
184: Still problem with utsname.h on Windows
185:
186: Revision 1.170 2014/12/23 11:17:12 brouard
187: Summary: Cleaning some \%% back to %%
188:
189: The escape was mandatory for a specific compiler (which one?), but too many warnings.
190:
191: Revision 1.169 2014/12/22 23:08:31 brouard
192: Summary: 0.98p
193:
194: Outputs some informations on compiler used, OS etc. Testing on different platforms.
195:
196: Revision 1.168 2014/12/22 15:17:42 brouard
197: Summary: update
198:
199: Revision 1.167 2014/12/22 13:50:56 brouard
200: Summary: Testing uname and compiler version and if compiled 32 or 64
201:
202: Testing on Linux 64
203:
204: Revision 1.166 2014/12/22 11:40:47 brouard
205: *** empty log message ***
206:
207: Revision 1.165 2014/12/16 11:20:36 brouard
208: Summary: After compiling on Visual C
209:
210: * imach.c (Module): Merging 1.61 to 1.162
211:
212: Revision 1.164 2014/12/16 10:52:11 brouard
213: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
214:
215: * imach.c (Module): Merging 1.61 to 1.162
216:
217: Revision 1.163 2014/12/16 10:30:11 brouard
218: * imach.c (Module): Merging 1.61 to 1.162
219:
220: Revision 1.162 2014/09/25 11:43:39 brouard
221: Summary: temporary backup 0.99!
222:
223: Revision 1.1 2014/09/16 11:06:58 brouard
224: Summary: With some code (wrong) for nlopt
225:
226: Author:
227:
228: Revision 1.161 2014/09/15 20:41:41 brouard
229: Summary: Problem with macro SQR on Intel compiler
230:
231: Revision 1.160 2014/09/02 09:24:05 brouard
232: *** empty log message ***
233:
234: Revision 1.159 2014/09/01 10:34:10 brouard
235: Summary: WIN32
236: Author: Brouard
237:
238: Revision 1.158 2014/08/27 17:11:51 brouard
239: *** empty log message ***
240:
241: Revision 1.157 2014/08/27 16:26:55 brouard
242: Summary: Preparing windows Visual studio version
243: Author: Brouard
244:
245: In order to compile on Visual studio, time.h is now correct and time_t
246: and tm struct should be used. difftime should be used but sometimes I
247: just make the differences in raw time format (time(&now).
248: Trying to suppress #ifdef LINUX
249: Add xdg-open for __linux in order to open default browser.
250:
251: Revision 1.156 2014/08/25 20:10:10 brouard
252: *** empty log message ***
253:
254: Revision 1.155 2014/08/25 18:32:34 brouard
255: Summary: New compile, minor changes
256: Author: Brouard
257:
258: Revision 1.154 2014/06/20 17:32:08 brouard
259: Summary: Outputs now all graphs of convergence to period prevalence
260:
261: Revision 1.153 2014/06/20 16:45:46 brouard
262: Summary: If 3 live state, convergence to period prevalence on same graph
263: Author: Brouard
264:
265: Revision 1.152 2014/06/18 17:54:09 brouard
266: Summary: open browser, use gnuplot on same dir than imach if not found in the path
267:
268: Revision 1.151 2014/06/18 16:43:30 brouard
269: *** empty log message ***
270:
271: Revision 1.150 2014/06/18 16:42:35 brouard
272: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
273: Author: brouard
274:
275: Revision 1.149 2014/06/18 15:51:14 brouard
276: Summary: Some fixes in parameter files errors
277: Author: Nicolas Brouard
278:
279: Revision 1.148 2014/06/17 17:38:48 brouard
280: Summary: Nothing new
281: Author: Brouard
282:
283: Just a new packaging for OS/X version 0.98nS
284:
285: Revision 1.147 2014/06/16 10:33:11 brouard
286: *** empty log message ***
287:
288: Revision 1.146 2014/06/16 10:20:28 brouard
289: Summary: Merge
290: Author: Brouard
291:
292: Merge, before building revised version.
293:
294: Revision 1.145 2014/06/10 21:23:15 brouard
295: Summary: Debugging with valgrind
296: Author: Nicolas Brouard
297:
298: Lot of changes in order to output the results with some covariates
299: After the Edimburgh REVES conference 2014, it seems mandatory to
300: improve the code.
301: No more memory valgrind error but a lot has to be done in order to
302: continue the work of splitting the code into subroutines.
303: Also, decodemodel has been improved. Tricode is still not
304: optimal. nbcode should be improved. Documentation has been added in
305: the source code.
306:
307: Revision 1.143 2014/01/26 09:45:38 brouard
308: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
309:
310: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
311: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
312:
313: Revision 1.142 2014/01/26 03:57:36 brouard
314: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
315:
316: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
317:
318: Revision 1.141 2014/01/26 02:42:01 brouard
319: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
320:
321: Revision 1.140 2011/09/02 10:37:54 brouard
322: Summary: times.h is ok with mingw32 now.
323:
324: Revision 1.139 2010/06/14 07:50:17 brouard
325: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
326: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
327:
328: Revision 1.138 2010/04/30 18:19:40 brouard
329: *** empty log message ***
330:
331: Revision 1.137 2010/04/29 18:11:38 brouard
332: (Module): Checking covariates for more complex models
333: than V1+V2. A lot of change to be done. Unstable.
334:
335: Revision 1.136 2010/04/26 20:30:53 brouard
336: (Module): merging some libgsl code. Fixing computation
337: of likelione (using inter/intrapolation if mle = 0) in order to
338: get same likelihood as if mle=1.
339: Some cleaning of code and comments added.
340:
341: Revision 1.135 2009/10/29 15:33:14 brouard
342: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
343:
344: Revision 1.134 2009/10/29 13:18:53 brouard
345: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
346:
347: Revision 1.133 2009/07/06 10:21:25 brouard
348: just nforces
349:
350: Revision 1.132 2009/07/06 08:22:05 brouard
351: Many tings
352:
353: Revision 1.131 2009/06/20 16:22:47 brouard
354: Some dimensions resccaled
355:
356: Revision 1.130 2009/05/26 06:44:34 brouard
357: (Module): Max Covariate is now set to 20 instead of 8. A
358: lot of cleaning with variables initialized to 0. Trying to make
359: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
360:
361: Revision 1.129 2007/08/31 13:49:27 lievre
362: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
363:
364: Revision 1.128 2006/06/30 13:02:05 brouard
365: (Module): Clarifications on computing e.j
366:
367: Revision 1.127 2006/04/28 18:11:50 brouard
368: (Module): Yes the sum of survivors was wrong since
369: imach-114 because nhstepm was no more computed in the age
370: loop. Now we define nhstepma in the age loop.
371: (Module): In order to speed up (in case of numerous covariates) we
372: compute health expectancies (without variances) in a first step
373: and then all the health expectancies with variances or standard
374: deviation (needs data from the Hessian matrices) which slows the
375: computation.
376: In the future we should be able to stop the program is only health
377: expectancies and graph are needed without standard deviations.
378:
379: Revision 1.126 2006/04/28 17:23:28 brouard
380: (Module): Yes the sum of survivors was wrong since
381: imach-114 because nhstepm was no more computed in the age
382: loop. Now we define nhstepma in the age loop.
383: Version 0.98h
384:
385: Revision 1.125 2006/04/04 15:20:31 lievre
386: Errors in calculation of health expectancies. Age was not initialized.
387: Forecasting file added.
388:
389: Revision 1.124 2006/03/22 17:13:53 lievre
390: Parameters are printed with %lf instead of %f (more numbers after the comma).
391: The log-likelihood is printed in the log file
392:
393: Revision 1.123 2006/03/20 10:52:43 brouard
394: * imach.c (Module): <title> changed, corresponds to .htm file
395: name. <head> headers where missing.
396:
397: * imach.c (Module): Weights can have a decimal point as for
398: English (a comma might work with a correct LC_NUMERIC environment,
399: otherwise the weight is truncated).
400: Modification of warning when the covariates values are not 0 or
401: 1.
402: Version 0.98g
403:
404: Revision 1.122 2006/03/20 09:45:41 brouard
405: (Module): Weights can have a decimal point as for
406: English (a comma might work with a correct LC_NUMERIC environment,
407: otherwise the weight is truncated).
408: Modification of warning when the covariates values are not 0 or
409: 1.
410: Version 0.98g
411:
412: Revision 1.121 2006/03/16 17:45:01 lievre
413: * imach.c (Module): Comments concerning covariates added
414:
415: * imach.c (Module): refinements in the computation of lli if
416: status=-2 in order to have more reliable computation if stepm is
417: not 1 month. Version 0.98f
418:
419: Revision 1.120 2006/03/16 15:10:38 lievre
420: (Module): refinements in the computation of lli if
421: status=-2 in order to have more reliable computation if stepm is
422: not 1 month. Version 0.98f
423:
424: Revision 1.119 2006/03/15 17:42:26 brouard
425: (Module): Bug if status = -2, the loglikelihood was
426: computed as likelihood omitting the logarithm. Version O.98e
427:
428: Revision 1.118 2006/03/14 18:20:07 brouard
429: (Module): varevsij Comments added explaining the second
430: table of variances if popbased=1 .
431: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
432: (Module): Function pstamp added
433: (Module): Version 0.98d
434:
435: Revision 1.117 2006/03/14 17:16:22 brouard
436: (Module): varevsij Comments added explaining the second
437: table of variances if popbased=1 .
438: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
439: (Module): Function pstamp added
440: (Module): Version 0.98d
441:
442: Revision 1.116 2006/03/06 10:29:27 brouard
443: (Module): Variance-covariance wrong links and
444: varian-covariance of ej. is needed (Saito).
445:
446: Revision 1.115 2006/02/27 12:17:45 brouard
447: (Module): One freematrix added in mlikeli! 0.98c
448:
449: Revision 1.114 2006/02/26 12:57:58 brouard
450: (Module): Some improvements in processing parameter
451: filename with strsep.
452:
453: Revision 1.113 2006/02/24 14:20:24 brouard
454: (Module): Memory leaks checks with valgrind and:
455: datafile was not closed, some imatrix were not freed and on matrix
456: allocation too.
457:
458: Revision 1.112 2006/01/30 09:55:26 brouard
459: (Module): Back to gnuplot.exe instead of wgnuplot.exe
460:
461: Revision 1.111 2006/01/25 20:38:18 brouard
462: (Module): Lots of cleaning and bugs added (Gompertz)
463: (Module): Comments can be added in data file. Missing date values
464: can be a simple dot '.'.
465:
466: Revision 1.110 2006/01/25 00:51:50 brouard
467: (Module): Lots of cleaning and bugs added (Gompertz)
468:
469: Revision 1.109 2006/01/24 19:37:15 brouard
470: (Module): Comments (lines starting with a #) are allowed in data.
471:
472: Revision 1.108 2006/01/19 18:05:42 lievre
473: Gnuplot problem appeared...
474: To be fixed
475:
476: Revision 1.107 2006/01/19 16:20:37 brouard
477: Test existence of gnuplot in imach path
478:
479: Revision 1.106 2006/01/19 13:24:36 brouard
480: Some cleaning and links added in html output
481:
482: Revision 1.105 2006/01/05 20:23:19 lievre
483: *** empty log message ***
484:
485: Revision 1.104 2005/09/30 16:11:43 lievre
486: (Module): sump fixed, loop imx fixed, and simplifications.
487: (Module): If the status is missing at the last wave but we know
488: that the person is alive, then we can code his/her status as -2
489: (instead of missing=-1 in earlier versions) and his/her
490: contributions to the likelihood is 1 - Prob of dying from last
491: health status (= 1-p13= p11+p12 in the easiest case of somebody in
492: the healthy state at last known wave). Version is 0.98
493:
494: Revision 1.103 2005/09/30 15:54:49 lievre
495: (Module): sump fixed, loop imx fixed, and simplifications.
496:
497: Revision 1.102 2004/09/15 17:31:30 brouard
498: Add the possibility to read data file including tab characters.
499:
500: Revision 1.101 2004/09/15 10:38:38 brouard
501: Fix on curr_time
502:
503: Revision 1.100 2004/07/12 18:29:06 brouard
504: Add version for Mac OS X. Just define UNIX in Makefile
505:
506: Revision 1.99 2004/06/05 08:57:40 brouard
507: *** empty log message ***
508:
509: Revision 1.98 2004/05/16 15:05:56 brouard
510: New version 0.97 . First attempt to estimate force of mortality
511: directly from the data i.e. without the need of knowing the health
512: state at each age, but using a Gompertz model: log u =a + b*age .
513: This is the basic analysis of mortality and should be done before any
514: other analysis, in order to test if the mortality estimated from the
515: cross-longitudinal survey is different from the mortality estimated
516: from other sources like vital statistic data.
517:
518: The same imach parameter file can be used but the option for mle should be -3.
519:
520: Agnès, who wrote this part of the code, tried to keep most of the
521: former routines in order to include the new code within the former code.
522:
523: The output is very simple: only an estimate of the intercept and of
524: the slope with 95% confident intervals.
525:
526: Current limitations:
527: A) Even if you enter covariates, i.e. with the
528: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
529: B) There is no computation of Life Expectancy nor Life Table.
530:
531: Revision 1.97 2004/02/20 13:25:42 lievre
532: Version 0.96d. Population forecasting command line is (temporarily)
533: suppressed.
534:
535: Revision 1.96 2003/07/15 15:38:55 brouard
536: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
537: rewritten within the same printf. Workaround: many printfs.
538:
539: Revision 1.95 2003/07/08 07:54:34 brouard
540: * imach.c (Repository):
541: (Repository): Using imachwizard code to output a more meaningful covariance
542: matrix (cov(a12,c31) instead of numbers.
543:
544: Revision 1.94 2003/06/27 13:00:02 brouard
545: Just cleaning
546:
547: Revision 1.93 2003/06/25 16:33:55 brouard
548: (Module): On windows (cygwin) function asctime_r doesn't
549: exist so I changed back to asctime which exists.
550: (Module): Version 0.96b
551:
552: Revision 1.92 2003/06/25 16:30:45 brouard
553: (Module): On windows (cygwin) function asctime_r doesn't
554: exist so I changed back to asctime which exists.
555:
556: Revision 1.91 2003/06/25 15:30:29 brouard
557: * imach.c (Repository): Duplicated warning errors corrected.
558: (Repository): Elapsed time after each iteration is now output. It
559: helps to forecast when convergence will be reached. Elapsed time
560: is stamped in powell. We created a new html file for the graphs
561: concerning matrix of covariance. It has extension -cov.htm.
562:
563: Revision 1.90 2003/06/24 12:34:15 brouard
564: (Module): Some bugs corrected for windows. Also, when
565: mle=-1 a template is output in file "or"mypar.txt with the design
566: of the covariance matrix to be input.
567:
568: Revision 1.89 2003/06/24 12:30:52 brouard
569: (Module): Some bugs corrected for windows. Also, when
570: mle=-1 a template is output in file "or"mypar.txt with the design
571: of the covariance matrix to be input.
572:
573: Revision 1.88 2003/06/23 17:54:56 brouard
574: * 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.
575:
576: Revision 1.87 2003/06/18 12:26:01 brouard
577: Version 0.96
578:
579: Revision 1.86 2003/06/17 20:04:08 brouard
580: (Module): Change position of html and gnuplot routines and added
581: routine fileappend.
582:
583: Revision 1.85 2003/06/17 13:12:43 brouard
584: * imach.c (Repository): Check when date of death was earlier that
585: current date of interview. It may happen when the death was just
586: prior to the death. In this case, dh was negative and likelihood
587: was wrong (infinity). We still send an "Error" but patch by
588: assuming that the date of death was just one stepm after the
589: interview.
590: (Repository): Because some people have very long ID (first column)
591: we changed int to long in num[] and we added a new lvector for
592: memory allocation. But we also truncated to 8 characters (left
593: truncation)
594: (Repository): No more line truncation errors.
595:
596: Revision 1.84 2003/06/13 21:44:43 brouard
597: * imach.c (Repository): Replace "freqsummary" at a correct
598: place. It differs from routine "prevalence" which may be called
599: many times. Probs is memory consuming and must be used with
600: parcimony.
601: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
602:
603: Revision 1.83 2003/06/10 13:39:11 lievre
604: *** empty log message ***
605:
606: Revision 1.82 2003/06/05 15:57:20 brouard
607: Add log in imach.c and fullversion number is now printed.
608:
609: */
610: /*
611: Interpolated Markov Chain
612:
613: Short summary of the programme:
614:
615: This program computes Healthy Life Expectancies from
616: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
617: first survey ("cross") where individuals from different ages are
618: interviewed on their health status or degree of disability (in the
619: case of a health survey which is our main interest) -2- at least a
620: second wave of interviews ("longitudinal") which measure each change
621: (if any) in individual health status. Health expectancies are
622: computed from the time spent in each health state according to a
623: model. More health states you consider, more time is necessary to reach the
624: Maximum Likelihood of the parameters involved in the model. The
625: simplest model is the multinomial logistic model where pij is the
626: probability to be observed in state j at the second wave
627: conditional to be observed in state i at the first wave. Therefore
628: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
629: 'age' is age and 'sex' is a covariate. If you want to have a more
630: complex model than "constant and age", you should modify the program
631: where the markup *Covariates have to be included here again* invites
632: you to do it. More covariates you add, slower the
633: convergence.
634:
635: The advantage of this computer programme, compared to a simple
636: multinomial logistic model, is clear when the delay between waves is not
637: identical for each individual. Also, if a individual missed an
638: intermediate interview, the information is lost, but taken into
639: account using an interpolation or extrapolation.
640:
641: hPijx is the probability to be observed in state i at age x+h
642: conditional to the observed state i at age x. The delay 'h' can be
643: split into an exact number (nh*stepm) of unobserved intermediate
644: states. This elementary transition (by month, quarter,
645: semester or year) is modelled as a multinomial logistic. The hPx
646: matrix is simply the matrix product of nh*stepm elementary matrices
647: and the contribution of each individual to the likelihood is simply
648: hPijx.
649:
650: Also this programme outputs the covariance matrix of the parameters but also
651: of the life expectancies. It also computes the period (stable) prevalence.
652:
653: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
654: Institut national d'études démographiques, Paris.
655: This software have been partly granted by Euro-REVES, a concerted action
656: from the European Union.
657: It is copyrighted identically to a GNU software product, ie programme and
658: software can be distributed freely for non commercial use. Latest version
659: can be accessed at http://euroreves.ined.fr/imach .
660:
661: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
662: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
663:
664: **********************************************************************/
665: /*
666: main
667: read parameterfile
668: read datafile
669: concatwav
670: freqsummary
671: if (mle >= 1)
672: mlikeli
673: print results files
674: if mle==1
675: computes hessian
676: read end of parameter file: agemin, agemax, bage, fage, estepm
677: begin-prev-date,...
678: open gnuplot file
679: open html file
680: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
681: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
682: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
683: freexexit2 possible for memory heap.
684:
685: h Pij x | pij_nom ficrestpij
686: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
687: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
688: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
689:
690: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
691: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
692: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
693: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
694: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
695:
696: forecasting if prevfcast==1 prevforecast call prevalence()
697: health expectancies
698: Variance-covariance of DFLE
699: prevalence()
700: movingaverage()
701: varevsij()
702: if popbased==1 varevsij(,popbased)
703: total life expectancies
704: Variance of period (stable) prevalence
705: end
706: */
707:
708: /* #define DEBUG */
709: /* #define DEBUGBRENT */
710: /* #define DEBUGLINMIN */
711: /* #define DEBUGHESS */
712: #define DEBUGHESSIJ
713: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
714: #define POWELL /* Instead of NLOPT */
715: #define POWELLF1F3 /* Skip test */
716: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
717: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
718:
719: #include <math.h>
720: #include <stdio.h>
721: #include <stdlib.h>
722: #include <string.h>
723:
724: #ifdef _WIN32
725: #include <io.h>
726: #include <windows.h>
727: #include <tchar.h>
728: #else
729: #include <unistd.h>
730: #endif
731:
732: #include <limits.h>
733: #include <sys/types.h>
734:
735: #if defined(__GNUC__)
736: #include <sys/utsname.h> /* Doesn't work on Windows */
737: #endif
738:
739: #include <sys/stat.h>
740: #include <errno.h>
741: /* extern int errno; */
742:
743: /* #ifdef LINUX */
744: /* #include <time.h> */
745: /* #include "timeval.h" */
746: /* #else */
747: /* #include <sys/time.h> */
748: /* #endif */
749:
750: #include <time.h>
751:
752: #ifdef GSL
753: #include <gsl/gsl_errno.h>
754: #include <gsl/gsl_multimin.h>
755: #endif
756:
757:
758: #ifdef NLOPT
759: #include <nlopt.h>
760: typedef struct {
761: double (* function)(double [] );
762: } myfunc_data ;
763: #endif
764:
765: /* #include <libintl.h> */
766: /* #define _(String) gettext (String) */
767:
768: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
769:
770: #define GNUPLOTPROGRAM "gnuplot"
771: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
772: #define FILENAMELENGTH 132
773:
774: #define GLOCK_ERROR_NOPATH -1 /* empty path */
775: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
776:
777: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
778: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
779:
780: #define NINTERVMAX 8
781: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
782: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
783: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
784: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
785: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
786: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
787: #define MAXN 20000
788: #define YEARM 12. /**< Number of months per year */
789: #define AGESUP 130
790: #define AGEBASE 40
791: #define AGEOVERFLOW 1.e20
792: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
793: #ifdef _WIN32
794: #define DIRSEPARATOR '\\'
795: #define CHARSEPARATOR "\\"
796: #define ODIRSEPARATOR '/'
797: #else
798: #define DIRSEPARATOR '/'
799: #define CHARSEPARATOR "/"
800: #define ODIRSEPARATOR '\\'
801: #endif
802:
803: /* $Id: imach.c,v 1.216 2015/12/18 17:32:11 brouard Exp $ */
804: /* $State: Exp $ */
805: #include "version.h"
806: char version[]=__IMACH_VERSION__;
807: 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";
808: char fullversion[]="$Revision: 1.216 $ $Date: 2015/12/18 17:32:11 $";
809: char strstart[80];
810: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
811: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
812: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
813: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
814: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
815: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
816: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
817: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
818: int cptcovprodnoage=0; /**< Number of covariate products without age */
819: int cptcoveff=0; /* Total number of covariates to vary for printing results */
820: int cptcov=0; /* Working variable */
821: int npar=NPARMAX;
822: int nlstate=2; /* Number of live states */
823: int ndeath=1; /* Number of dead states */
824: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
825: int popbased=0;
826:
827: int *wav; /* Number of waves for this individuual 0 is possible */
828: int maxwav=0; /* Maxim number of waves */
829: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
830: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
831: int gipmx=0, gsw=0; /* Global variables on the number of contributions
832: to the likelihood and the sum of weights (done by funcone)*/
833: int mle=1, weightopt=0;
834: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
835: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
836: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
837: * wave mi and wave mi+1 is not an exact multiple of stepm. */
838: int countcallfunc=0; /* Count the number of calls to func */
839: double jmean=1; /* Mean space between 2 waves */
840: double **matprod2(); /* test */
841: double **oldm, **newm, **savm; /* Working pointers to matrices */
842: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
843: /*FILE *fic ; */ /* Used in readdata only */
844: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
845: FILE *ficlog, *ficrespow;
846: int globpr=0; /* Global variable for printing or not */
847: double fretone; /* Only one call to likelihood */
848: long ipmx=0; /* Number of contributions */
849: double sw; /* Sum of weights */
850: char filerespow[FILENAMELENGTH];
851: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
852: FILE *ficresilk;
853: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
854: FILE *ficresprobmorprev;
855: FILE *fichtm, *fichtmcov; /* Html File */
856: FILE *ficreseij;
857: char filerese[FILENAMELENGTH];
858: FILE *ficresstdeij;
859: char fileresstde[FILENAMELENGTH];
860: FILE *ficrescveij;
861: char filerescve[FILENAMELENGTH];
862: FILE *ficresvij;
863: char fileresv[FILENAMELENGTH];
864: FILE *ficresvpl;
865: char fileresvpl[FILENAMELENGTH];
866: char title[MAXLINE];
867: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
868: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
869: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
870: char command[FILENAMELENGTH];
871: int outcmd=0;
872:
873: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
874: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
875: char filelog[FILENAMELENGTH]; /* Log file */
876: char filerest[FILENAMELENGTH];
877: char fileregp[FILENAMELENGTH];
878: char popfile[FILENAMELENGTH];
879:
880: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
881:
882: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
883: /* struct timezone tzp; */
884: /* extern int gettimeofday(); */
885: struct tm tml, *gmtime(), *localtime();
886:
887: extern time_t time();
888:
889: struct tm start_time, end_time, curr_time, last_time, forecast_time;
890: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
891: struct tm tm;
892:
893: char strcurr[80], strfor[80];
894:
895: char *endptr;
896: long lval;
897: double dval;
898:
899: #define NR_END 1
900: #define FREE_ARG char*
901: #define FTOL 1.0e-10
902:
903: #define NRANSI
904: #define ITMAX 200
905:
906: #define TOL 2.0e-4
907:
908: #define CGOLD 0.3819660
909: #define ZEPS 1.0e-10
910: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
911:
912: #define GOLD 1.618034
913: #define GLIMIT 100.0
914: #define TINY 1.0e-20
915:
916: static double maxarg1,maxarg2;
917: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
918: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
919:
920: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
921: #define rint(a) floor(a+0.5)
922: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
923: #define mytinydouble 1.0e-16
924: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
925: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
926: /* static double dsqrarg; */
927: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
928: static double sqrarg;
929: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
930: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
931: int agegomp= AGEGOMP;
932:
933: int imx;
934: int stepm=1;
935: /* Stepm, step in month: minimum step interpolation*/
936:
937: int estepm;
938: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
939:
940: int m,nb;
941: long *num;
942: int firstpass=0, lastpass=4,*cod, *cens;
943: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
944: covariate for which somebody answered excluding
945: undefined. Usually 2: 0 and 1. */
946: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
947: covariate for which somebody answered including
948: undefined. Usually 3: -1, 0 and 1. */
949: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
950: double **pmmij, ***probs;
951: double *ageexmed,*agecens;
952: double dateintmean=0;
953:
954: double *weight;
955: int **s; /* Status */
956: double *agedc;
957: double **covar; /**< covar[j,i], value of jth covariate for individual i,
958: * covar=matrix(0,NCOVMAX,1,n);
959: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
960: double idx;
961: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
962: int *Tage;
963: int *Ndum; /** Freq of modality (tricode */
964: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
965: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
966: double *lsurv, *lpop, *tpop;
967:
968: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
969: double ftolhess; /**< Tolerance for computing hessian */
970:
971: /**************** split *************************/
972: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
973: {
974: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
975: the name of the file (name), its extension only (ext) and its first part of the name (finame)
976: */
977: char *ss; /* pointer */
978: int l1=0, l2=0; /* length counters */
979:
980: l1 = strlen(path ); /* length of path */
981: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
982: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
983: if ( ss == NULL ) { /* no directory, so determine current directory */
984: strcpy( name, path ); /* we got the fullname name because no directory */
985: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
986: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
987: /* get current working directory */
988: /* extern char* getcwd ( char *buf , int len);*/
989: #ifdef WIN32
990: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
991: #else
992: if (getcwd(dirc, FILENAME_MAX) == NULL) {
993: #endif
994: return( GLOCK_ERROR_GETCWD );
995: }
996: /* got dirc from getcwd*/
997: printf(" DIRC = %s \n",dirc);
998: } else { /* strip directory from path */
999: ss++; /* after this, the filename */
1000: l2 = strlen( ss ); /* length of filename */
1001: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
1002: strcpy( name, ss ); /* save file name */
1003: strncpy( dirc, path, l1 - l2 ); /* now the directory */
1004: dirc[l1-l2] = '\0'; /* add zero */
1005: printf(" DIRC2 = %s \n",dirc);
1006: }
1007: /* We add a separator at the end of dirc if not exists */
1008: l1 = strlen( dirc ); /* length of directory */
1009: if( dirc[l1-1] != DIRSEPARATOR ){
1010: dirc[l1] = DIRSEPARATOR;
1011: dirc[l1+1] = 0;
1012: printf(" DIRC3 = %s \n",dirc);
1013: }
1014: ss = strrchr( name, '.' ); /* find last / */
1015: if (ss >0){
1016: ss++;
1017: strcpy(ext,ss); /* save extension */
1018: l1= strlen( name);
1019: l2= strlen(ss)+1;
1020: strncpy( finame, name, l1-l2);
1021: finame[l1-l2]= 0;
1022: }
1023:
1024: return( 0 ); /* we're done */
1025: }
1026:
1027:
1028: /******************************************/
1029:
1030: void replace_back_to_slash(char *s, char*t)
1031: {
1032: int i;
1033: int lg=0;
1034: i=0;
1035: lg=strlen(t);
1036: for(i=0; i<= lg; i++) {
1037: (s[i] = t[i]);
1038: if (t[i]== '\\') s[i]='/';
1039: }
1040: }
1041:
1042: char *trimbb(char *out, char *in)
1043: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1044: char *s;
1045: s=out;
1046: while (*in != '\0'){
1047: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1048: in++;
1049: }
1050: *out++ = *in++;
1051: }
1052: *out='\0';
1053: return s;
1054: }
1055:
1056: /* char *substrchaine(char *out, char *in, char *chain) */
1057: /* { */
1058: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1059: /* char *s, *t; */
1060: /* t=in;s=out; */
1061: /* while ((*in != *chain) && (*in != '\0')){ */
1062: /* *out++ = *in++; */
1063: /* } */
1064:
1065: /* /\* *in matches *chain *\/ */
1066: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1067: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1068: /* } */
1069: /* in--; chain--; */
1070: /* while ( (*in != '\0')){ */
1071: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1072: /* *out++ = *in++; */
1073: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1074: /* } */
1075: /* *out='\0'; */
1076: /* out=s; */
1077: /* return out; */
1078: /* } */
1079: char *substrchaine(char *out, char *in, char *chain)
1080: {
1081: /* Substract chain 'chain' from 'in', return and output 'out' */
1082: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1083:
1084: char *strloc;
1085:
1086: strcpy (out, in);
1087: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1088: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1089: if(strloc != NULL){
1090: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1091: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1092: /* strcpy (strloc, strloc +strlen(chain));*/
1093: }
1094: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1095: return out;
1096: }
1097:
1098:
1099: char *cutl(char *blocc, char *alocc, char *in, char occ)
1100: {
1101: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1102: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1103: gives blocc="abcdef" and alocc="ghi2j".
1104: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1105: */
1106: char *s, *t;
1107: t=in;s=in;
1108: while ((*in != occ) && (*in != '\0')){
1109: *alocc++ = *in++;
1110: }
1111: if( *in == occ){
1112: *(alocc)='\0';
1113: s=++in;
1114: }
1115:
1116: if (s == t) {/* occ not found */
1117: *(alocc-(in-s))='\0';
1118: in=s;
1119: }
1120: while ( *in != '\0'){
1121: *blocc++ = *in++;
1122: }
1123:
1124: *blocc='\0';
1125: return t;
1126: }
1127: char *cutv(char *blocc, char *alocc, char *in, char occ)
1128: {
1129: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1130: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1131: gives blocc="abcdef2ghi" and alocc="j".
1132: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1133: */
1134: char *s, *t;
1135: t=in;s=in;
1136: while (*in != '\0'){
1137: while( *in == occ){
1138: *blocc++ = *in++;
1139: s=in;
1140: }
1141: *blocc++ = *in++;
1142: }
1143: if (s == t) /* occ not found */
1144: *(blocc-(in-s))='\0';
1145: else
1146: *(blocc-(in-s)-1)='\0';
1147: in=s;
1148: while ( *in != '\0'){
1149: *alocc++ = *in++;
1150: }
1151:
1152: *alocc='\0';
1153: return s;
1154: }
1155:
1156: int nbocc(char *s, char occ)
1157: {
1158: int i,j=0;
1159: int lg=20;
1160: i=0;
1161: lg=strlen(s);
1162: for(i=0; i<= lg; i++) {
1163: if (s[i] == occ ) j++;
1164: }
1165: return j;
1166: }
1167:
1168: /* void cutv(char *u,char *v, char*t, char occ) */
1169: /* { */
1170: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1171: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1172: /* gives u="abcdef2ghi" and v="j" *\/ */
1173: /* int i,lg,j,p=0; */
1174: /* i=0; */
1175: /* lg=strlen(t); */
1176: /* for(j=0; j<=lg-1; j++) { */
1177: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1178: /* } */
1179:
1180: /* for(j=0; j<p; j++) { */
1181: /* (u[j] = t[j]); */
1182: /* } */
1183: /* u[p]='\0'; */
1184:
1185: /* for(j=0; j<= lg; j++) { */
1186: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1187: /* } */
1188: /* } */
1189:
1190: #ifdef _WIN32
1191: char * strsep(char **pp, const char *delim)
1192: {
1193: char *p, *q;
1194:
1195: if ((p = *pp) == NULL)
1196: return 0;
1197: if ((q = strpbrk (p, delim)) != NULL)
1198: {
1199: *pp = q + 1;
1200: *q = '\0';
1201: }
1202: else
1203: *pp = 0;
1204: return p;
1205: }
1206: #endif
1207:
1208: /********************** nrerror ********************/
1209:
1210: void nrerror(char error_text[])
1211: {
1212: fprintf(stderr,"ERREUR ...\n");
1213: fprintf(stderr,"%s\n",error_text);
1214: exit(EXIT_FAILURE);
1215: }
1216: /*********************** vector *******************/
1217: double *vector(int nl, int nh)
1218: {
1219: double *v;
1220: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1221: if (!v) nrerror("allocation failure in vector");
1222: return v-nl+NR_END;
1223: }
1224:
1225: /************************ free vector ******************/
1226: void free_vector(double*v, int nl, int nh)
1227: {
1228: free((FREE_ARG)(v+nl-NR_END));
1229: }
1230:
1231: /************************ivector *******************************/
1232: int *ivector(long nl,long nh)
1233: {
1234: int *v;
1235: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1236: if (!v) nrerror("allocation failure in ivector");
1237: return v-nl+NR_END;
1238: }
1239:
1240: /******************free ivector **************************/
1241: void free_ivector(int *v, long nl, long nh)
1242: {
1243: free((FREE_ARG)(v+nl-NR_END));
1244: }
1245:
1246: /************************lvector *******************************/
1247: long *lvector(long nl,long nh)
1248: {
1249: long *v;
1250: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1251: if (!v) nrerror("allocation failure in ivector");
1252: return v-nl+NR_END;
1253: }
1254:
1255: /******************free lvector **************************/
1256: void free_lvector(long *v, long nl, long nh)
1257: {
1258: free((FREE_ARG)(v+nl-NR_END));
1259: }
1260:
1261: /******************* imatrix *******************************/
1262: int **imatrix(long nrl, long nrh, long ncl, long nch)
1263: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1264: {
1265: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1266: int **m;
1267:
1268: /* allocate pointers to rows */
1269: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1270: if (!m) nrerror("allocation failure 1 in matrix()");
1271: m += NR_END;
1272: m -= nrl;
1273:
1274:
1275: /* allocate rows and set pointers to them */
1276: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1277: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1278: m[nrl] += NR_END;
1279: m[nrl] -= ncl;
1280:
1281: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1282:
1283: /* return pointer to array of pointers to rows */
1284: return m;
1285: }
1286:
1287: /****************** free_imatrix *************************/
1288: void free_imatrix(m,nrl,nrh,ncl,nch)
1289: int **m;
1290: long nch,ncl,nrh,nrl;
1291: /* free an int matrix allocated by imatrix() */
1292: {
1293: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1294: free((FREE_ARG) (m+nrl-NR_END));
1295: }
1296:
1297: /******************* matrix *******************************/
1298: double **matrix(long nrl, long nrh, long ncl, long nch)
1299: {
1300: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1301: double **m;
1302:
1303: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1304: if (!m) nrerror("allocation failure 1 in matrix()");
1305: m += NR_END;
1306: m -= nrl;
1307:
1308: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1309: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1310: m[nrl] += NR_END;
1311: m[nrl] -= ncl;
1312:
1313: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1314: return m;
1315: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1316: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1317: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1318: */
1319: }
1320:
1321: /*************************free matrix ************************/
1322: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1323: {
1324: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1325: free((FREE_ARG)(m+nrl-NR_END));
1326: }
1327:
1328: /******************* ma3x *******************************/
1329: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1330: {
1331: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1332: double ***m;
1333:
1334: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1335: if (!m) nrerror("allocation failure 1 in matrix()");
1336: m += NR_END;
1337: m -= nrl;
1338:
1339: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1340: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1341: m[nrl] += NR_END;
1342: m[nrl] -= ncl;
1343:
1344: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1345:
1346: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1347: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1348: m[nrl][ncl] += NR_END;
1349: m[nrl][ncl] -= nll;
1350: for (j=ncl+1; j<=nch; j++)
1351: m[nrl][j]=m[nrl][j-1]+nlay;
1352:
1353: for (i=nrl+1; i<=nrh; i++) {
1354: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1355: for (j=ncl+1; j<=nch; j++)
1356: m[i][j]=m[i][j-1]+nlay;
1357: }
1358: return m;
1359: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1360: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1361: */
1362: }
1363:
1364: /*************************free ma3x ************************/
1365: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1366: {
1367: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1368: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1369: free((FREE_ARG)(m+nrl-NR_END));
1370: }
1371:
1372: /*************** function subdirf ***********/
1373: char *subdirf(char fileres[])
1374: {
1375: /* Caution optionfilefiname is hidden */
1376: strcpy(tmpout,optionfilefiname);
1377: strcat(tmpout,"/"); /* Add to the right */
1378: strcat(tmpout,fileres);
1379: return tmpout;
1380: }
1381:
1382: /*************** function subdirf2 ***********/
1383: char *subdirf2(char fileres[], char *preop)
1384: {
1385:
1386: /* Caution optionfilefiname is hidden */
1387: strcpy(tmpout,optionfilefiname);
1388: strcat(tmpout,"/");
1389: strcat(tmpout,preop);
1390: strcat(tmpout,fileres);
1391: return tmpout;
1392: }
1393:
1394: /*************** function subdirf3 ***********/
1395: char *subdirf3(char fileres[], char *preop, char *preop2)
1396: {
1397:
1398: /* Caution optionfilefiname is hidden */
1399: strcpy(tmpout,optionfilefiname);
1400: strcat(tmpout,"/");
1401: strcat(tmpout,preop);
1402: strcat(tmpout,preop2);
1403: strcat(tmpout,fileres);
1404: return tmpout;
1405: }
1406:
1407: /*************** function subdirfext ***********/
1408: char *subdirfext(char fileres[], char *preop, char *postop)
1409: {
1410:
1411: strcpy(tmpout,preop);
1412: strcat(tmpout,fileres);
1413: strcat(tmpout,postop);
1414: return tmpout;
1415: }
1416:
1417: /*************** function subdirfext3 ***********/
1418: char *subdirfext3(char fileres[], char *preop, char *postop)
1419: {
1420:
1421: /* Caution optionfilefiname is hidden */
1422: strcpy(tmpout,optionfilefiname);
1423: strcat(tmpout,"/");
1424: strcat(tmpout,preop);
1425: strcat(tmpout,fileres);
1426: strcat(tmpout,postop);
1427: return tmpout;
1428: }
1429:
1430: char *asc_diff_time(long time_sec, char ascdiff[])
1431: {
1432: long sec_left, days, hours, minutes;
1433: days = (time_sec) / (60*60*24);
1434: sec_left = (time_sec) % (60*60*24);
1435: hours = (sec_left) / (60*60) ;
1436: sec_left = (sec_left) %(60*60);
1437: minutes = (sec_left) /60;
1438: sec_left = (sec_left) % (60);
1439: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1440: return ascdiff;
1441: }
1442:
1443: /***************** f1dim *************************/
1444: extern int ncom;
1445: extern double *pcom,*xicom;
1446: extern double (*nrfunc)(double []);
1447:
1448: double f1dim(double x)
1449: {
1450: int j;
1451: double f;
1452: double *xt;
1453:
1454: xt=vector(1,ncom);
1455: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1456: f=(*nrfunc)(xt);
1457: free_vector(xt,1,ncom);
1458: return f;
1459: }
1460:
1461: /*****************brent *************************/
1462: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1463: {
1464: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1465: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1466: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1467: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1468: * returned function value.
1469: */
1470: int iter;
1471: double a,b,d,etemp;
1472: double fu=0,fv,fw,fx;
1473: double ftemp=0.;
1474: double p,q,r,tol1,tol2,u,v,w,x,xm;
1475: double e=0.0;
1476:
1477: a=(ax < cx ? ax : cx);
1478: b=(ax > cx ? ax : cx);
1479: x=w=v=bx;
1480: fw=fv=fx=(*f)(x);
1481: for (iter=1;iter<=ITMAX;iter++) {
1482: xm=0.5*(a+b);
1483: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1484: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1485: printf(".");fflush(stdout);
1486: fprintf(ficlog,".");fflush(ficlog);
1487: #ifdef DEBUGBRENT
1488: 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);
1489: 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);
1490: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1491: #endif
1492: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1493: *xmin=x;
1494: return fx;
1495: }
1496: ftemp=fu;
1497: if (fabs(e) > tol1) {
1498: r=(x-w)*(fx-fv);
1499: q=(x-v)*(fx-fw);
1500: p=(x-v)*q-(x-w)*r;
1501: q=2.0*(q-r);
1502: if (q > 0.0) p = -p;
1503: q=fabs(q);
1504: etemp=e;
1505: e=d;
1506: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1507: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1508: else {
1509: d=p/q;
1510: u=x+d;
1511: if (u-a < tol2 || b-u < tol2)
1512: d=SIGN(tol1,xm-x);
1513: }
1514: } else {
1515: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1516: }
1517: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1518: fu=(*f)(u);
1519: if (fu <= fx) {
1520: if (u >= x) a=x; else b=x;
1521: SHFT(v,w,x,u)
1522: SHFT(fv,fw,fx,fu)
1523: } else {
1524: if (u < x) a=u; else b=u;
1525: if (fu <= fw || w == x) {
1526: v=w;
1527: w=u;
1528: fv=fw;
1529: fw=fu;
1530: } else if (fu <= fv || v == x || v == w) {
1531: v=u;
1532: fv=fu;
1533: }
1534: }
1535: }
1536: nrerror("Too many iterations in brent");
1537: *xmin=x;
1538: return fx;
1539: }
1540:
1541: /****************** mnbrak ***********************/
1542:
1543: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1544: double (*func)(double))
1545: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1546: the downhill direction (defined by the function as evaluated at the initial points) and returns
1547: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1548: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1549: */
1550: double ulim,u,r,q, dum;
1551: double fu;
1552:
1553: double scale=10.;
1554: int iterscale=0;
1555:
1556: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1557: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1558:
1559:
1560: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1561: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1562: /* *bx = *ax - (*ax - *bx)/scale; */
1563: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1564: /* } */
1565:
1566: if (*fb > *fa) {
1567: SHFT(dum,*ax,*bx,dum)
1568: SHFT(dum,*fb,*fa,dum)
1569: }
1570: *cx=(*bx)+GOLD*(*bx-*ax);
1571: *fc=(*func)(*cx);
1572: #ifdef DEBUG
1573: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1574: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1575: #endif
1576: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1577: r=(*bx-*ax)*(*fb-*fc);
1578: q=(*bx-*cx)*(*fb-*fa);
1579: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1580: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1581: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1582: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1583: fu=(*func)(u);
1584: #ifdef DEBUG
1585: /* f(x)=A(x-u)**2+f(u) */
1586: double A, fparabu;
1587: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1588: fparabu= *fa - A*(*ax-u)*(*ax-u);
1589: 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);
1590: 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);
1591: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1592: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1593: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1594: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1595: #endif
1596: #ifdef MNBRAKORIGINAL
1597: #else
1598: /* if (fu > *fc) { */
1599: /* #ifdef DEBUG */
1600: /* printf("mnbrak4 fu > fc \n"); */
1601: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1602: /* #endif */
1603: /* /\* 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 *\\/ *\/ */
1604: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1605: /* dum=u; /\* Shifting c and u *\/ */
1606: /* u = *cx; */
1607: /* *cx = dum; */
1608: /* dum = fu; */
1609: /* fu = *fc; */
1610: /* *fc =dum; */
1611: /* } else { /\* end *\/ */
1612: /* #ifdef DEBUG */
1613: /* printf("mnbrak3 fu < fc \n"); */
1614: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1615: /* #endif */
1616: /* dum=u; /\* Shifting c and u *\/ */
1617: /* u = *cx; */
1618: /* *cx = dum; */
1619: /* dum = fu; */
1620: /* fu = *fc; */
1621: /* *fc =dum; */
1622: /* } */
1623: #ifdef DEBUG
1624: printf("mnbrak34 fu < or >= fc \n");
1625: fprintf(ficlog, "mnbrak34 fu < fc\n");
1626: #endif
1627: dum=u; /* Shifting c and u */
1628: u = *cx;
1629: *cx = dum;
1630: dum = fu;
1631: fu = *fc;
1632: *fc =dum;
1633: #endif
1634: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1635: #ifdef DEBUG
1636: printf("mnbrak2 u after c but before ulim\n");
1637: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1638: #endif
1639: fu=(*func)(u);
1640: if (fu < *fc) {
1641: #ifdef DEBUG
1642: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1643: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1644: #endif
1645: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1646: SHFT(*fb,*fc,fu,(*func)(u))
1647: }
1648: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1649: #ifdef DEBUG
1650: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1651: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1652: #endif
1653: u=ulim;
1654: fu=(*func)(u);
1655: } else { /* u could be left to b (if r > q parabola has a maximum) */
1656: #ifdef DEBUG
1657: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1658: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1659: #endif
1660: u=(*cx)+GOLD*(*cx-*bx);
1661: fu=(*func)(u);
1662: } /* end tests */
1663: SHFT(*ax,*bx,*cx,u)
1664: SHFT(*fa,*fb,*fc,fu)
1665: #ifdef DEBUG
1666: 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);
1667: 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);
1668: #endif
1669: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1670: }
1671:
1672: /*************** linmin ************************/
1673: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1674: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1675: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1676: the value of func at the returned location p . This is actually all accomplished by calling the
1677: routines mnbrak and brent .*/
1678: int ncom;
1679: double *pcom,*xicom;
1680: double (*nrfunc)(double []);
1681:
1682: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1683: {
1684: double brent(double ax, double bx, double cx,
1685: double (*f)(double), double tol, double *xmin);
1686: double f1dim(double x);
1687: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1688: double *fc, double (*func)(double));
1689: int j;
1690: double xx,xmin,bx,ax;
1691: double fx,fb,fa;
1692:
1693: #ifdef LINMINORIGINAL
1694: #else
1695: double scale=10., axs, xxs; /* Scale added for infinity */
1696: #endif
1697:
1698: ncom=n;
1699: pcom=vector(1,n);
1700: xicom=vector(1,n);
1701: nrfunc=func;
1702: for (j=1;j<=n;j++) {
1703: pcom[j]=p[j];
1704: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1705: }
1706:
1707: #ifdef LINMINORIGINAL
1708: xx=1.;
1709: #else
1710: axs=0.0;
1711: xxs=1.;
1712: do{
1713: xx= xxs;
1714: #endif
1715: ax=0.;
1716: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1717: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1718: /* 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)) */
1719: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1720: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1721: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1722: /* 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]]*/
1723: #ifdef LINMINORIGINAL
1724: #else
1725: if (fx != fx){
1726: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1727: printf("|");
1728: fprintf(ficlog,"|");
1729: #ifdef DEBUGLINMIN
1730: 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);
1731: #endif
1732: }
1733: }while(fx != fx);
1734: #endif
1735:
1736: #ifdef DEBUGLINMIN
1737: 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);
1738: 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);
1739: #endif
1740: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1741: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1742: /* fmin = f(p[j] + xmin * xi[j]) */
1743: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1744: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1745: #ifdef DEBUG
1746: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1747: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1748: #endif
1749: #ifdef DEBUGLINMIN
1750: printf("linmin end ");
1751: fprintf(ficlog,"linmin end ");
1752: #endif
1753: for (j=1;j<=n;j++) {
1754: #ifdef LINMINORIGINAL
1755: xi[j] *= xmin;
1756: #else
1757: #ifdef DEBUGLINMIN
1758: if(xxs <1.0)
1759: printf(" before xi[%d]=%12.8f", j,xi[j]);
1760: #endif
1761: 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) */
1762: #ifdef DEBUGLINMIN
1763: if(xxs <1.0)
1764: 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 );
1765: #endif
1766: #endif
1767: p[j] += xi[j]; /* Parameters values are updated accordingly */
1768: }
1769: #ifdef DEBUGLINMIN
1770: printf("\n");
1771: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1772: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1773: for (j=1;j<=n;j++) {
1774: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1775: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1776: if(j % ncovmodel == 0){
1777: printf("\n");
1778: fprintf(ficlog,"\n");
1779: }
1780: }
1781: #else
1782: #endif
1783: free_vector(xicom,1,n);
1784: free_vector(pcom,1,n);
1785: }
1786:
1787:
1788: /*************** powell ************************/
1789: /*
1790: Minimization of a function func of n variables. Input consists of an initial starting point
1791: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1792: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1793: such that failure to decrease by more than this amount on one iteration signals doneness. On
1794: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1795: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1796: */
1797: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1798: double (*func)(double []))
1799: {
1800: void linmin(double p[], double xi[], int n, double *fret,
1801: double (*func)(double []));
1802: int i,ibig,j;
1803: double del,t,*pt,*ptt,*xit;
1804: double directest;
1805: double fp,fptt;
1806: double *xits;
1807: int niterf, itmp;
1808:
1809: pt=vector(1,n);
1810: ptt=vector(1,n);
1811: xit=vector(1,n);
1812: xits=vector(1,n);
1813: *fret=(*func)(p);
1814: for (j=1;j<=n;j++) pt[j]=p[j];
1815: rcurr_time = time(NULL);
1816: for (*iter=1;;++(*iter)) {
1817: fp=(*fret); /* From former iteration or initial value */
1818: ibig=0;
1819: del=0.0;
1820: rlast_time=rcurr_time;
1821: /* (void) gettimeofday(&curr_time,&tzp); */
1822: rcurr_time = time(NULL);
1823: curr_time = *localtime(&rcurr_time);
1824: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1825: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1826: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1827: for (i=1;i<=n;i++) {
1828: printf(" %d %.12f",i, p[i]);
1829: fprintf(ficlog," %d %.12lf",i, p[i]);
1830: fprintf(ficrespow," %.12lf", p[i]);
1831: }
1832: printf("\n");
1833: fprintf(ficlog,"\n");
1834: fprintf(ficrespow,"\n");fflush(ficrespow);
1835: if(*iter <=3){
1836: tml = *localtime(&rcurr_time);
1837: strcpy(strcurr,asctime(&tml));
1838: rforecast_time=rcurr_time;
1839: itmp = strlen(strcurr);
1840: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1841: strcurr[itmp-1]='\0';
1842: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1843: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1844: for(niterf=10;niterf<=30;niterf+=10){
1845: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1846: forecast_time = *localtime(&rforecast_time);
1847: strcpy(strfor,asctime(&forecast_time));
1848: itmp = strlen(strfor);
1849: if(strfor[itmp-1]=='\n')
1850: strfor[itmp-1]='\0';
1851: 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);
1852: 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);
1853: }
1854: }
1855: for (i=1;i<=n;i++) { /* For each direction i */
1856: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1857: fptt=(*fret);
1858: #ifdef DEBUG
1859: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1860: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1861: #endif
1862: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1863: fprintf(ficlog,"%d",i);fflush(ficlog);
1864: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1865: /* Outputs are fret(new point p) p is updated and xit rescaled */
1866: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1867: /* because that direction will be replaced unless the gain del is small */
1868: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1869: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1870: /* with the new direction. */
1871: del=fabs(fptt-(*fret));
1872: ibig=i;
1873: }
1874: #ifdef DEBUG
1875: printf("%d %.12e",i,(*fret));
1876: fprintf(ficlog,"%d %.12e",i,(*fret));
1877: for (j=1;j<=n;j++) {
1878: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1879: printf(" x(%d)=%.12e",j,xit[j]);
1880: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1881: }
1882: for(j=1;j<=n;j++) {
1883: printf(" p(%d)=%.12e",j,p[j]);
1884: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1885: }
1886: printf("\n");
1887: fprintf(ficlog,"\n");
1888: #endif
1889: } /* end loop on each direction i */
1890: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1891: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1892: /* New value of last point Pn is not computed, P(n-1) */
1893: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1894: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1895: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1896: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1897: /* decreased of more than 3.84 */
1898: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1899: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1900: /* By adding 10 parameters more the gain should be 18.31 */
1901:
1902: /* Starting the program with initial values given by a former maximization will simply change */
1903: /* the scales of the directions and the directions, because the are reset to canonical directions */
1904: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1905: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1906: #ifdef DEBUG
1907: int k[2],l;
1908: k[0]=1;
1909: k[1]=-1;
1910: printf("Max: %.12e",(*func)(p));
1911: fprintf(ficlog,"Max: %.12e",(*func)(p));
1912: for (j=1;j<=n;j++) {
1913: printf(" %.12e",p[j]);
1914: fprintf(ficlog," %.12e",p[j]);
1915: }
1916: printf("\n");
1917: fprintf(ficlog,"\n");
1918: for(l=0;l<=1;l++) {
1919: for (j=1;j<=n;j++) {
1920: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1921: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1922: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1923: }
1924: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1925: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1926: }
1927: #endif
1928:
1929:
1930: free_vector(xit,1,n);
1931: free_vector(xits,1,n);
1932: free_vector(ptt,1,n);
1933: free_vector(pt,1,n);
1934: return;
1935: } /* enough precision */
1936: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1937: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1938: ptt[j]=2.0*p[j]-pt[j];
1939: xit[j]=p[j]-pt[j];
1940: pt[j]=p[j];
1941: }
1942: fptt=(*func)(ptt); /* f_3 */
1943: #ifdef POWELLF1F3
1944: #else
1945: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1946: #endif
1947: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1948: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1949: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1950: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1951: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1952: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1953: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1954: #ifdef NRCORIGINAL
1955: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1956: #else
1957: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1958: t= t- del*SQR(fp-fptt);
1959: #endif
1960: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1961: #ifdef DEBUG
1962: 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);
1963: 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);
1964: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1965: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1966: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1967: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1968: 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);
1969: 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);
1970: #endif
1971: #ifdef POWELLORIGINAL
1972: if (t < 0.0) { /* Then we use it for new direction */
1973: #else
1974: if (directest*t < 0.0) { /* Contradiction between both tests */
1975: 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);
1976: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1977: 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);
1978: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1979: }
1980: if (directest < 0.0) { /* Then we use it for new direction */
1981: #endif
1982: #ifdef DEBUGLINMIN
1983: printf("Before linmin in direction P%d-P0\n",n);
1984: for (j=1;j<=n;j++) {
1985: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1986: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1987: if(j % ncovmodel == 0){
1988: printf("\n");
1989: fprintf(ficlog,"\n");
1990: }
1991: }
1992: #endif
1993: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1994: #ifdef DEBUGLINMIN
1995: for (j=1;j<=n;j++) {
1996: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1997: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1998: if(j % ncovmodel == 0){
1999: printf("\n");
2000: fprintf(ficlog,"\n");
2001: }
2002: }
2003: #endif
2004: for (j=1;j<=n;j++) {
2005: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
2006: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
2007: }
2008: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2009: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2010:
2011: #ifdef DEBUG
2012: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2013: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2014: for(j=1;j<=n;j++){
2015: printf(" %.12e",xit[j]);
2016: fprintf(ficlog," %.12e",xit[j]);
2017: }
2018: printf("\n");
2019: fprintf(ficlog,"\n");
2020: #endif
2021: } /* end of t or directest negative */
2022: #ifdef POWELLF1F3
2023: #else
2024: } /* end if (fptt < fp) */
2025: #endif
2026: } /* loop iteration */
2027: }
2028:
2029: /**** Prevalence limit (stable or period prevalence) ****************/
2030:
2031: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
2032: {
2033: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
2034: matrix by transitions matrix until convergence is reached with precision ftolpl */
2035: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2036: /* Wx is row vector: population in state 1, population in state 2, population dead */
2037: /* or prevalence in state 1, prevalence in state 2, 0 */
2038: /* newm is the matrix after multiplications, its rows are identical at a factor */
2039: /* Initial matrix pimij */
2040: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2041: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2042: /* 0, 0 , 1} */
2043: /*
2044: * and after some iteration: */
2045: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2046: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2047: /* 0, 0 , 1} */
2048: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2049: /* {0.51571254859325999, 0.4842874514067399, */
2050: /* 0.51326036147820708, 0.48673963852179264} */
2051: /* If we start from prlim again, prlim tends to a constant matrix */
2052:
2053: int i, ii,j,k;
2054: double *min, *max, *meandiff, maxmax,sumnew=0.;
2055: /* double **matprod2(); */ /* test */
2056: double **out, cov[NCOVMAX+1], **pmij();
2057: double **newm;
2058: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2059: int ncvloop=0;
2060:
2061: min=vector(1,nlstate);
2062: max=vector(1,nlstate);
2063: meandiff=vector(1,nlstate);
2064:
2065: for (ii=1;ii<=nlstate+ndeath;ii++)
2066: for (j=1;j<=nlstate+ndeath;j++){
2067: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2068: }
2069:
2070: cov[1]=1.;
2071:
2072: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2073: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2074: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2075: ncvloop++;
2076: newm=savm;
2077: /* Covariates have to be included here again */
2078: cov[2]=agefin;
2079: if(nagesqr==1)
2080: cov[3]= agefin*agefin;;
2081: for (k=1; k<=cptcovn;k++) {
2082: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2083: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2084: /* 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])]); */
2085: }
2086: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2087: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2088: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2089: for (k=1; k<=cptcovprod;k++) /* Useless */
2090: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2091: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2092:
2093: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2094: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2095: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2096: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2097: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2098: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2099:
2100: savm=oldm;
2101: oldm=newm;
2102:
2103: for(j=1; j<=nlstate; j++){
2104: max[j]=0.;
2105: min[j]=1.;
2106: }
2107: for(i=1;i<=nlstate;i++){
2108: sumnew=0;
2109: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2110: for(j=1; j<=nlstate; j++){
2111: prlim[i][j]= newm[i][j]/(1-sumnew);
2112: max[j]=FMAX(max[j],prlim[i][j]);
2113: min[j]=FMIN(min[j],prlim[i][j]);
2114: }
2115: }
2116:
2117: maxmax=0.;
2118: for(j=1; j<=nlstate; j++){
2119: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2120: maxmax=FMAX(maxmax,meandiff[j]);
2121: /* 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); */
2122: } /* j loop */
2123: *ncvyear= (int)age- (int)agefin;
2124: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2125: if(maxmax < ftolpl){
2126: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2127: free_vector(min,1,nlstate);
2128: free_vector(max,1,nlstate);
2129: free_vector(meandiff,1,nlstate);
2130: return prlim;
2131: }
2132: } /* age loop */
2133: /* After some age loop it doesn't converge */
2134: 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\
2135: 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);
2136: /* 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); */
2137: free_vector(min,1,nlstate);
2138: free_vector(max,1,nlstate);
2139: free_vector(meandiff,1,nlstate);
2140:
2141: return prlim; /* should not reach here */
2142: }
2143:
2144: /*************** transition probabilities ***************/
2145:
2146: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2147: {
2148: /* According to parameters values stored in x and the covariate's values stored in cov,
2149: computes the probability to be observed in state j being in state i by appying the
2150: model to the ncovmodel covariates (including constant and age).
2151: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2152: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2153: ncth covariate in the global vector x is given by the formula:
2154: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2155: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2156: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2157: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2158: Outputs ps[i][j] the probability to be observed in j being in j according to
2159: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2160: */
2161: double s1, lnpijopii;
2162: /*double t34;*/
2163: int i,j, nc, ii, jj;
2164:
2165: for(i=1; i<= nlstate; i++){
2166: for(j=1; j<i;j++){
2167: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2168: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2169: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2170: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2171: }
2172: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2173: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2174: }
2175: for(j=i+1; j<=nlstate+ndeath;j++){
2176: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2177: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2178: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2179: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2180: }
2181: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2182: }
2183: }
2184:
2185: for(i=1; i<= nlstate; i++){
2186: s1=0;
2187: for(j=1; j<i; j++){
2188: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2189: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2190: }
2191: for(j=i+1; j<=nlstate+ndeath; j++){
2192: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2193: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2194: }
2195: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2196: ps[i][i]=1./(s1+1.);
2197: /* Computing other pijs */
2198: for(j=1; j<i; j++)
2199: ps[i][j]= exp(ps[i][j])*ps[i][i];
2200: for(j=i+1; j<=nlstate+ndeath; j++)
2201: ps[i][j]= exp(ps[i][j])*ps[i][i];
2202: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2203: } /* end i */
2204:
2205: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2206: for(jj=1; jj<= nlstate+ndeath; jj++){
2207: ps[ii][jj]=0;
2208: ps[ii][ii]=1;
2209: }
2210: }
2211:
2212:
2213: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2214: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2215: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2216: /* } */
2217: /* printf("\n "); */
2218: /* } */
2219: /* printf("\n ");printf("%lf ",cov[2]);*/
2220: /*
2221: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2222: goto end;*/
2223: return ps;
2224: }
2225:
2226: /**************** Product of 2 matrices ******************/
2227:
2228: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2229: {
2230: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2231: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2232: /* in, b, out are matrice of pointers which should have been initialized
2233: before: only the contents of out is modified. The function returns
2234: a pointer to pointers identical to out */
2235: int i, j, k;
2236: for(i=nrl; i<= nrh; i++)
2237: for(k=ncolol; k<=ncoloh; k++){
2238: out[i][k]=0.;
2239: for(j=ncl; j<=nch; j++)
2240: out[i][k] +=in[i][j]*b[j][k];
2241: }
2242: return out;
2243: }
2244:
2245:
2246: /************* Higher Matrix Product ***************/
2247:
2248: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2249: {
2250: /* Computes the transition matrix starting at age 'age' over
2251: 'nhstepm*hstepm*stepm' months (i.e. until
2252: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2253: nhstepm*hstepm matrices.
2254: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2255: (typically every 2 years instead of every month which is too big
2256: for the memory).
2257: Model is determined by parameters x and covariates have to be
2258: included manually here.
2259:
2260: */
2261:
2262: int i, j, d, h, k;
2263: double **out, cov[NCOVMAX+1];
2264: double **newm;
2265: double agexact;
2266: double agebegin, ageend;
2267:
2268: /* Hstepm could be zero and should return the unit matrix */
2269: for (i=1;i<=nlstate+ndeath;i++)
2270: for (j=1;j<=nlstate+ndeath;j++){
2271: oldm[i][j]=(i==j ? 1.0 : 0.0);
2272: po[i][j][0]=(i==j ? 1.0 : 0.0);
2273: }
2274: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2275: for(h=1; h <=nhstepm; h++){
2276: for(d=1; d <=hstepm; d++){
2277: newm=savm;
2278: /* Covariates have to be included here again */
2279: cov[1]=1.;
2280: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
2281: cov[2]=agexact;
2282: if(nagesqr==1)
2283: cov[3]= agexact*agexact;
2284: for (k=1; k<=cptcovn;k++)
2285: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2286: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2287: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2288: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2289: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2290: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2291: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2292: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2293: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2294:
2295:
2296: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2297: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2298: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2299: pmij(pmmij,cov,ncovmodel,x,nlstate));
2300: savm=oldm;
2301: oldm=newm;
2302: }
2303: for(i=1; i<=nlstate+ndeath; i++)
2304: for(j=1;j<=nlstate+ndeath;j++) {
2305: po[i][j][h]=newm[i][j];
2306: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2307: }
2308: /*printf("h=%d ",h);*/
2309: } /* end h */
2310: /* printf("\n H=%d \n",h); */
2311: return po;
2312: }
2313:
2314: #ifdef NLOPT
2315: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2316: double fret;
2317: double *xt;
2318: int j;
2319: myfunc_data *d2 = (myfunc_data *) pd;
2320: /* xt = (p1-1); */
2321: xt=vector(1,n);
2322: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2323:
2324: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2325: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2326: printf("Function = %.12lf ",fret);
2327: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2328: printf("\n");
2329: free_vector(xt,1,n);
2330: return fret;
2331: }
2332: #endif
2333:
2334: /*************** log-likelihood *************/
2335: double func( double *x)
2336: {
2337: int i, ii, j, k, mi, d, kk;
2338: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2339: double **out;
2340: double sw; /* Sum of weights */
2341: double lli; /* Individual log likelihood */
2342: int s1, s2;
2343: double bbh, survp;
2344: long ipmx;
2345: double agexact;
2346: /*extern weight */
2347: /* We are differentiating ll according to initial status */
2348: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2349: /*for(i=1;i<imx;i++)
2350: printf(" %d\n",s[4][i]);
2351: */
2352:
2353: ++countcallfunc;
2354:
2355: cov[1]=1.;
2356:
2357: for(k=1; k<=nlstate; k++) ll[k]=0.;
2358:
2359: if(mle==1){
2360: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2361: /* Computes the values of the ncovmodel covariates of the model
2362: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2363: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2364: to be observed in j being in i according to the model.
2365: */
2366: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2367: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2368: }
2369: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2370: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2371: has been calculated etc */
2372: for(mi=1; mi<= wav[i]-1; mi++){
2373: for (ii=1;ii<=nlstate+ndeath;ii++)
2374: for (j=1;j<=nlstate+ndeath;j++){
2375: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2376: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2377: }
2378: for(d=0; d<dh[mi][i]; d++){
2379: newm=savm;
2380: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2381: cov[2]=agexact;
2382: if(nagesqr==1)
2383: cov[3]= agexact*agexact;
2384: for (kk=1; kk<=cptcovage;kk++) {
2385: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2386: }
2387: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2388: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2389: savm=oldm;
2390: oldm=newm;
2391: } /* end mult */
2392:
2393: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2394: /* But now since version 0.9 we anticipate for bias at large stepm.
2395: * If stepm is larger than one month (smallest stepm) and if the exact delay
2396: * (in months) between two waves is not a multiple of stepm, we rounded to
2397: * the nearest (and in case of equal distance, to the lowest) interval but now
2398: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2399: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2400: * probability in order to take into account the bias as a fraction of the way
2401: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2402: * -stepm/2 to stepm/2 .
2403: * For stepm=1 the results are the same as for previous versions of Imach.
2404: * For stepm > 1 the results are less biased than in previous versions.
2405: */
2406: s1=s[mw[mi][i]][i];
2407: s2=s[mw[mi+1][i]][i];
2408: bbh=(double)bh[mi][i]/(double)stepm;
2409: /* bias bh is positive if real duration
2410: * is higher than the multiple of stepm and negative otherwise.
2411: */
2412: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2413: if( s2 > nlstate){
2414: /* i.e. if s2 is a death state and if the date of death is known
2415: then the contribution to the likelihood is the probability to
2416: die between last step unit time and current step unit time,
2417: which is also equal to probability to die before dh
2418: minus probability to die before dh-stepm .
2419: In version up to 0.92 likelihood was computed
2420: as if date of death was unknown. Death was treated as any other
2421: health state: the date of the interview describes the actual state
2422: and not the date of a change in health state. The former idea was
2423: to consider that at each interview the state was recorded
2424: (healthy, disable or death) and IMaCh was corrected; but when we
2425: introduced the exact date of death then we should have modified
2426: the contribution of an exact death to the likelihood. This new
2427: contribution is smaller and very dependent of the step unit
2428: stepm. It is no more the probability to die between last interview
2429: and month of death but the probability to survive from last
2430: interview up to one month before death multiplied by the
2431: probability to die within a month. Thanks to Chris
2432: Jackson for correcting this bug. Former versions increased
2433: mortality artificially. The bad side is that we add another loop
2434: which slows down the processing. The difference can be up to 10%
2435: lower mortality.
2436: */
2437: /* If, at the beginning of the maximization mostly, the
2438: cumulative probability or probability to be dead is
2439: constant (ie = 1) over time d, the difference is equal to
2440: 0. out[s1][3] = savm[s1][3]: probability, being at state
2441: s1 at precedent wave, to be dead a month before current
2442: wave is equal to probability, being at state s1 at
2443: precedent wave, to be dead at mont of the current
2444: wave. Then the observed probability (that this person died)
2445: is null according to current estimated parameter. In fact,
2446: it should be very low but not zero otherwise the log go to
2447: infinity.
2448: */
2449: /* #ifdef INFINITYORIGINAL */
2450: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2451: /* #else */
2452: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2453: /* lli=log(mytinydouble); */
2454: /* else */
2455: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2456: /* #endif */
2457: lli=log(out[s1][s2] - savm[s1][s2]);
2458:
2459: } else if ( s2==-1 ) { /* alive */
2460: for (j=1,survp=0. ; j<=nlstate; j++)
2461: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2462: /*survp += out[s1][j]; */
2463: lli= log(survp);
2464: }
2465: else if (s2==-4) {
2466: for (j=3,survp=0. ; j<=nlstate; j++)
2467: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2468: lli= log(survp);
2469: }
2470: else if (s2==-5) {
2471: for (j=1,survp=0. ; j<=2; j++)
2472: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2473: lli= log(survp);
2474: }
2475: else{
2476: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
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: }
2479: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2480: /*if(lli ==000.0)*/
2481: /*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); */
2482: ipmx +=1;
2483: sw += weight[i];
2484: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2485: /* if (lli < log(mytinydouble)){ */
2486: /* 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); */
2487: /* 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]); */
2488: /* } */
2489: } /* end of wave */
2490: } /* end of individual */
2491: } else if(mle==2){
2492: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2493: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2494: for(mi=1; mi<= wav[i]-1; mi++){
2495: for (ii=1;ii<=nlstate+ndeath;ii++)
2496: for (j=1;j<=nlstate+ndeath;j++){
2497: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2498: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2499: }
2500: for(d=0; d<=dh[mi][i]; d++){
2501: newm=savm;
2502: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2503: cov[2]=agexact;
2504: if(nagesqr==1)
2505: cov[3]= agexact*agexact;
2506: for (kk=1; kk<=cptcovage;kk++) {
2507: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2508: }
2509: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2510: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2511: savm=oldm;
2512: oldm=newm;
2513: } /* end mult */
2514:
2515: s1=s[mw[mi][i]][i];
2516: s2=s[mw[mi+1][i]][i];
2517: bbh=(double)bh[mi][i]/(double)stepm;
2518: 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 */
2519: ipmx +=1;
2520: sw += weight[i];
2521: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2522: } /* end of wave */
2523: } /* end of individual */
2524: } else if(mle==3){ /* exponential inter-extrapolation */
2525: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2526: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2527: for(mi=1; mi<= wav[i]-1; mi++){
2528: for (ii=1;ii<=nlstate+ndeath;ii++)
2529: for (j=1;j<=nlstate+ndeath;j++){
2530: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2531: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2532: }
2533: for(d=0; d<dh[mi][i]; d++){
2534: newm=savm;
2535: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2536: cov[2]=agexact;
2537: if(nagesqr==1)
2538: cov[3]= agexact*agexact;
2539: for (kk=1; kk<=cptcovage;kk++) {
2540: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2541: }
2542: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2543: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2544: savm=oldm;
2545: oldm=newm;
2546: } /* end mult */
2547:
2548: s1=s[mw[mi][i]][i];
2549: s2=s[mw[mi+1][i]][i];
2550: bbh=(double)bh[mi][i]/(double)stepm;
2551: 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 */
2552: ipmx +=1;
2553: sw += weight[i];
2554: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2555: } /* end of wave */
2556: } /* end of individual */
2557: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2558: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2559: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2560: for(mi=1; mi<= wav[i]-1; mi++){
2561: for (ii=1;ii<=nlstate+ndeath;ii++)
2562: for (j=1;j<=nlstate+ndeath;j++){
2563: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2564: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2565: }
2566: for(d=0; d<dh[mi][i]; d++){
2567: newm=savm;
2568: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2569: cov[2]=agexact;
2570: if(nagesqr==1)
2571: cov[3]= agexact*agexact;
2572: for (kk=1; kk<=cptcovage;kk++) {
2573: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2574: }
2575:
2576: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2577: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2578: savm=oldm;
2579: oldm=newm;
2580: } /* end mult */
2581:
2582: s1=s[mw[mi][i]][i];
2583: s2=s[mw[mi+1][i]][i];
2584: if( s2 > nlstate){
2585: lli=log(out[s1][s2] - savm[s1][s2]);
2586: } else if ( s2==-1 ) { /* alive */
2587: for (j=1,survp=0. ; j<=nlstate; j++)
2588: survp += out[s1][j];
2589: lli= log(survp);
2590: }else{
2591: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2592: }
2593: ipmx +=1;
2594: sw += weight[i];
2595: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2596: /* 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]); */
2597: } /* end of wave */
2598: } /* end of individual */
2599: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2600: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2601: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2602: for(mi=1; mi<= wav[i]-1; mi++){
2603: for (ii=1;ii<=nlstate+ndeath;ii++)
2604: for (j=1;j<=nlstate+ndeath;j++){
2605: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2606: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2607: }
2608: for(d=0; d<dh[mi][i]; d++){
2609: newm=savm;
2610: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2611: cov[2]=agexact;
2612: if(nagesqr==1)
2613: cov[3]= agexact*agexact;
2614: for (kk=1; kk<=cptcovage;kk++) {
2615: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2616: }
2617:
2618: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2619: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2620: savm=oldm;
2621: oldm=newm;
2622: } /* end mult */
2623:
2624: s1=s[mw[mi][i]][i];
2625: s2=s[mw[mi+1][i]][i];
2626: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2627: ipmx +=1;
2628: sw += weight[i];
2629: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2630: /*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]);*/
2631: } /* end of wave */
2632: } /* end of individual */
2633: } /* End of if */
2634: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2635: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2636: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2637: return -l;
2638: }
2639:
2640: /*************** log-likelihood *************/
2641: double funcone( double *x)
2642: {
2643: /* Same as likeli but slower because of a lot of printf and if */
2644: int i, ii, j, k, mi, d, kk;
2645: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2646: double **out;
2647: double lli; /* Individual log likelihood */
2648: double llt;
2649: int s1, s2;
2650: double bbh, survp;
2651: double agexact;
2652: double agebegin, ageend;
2653: /*extern weight */
2654: /* We are differentiating ll according to initial status */
2655: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2656: /*for(i=1;i<imx;i++)
2657: printf(" %d\n",s[4][i]);
2658: */
2659: cov[1]=1.;
2660:
2661: for(k=1; k<=nlstate; k++) ll[k]=0.;
2662:
2663: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2664: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2665: for(mi=1; mi<= wav[i]-1; mi++){
2666: for (ii=1;ii<=nlstate+ndeath;ii++)
2667: for (j=1;j<=nlstate+ndeath;j++){
2668: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2669: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2670: }
2671:
2672: agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
2673: ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
2674: for(d=0; d<dh[mi][i]; d++){ /* Delay between two effective waves */
2675: /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2676: and mw[mi+1][i]. dh depends on stepm.*/
2677: newm=savm;
2678: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2679: cov[2]=agexact;
2680: if(nagesqr==1)
2681: cov[3]= agexact*agexact;
2682: for (kk=1; kk<=cptcovage;kk++) {
2683: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2684: }
2685:
2686: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2687: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2688: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2689: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2690: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2691: savm=oldm;
2692: oldm=newm;
2693: } /* end mult */
2694:
2695: s1=s[mw[mi][i]][i];
2696: s2=s[mw[mi+1][i]][i];
2697: if(s2==-1){
2698: printf(" s1=%d, s2=%d i=%d \n", s1, s2, i);
2699: /* exit(1); */
2700: }
2701: bbh=(double)bh[mi][i]/(double)stepm;
2702: /* bias is positive if real duration
2703: * is higher than the multiple of stepm and negative otherwise.
2704: */
2705: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2706: lli=log(out[s1][s2] - savm[s1][s2]);
2707: } else if ( s2==-1 ) { /* alive */
2708: for (j=1,survp=0. ; j<=nlstate; j++)
2709: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2710: lli= log(survp);
2711: }else if (mle==1){
2712: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2713: } else if(mle==2){
2714: 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 */
2715: } else if(mle==3){ /* exponential inter-extrapolation */
2716: 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 */
2717: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2718: lli=log(out[s1][s2]); /* Original formula */
2719: } else{ /* mle=0 back to 1 */
2720: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2721: /*lli=log(out[s1][s2]); */ /* Original formula */
2722: } /* End of if */
2723: ipmx +=1;
2724: sw += weight[i];
2725: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2726: /*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]); */
2727: if(globpr){
2728: fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2729: %11.6f %11.6f %11.6f ", \
2730: num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2731: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2732: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2733: llt +=ll[k]*gipmx/gsw;
2734: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2735: }
2736: fprintf(ficresilk," %10.6f\n", -llt);
2737: }
2738: } /* end of wave */
2739: } /* end of individual */
2740: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2741: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2742: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2743: if(globpr==0){ /* First time we count the contributions and weights */
2744: gipmx=ipmx;
2745: gsw=sw;
2746: }
2747: return -l;
2748: }
2749:
2750:
2751: /*************** function likelione ***********/
2752: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2753: {
2754: /* This routine should help understanding what is done with
2755: the selection of individuals/waves and
2756: to check the exact contribution to the likelihood.
2757: Plotting could be done.
2758: */
2759: int k;
2760:
2761: if(*globpri !=0){ /* Just counts and sums, no printings */
2762: strcpy(fileresilk,"ILK_");
2763: strcat(fileresilk,fileresu);
2764: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2765: printf("Problem with resultfile: %s\n", fileresilk);
2766: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2767: }
2768: fprintf(ficresilk, "#individual(line's_record) count ageb ageend 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");
2769: fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
2770: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2771: for(k=1; k<=nlstate; k++)
2772: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2773: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2774: }
2775:
2776: *fretone=(*funcone)(p);
2777: if(*globpri !=0){
2778: fclose(ficresilk);
2779: if (mle ==0)
2780: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2781: else if(mle >=1)
2782: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2783: 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));
2784:
2785:
2786: for (k=1; k<= nlstate ; k++) {
2787: 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> \
2788: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2789: }
2790: 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> \
2791: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2792: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2793: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2794: fflush(fichtm);
2795: }
2796: return;
2797: }
2798:
2799:
2800: /*********** Maximum Likelihood Estimation ***************/
2801:
2802: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2803: {
2804: int i,j, iter=0;
2805: double **xi;
2806: double fret;
2807: double fretone; /* Only one call to likelihood */
2808: /* char filerespow[FILENAMELENGTH];*/
2809:
2810: #ifdef NLOPT
2811: int creturn;
2812: nlopt_opt opt;
2813: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2814: double *lb;
2815: double minf; /* the minimum objective value, upon return */
2816: double * p1; /* Shifted parameters from 0 instead of 1 */
2817: myfunc_data dinst, *d = &dinst;
2818: #endif
2819:
2820:
2821: xi=matrix(1,npar,1,npar);
2822: for (i=1;i<=npar;i++)
2823: for (j=1;j<=npar;j++)
2824: xi[i][j]=(i==j ? 1.0 : 0.0);
2825: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2826: strcpy(filerespow,"POW_");
2827: strcat(filerespow,fileres);
2828: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2829: printf("Problem with resultfile: %s\n", filerespow);
2830: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2831: }
2832: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2833: for (i=1;i<=nlstate;i++)
2834: for(j=1;j<=nlstate+ndeath;j++)
2835: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2836: fprintf(ficrespow,"\n");
2837: #ifdef POWELL
2838: powell(p,xi,npar,ftol,&iter,&fret,func);
2839: #endif
2840:
2841: #ifdef NLOPT
2842: #ifdef NEWUOA
2843: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2844: #else
2845: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2846: #endif
2847: lb=vector(0,npar-1);
2848: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2849: nlopt_set_lower_bounds(opt, lb);
2850: nlopt_set_initial_step1(opt, 0.1);
2851:
2852: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2853: d->function = func;
2854: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2855: nlopt_set_min_objective(opt, myfunc, d);
2856: nlopt_set_xtol_rel(opt, ftol);
2857: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2858: printf("nlopt failed! %d\n",creturn);
2859: }
2860: else {
2861: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2862: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2863: iter=1; /* not equal */
2864: }
2865: nlopt_destroy(opt);
2866: #endif
2867: free_matrix(xi,1,npar,1,npar);
2868: fclose(ficrespow);
2869: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2870: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2871: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2872:
2873: }
2874:
2875: /**** Computes Hessian and covariance matrix ***/
2876: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2877: {
2878: double **a,**y,*x,pd;
2879: /* double **hess; */
2880: int i, j;
2881: int *indx;
2882:
2883: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2884: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2885: void lubksb(double **a, int npar, int *indx, double b[]) ;
2886: void ludcmp(double **a, int npar, int *indx, double *d) ;
2887: double gompertz(double p[]);
2888: /* hess=matrix(1,npar,1,npar); */
2889:
2890: printf("\nCalculation of the hessian matrix. Wait...\n");
2891: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2892: for (i=1;i<=npar;i++){
2893: printf("%d-",i);fflush(stdout);
2894: fprintf(ficlog,"%d-",i);fflush(ficlog);
2895:
2896: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2897:
2898: /* printf(" %f ",p[i]);
2899: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2900: }
2901:
2902: for (i=1;i<=npar;i++) {
2903: for (j=1;j<=npar;j++) {
2904: if (j>i) {
2905: printf(".%d-%d",i,j);fflush(stdout);
2906: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2907: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2908:
2909: hess[j][i]=hess[i][j];
2910: /*printf(" %lf ",hess[i][j]);*/
2911: }
2912: }
2913: }
2914: printf("\n");
2915: fprintf(ficlog,"\n");
2916:
2917: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2918: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2919:
2920: a=matrix(1,npar,1,npar);
2921: y=matrix(1,npar,1,npar);
2922: x=vector(1,npar);
2923: indx=ivector(1,npar);
2924: for (i=1;i<=npar;i++)
2925: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2926: ludcmp(a,npar,indx,&pd);
2927:
2928: for (j=1;j<=npar;j++) {
2929: for (i=1;i<=npar;i++) x[i]=0;
2930: x[j]=1;
2931: lubksb(a,npar,indx,x);
2932: for (i=1;i<=npar;i++){
2933: matcov[i][j]=x[i];
2934: }
2935: }
2936:
2937: printf("\n#Hessian matrix#\n");
2938: fprintf(ficlog,"\n#Hessian matrix#\n");
2939: for (i=1;i<=npar;i++) {
2940: for (j=1;j<=npar;j++) {
2941: printf("%.6e ",hess[i][j]);
2942: fprintf(ficlog,"%.6e ",hess[i][j]);
2943: }
2944: printf("\n");
2945: fprintf(ficlog,"\n");
2946: }
2947:
2948: /* printf("\n#Covariance matrix#\n"); */
2949: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2950: /* for (i=1;i<=npar;i++) { */
2951: /* for (j=1;j<=npar;j++) { */
2952: /* printf("%.6e ",matcov[i][j]); */
2953: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2954: /* } */
2955: /* printf("\n"); */
2956: /* fprintf(ficlog,"\n"); */
2957: /* } */
2958:
2959: /* Recompute Inverse */
2960: /* for (i=1;i<=npar;i++) */
2961: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2962: /* ludcmp(a,npar,indx,&pd); */
2963:
2964: /* printf("\n#Hessian matrix recomputed#\n"); */
2965:
2966: /* for (j=1;j<=npar;j++) { */
2967: /* for (i=1;i<=npar;i++) x[i]=0; */
2968: /* x[j]=1; */
2969: /* lubksb(a,npar,indx,x); */
2970: /* for (i=1;i<=npar;i++){ */
2971: /* y[i][j]=x[i]; */
2972: /* printf("%.3e ",y[i][j]); */
2973: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2974: /* } */
2975: /* printf("\n"); */
2976: /* fprintf(ficlog,"\n"); */
2977: /* } */
2978:
2979: /* Verifying the inverse matrix */
2980: #ifdef DEBUGHESS
2981: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2982:
2983: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2984: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2985:
2986: for (j=1;j<=npar;j++) {
2987: for (i=1;i<=npar;i++){
2988: printf("%.2f ",y[i][j]);
2989: fprintf(ficlog,"%.2f ",y[i][j]);
2990: }
2991: printf("\n");
2992: fprintf(ficlog,"\n");
2993: }
2994: #endif
2995:
2996: free_matrix(a,1,npar,1,npar);
2997: free_matrix(y,1,npar,1,npar);
2998: free_vector(x,1,npar);
2999: free_ivector(indx,1,npar);
3000: /* free_matrix(hess,1,npar,1,npar); */
3001:
3002:
3003: }
3004:
3005: /*************** hessian matrix ****************/
3006: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
3007: { /* Around values of x, computes the function func and returns the scales delti and hessian */
3008: int i;
3009: int l=1, lmax=20;
3010: double k1,k2, res, fx;
3011: double p2[MAXPARM+1]; /* identical to x */
3012: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
3013: int k=0,kmax=10;
3014: double l1;
3015:
3016: fx=func(x);
3017: for (i=1;i<=npar;i++) p2[i]=x[i];
3018: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
3019: l1=pow(10,l);
3020: delts=delt;
3021: for(k=1 ; k <kmax; k=k+1){
3022: delt = delta*(l1*k);
3023: p2[theta]=x[theta] +delt;
3024: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
3025: p2[theta]=x[theta]-delt;
3026: k2=func(p2)-fx;
3027: /*res= (k1-2.0*fx+k2)/delt/delt; */
3028: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
3029:
3030: #ifdef DEBUGHESSII
3031: 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);
3032: 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);
3033: #endif
3034: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3035: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3036: k=kmax;
3037: }
3038: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
3039: k=kmax; l=lmax*10;
3040: }
3041: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3042: delts=delt;
3043: }
3044: } /* End loop k */
3045: }
3046: delti[theta]=delts;
3047: return res;
3048:
3049: }
3050:
3051: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
3052: {
3053: int i;
3054: int l=1, lmax=20;
3055: double k1,k2,k3,k4,res,fx;
3056: double p2[MAXPARM+1];
3057: int k, kmax=1;
3058: double v1, v2, cv12, lc1, lc2;
3059:
3060: int firstime=0;
3061:
3062: fx=func(x);
3063: for (k=1; k<=kmax; k=k+10) {
3064: for (i=1;i<=npar;i++) p2[i]=x[i];
3065: p2[thetai]=x[thetai]+delti[thetai]*k;
3066: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3067: k1=func(p2)-fx;
3068:
3069: p2[thetai]=x[thetai]+delti[thetai]*k;
3070: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3071: k2=func(p2)-fx;
3072:
3073: p2[thetai]=x[thetai]-delti[thetai]*k;
3074: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3075: k3=func(p2)-fx;
3076:
3077: p2[thetai]=x[thetai]-delti[thetai]*k;
3078: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3079: k4=func(p2)-fx;
3080: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3081: if(k1*k2*k3*k4 <0.){
3082: firstime=1;
3083: kmax=kmax+10;
3084: }
3085: if(kmax >=10 || firstime ==1){
3086: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3087: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3088: 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);
3089: 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);
3090: }
3091: #ifdef DEBUGHESSIJ
3092: v1=hess[thetai][thetai];
3093: v2=hess[thetaj][thetaj];
3094: cv12=res;
3095: /* Computing eigen value of Hessian matrix */
3096: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3097: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3098: if ((lc2 <0) || (lc1 <0) ){
3099: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3100: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3101: 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);
3102: 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);
3103: }
3104: #endif
3105: }
3106: return res;
3107: }
3108:
3109: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3110: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3111: /* { */
3112: /* int i; */
3113: /* int l=1, lmax=20; */
3114: /* double k1,k2,k3,k4,res,fx; */
3115: /* double p2[MAXPARM+1]; */
3116: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3117: /* int k=0,kmax=10; */
3118: /* double l1; */
3119:
3120: /* fx=func(x); */
3121: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3122: /* l1=pow(10,l); */
3123: /* delts=delt; */
3124: /* for(k=1 ; k <kmax; k=k+1){ */
3125: /* delt = delti*(l1*k); */
3126: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3127: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3128: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3129: /* k1=func(p2)-fx; */
3130:
3131: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3132: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3133: /* k2=func(p2)-fx; */
3134:
3135: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3136: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3137: /* k3=func(p2)-fx; */
3138:
3139: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3140: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3141: /* k4=func(p2)-fx; */
3142: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3143: /* #ifdef DEBUGHESSIJ */
3144: /* 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); */
3145: /* 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); */
3146: /* #endif */
3147: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3148: /* k=kmax; */
3149: /* } */
3150: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3151: /* k=kmax; l=lmax*10; */
3152: /* } */
3153: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3154: /* delts=delt; */
3155: /* } */
3156: /* } /\* End loop k *\/ */
3157: /* } */
3158: /* delti[theta]=delts; */
3159: /* return res; */
3160: /* } */
3161:
3162:
3163: /************** Inverse of matrix **************/
3164: void ludcmp(double **a, int n, int *indx, double *d)
3165: {
3166: int i,imax,j,k;
3167: double big,dum,sum,temp;
3168: double *vv;
3169:
3170: vv=vector(1,n);
3171: *d=1.0;
3172: for (i=1;i<=n;i++) {
3173: big=0.0;
3174: for (j=1;j<=n;j++)
3175: if ((temp=fabs(a[i][j])) > big) big=temp;
3176: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3177: vv[i]=1.0/big;
3178: }
3179: for (j=1;j<=n;j++) {
3180: for (i=1;i<j;i++) {
3181: sum=a[i][j];
3182: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3183: a[i][j]=sum;
3184: }
3185: big=0.0;
3186: for (i=j;i<=n;i++) {
3187: sum=a[i][j];
3188: for (k=1;k<j;k++)
3189: sum -= a[i][k]*a[k][j];
3190: a[i][j]=sum;
3191: if ( (dum=vv[i]*fabs(sum)) >= big) {
3192: big=dum;
3193: imax=i;
3194: }
3195: }
3196: if (j != imax) {
3197: for (k=1;k<=n;k++) {
3198: dum=a[imax][k];
3199: a[imax][k]=a[j][k];
3200: a[j][k]=dum;
3201: }
3202: *d = -(*d);
3203: vv[imax]=vv[j];
3204: }
3205: indx[j]=imax;
3206: if (a[j][j] == 0.0) a[j][j]=TINY;
3207: if (j != n) {
3208: dum=1.0/(a[j][j]);
3209: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3210: }
3211: }
3212: free_vector(vv,1,n); /* Doesn't work */
3213: ;
3214: }
3215:
3216: void lubksb(double **a, int n, int *indx, double b[])
3217: {
3218: int i,ii=0,ip,j;
3219: double sum;
3220:
3221: for (i=1;i<=n;i++) {
3222: ip=indx[i];
3223: sum=b[ip];
3224: b[ip]=b[i];
3225: if (ii)
3226: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3227: else if (sum) ii=i;
3228: b[i]=sum;
3229: }
3230: for (i=n;i>=1;i--) {
3231: sum=b[i];
3232: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3233: b[i]=sum/a[i][i];
3234: }
3235: }
3236:
3237: void pstamp(FILE *fichier)
3238: {
3239: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3240: }
3241:
3242: /************ Frequencies ********************/
3243: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
3244: int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
3245: int firstpass, int lastpass, int stepm, int weightopt, char model[])
3246: { /* Some frequencies */
3247:
3248: int i, m, jk, j1, bool, z1,j;
3249: int mi; /* Effective wave */
3250: int first;
3251: double ***freq; /* Frequencies */
3252: double *pp, **prop;
3253: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3254: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
3255: double agebegin, ageend;
3256:
3257: pp=vector(1,nlstate);
3258: prop=matrix(1,nlstate,iagemin,iagemax+3);
3259: strcpy(fileresp,"P_");
3260: strcat(fileresp,fileresu);
3261: /*strcat(fileresphtm,fileresu);*/
3262: if((ficresp=fopen(fileresp,"w"))==NULL) {
3263: printf("Problem with prevalence resultfile: %s\n", fileresp);
3264: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3265: exit(0);
3266: }
3267:
3268: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
3269: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
3270: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3271: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3272: fflush(ficlog);
3273: exit(70);
3274: }
3275: else{
3276: fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3277: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3278: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3279: fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3280: }
3281: fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
3282:
3283: strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
3284: if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
3285: printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3286: fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3287: fflush(ficlog);
3288: exit(70);
3289: }
3290: else{
3291: fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3292: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3293: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3294: fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3295: }
3296: fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
3297:
3298: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3299: j1=0;
3300:
3301: j=cptcoveff;
3302: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3303:
3304: first=1;
3305:
3306: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
3307: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3308: scanf("%d", i);*/
3309: for (i=-5; i<=nlstate+ndeath; i++)
3310: for (jk=-5; jk<=nlstate+ndeath; jk++)
3311: for(m=iagemin; m <= iagemax+3; m++)
3312: freq[i][jk][m]=0;
3313:
3314: for (i=1; i<=nlstate; i++)
3315: for(m=iagemin; m <= iagemax+3; m++)
3316: prop[i][m]=0;
3317:
3318: dateintsum=0;
3319: k2cpt=0;
3320: for (i=1; i<=imx; i++) { /* For each individual i */
3321: bool=1;
3322: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3323: for (z1=1; z1<=cptcoveff; z1++)
3324: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3325: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3326: bool=0;
3327: /* 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",
3328: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3329: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3330: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3331: }
3332: } /* cptcovn > 0 */
3333:
3334: if (bool==1){
3335: /* for(m=firstpass; m<=lastpass; m++){ */
3336: for(mi=1; mi<wav[i];mi++){
3337: m=mw[mi][i];
3338: /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
3339: and mw[mi+1][i]. dh depends on stepm. */
3340: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3341: ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
3342: if(m >=firstpass && m <=lastpass){
3343: k2=anint[m][i]+(mint[m][i]/12.);
3344: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3345: if(agev[m][i]==0) agev[m][i]=iagemax+1; /* All ages equal to 0 are in iagemax+1 */
3346: if(agev[m][i]==1) agev[m][i]=iagemax+2; /* All ages equal to 1 are in iagemax+2 */
3347: if (s[m][i]>0 && s[m][i]<=nlstate) /* If status at wave m is known and a live state */
3348: prop[s[m][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3349: if (m<lastpass) {
3350: /* if(s[m][i]==4 && s[m+1][i]==4) */
3351: /* printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
3352: if(s[m][i]==-1)
3353: printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
3354: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3355: /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
3356: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
3357: }
3358: }
3359: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
3360: dateintsum=dateintsum+k2;
3361: k2cpt++;
3362: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
3363: }
3364: /*}*/
3365: } /* end m */
3366: } /* end bool */
3367: } /* end i = 1 to imx */
3368:
3369: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3370: pstamp(ficresp);
3371: if (cptcovn>0) {
3372: fprintf(ficresp, "\n#********** Variable ");
3373: fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable ");
3374: fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable ");
3375: for (z1=1; z1<=cptcoveff; z1++){
3376: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3377: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3378: fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3379: }
3380: fprintf(ficresp, "**********\n#");
3381: fprintf(ficresphtm, "**********</h3>\n");
3382: fprintf(ficresphtmfr, "**********</h3>\n");
3383: fprintf(ficlog, "\n#********** Variable ");
3384: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3385: fprintf(ficlog, "**********\n");
3386: }
3387: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
3388: for(i=1; i<=nlstate;i++) {
3389: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3390: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
3391: }
3392: fprintf(ficresp, "\n");
3393: fprintf(ficresphtm, "\n");
3394:
3395: /* Header of frequency table by age */
3396: fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
3397: fprintf(ficresphtmfr,"<th>Age</th> ");
3398: for(jk=-1; jk <=nlstate+ndeath; jk++){
3399: for(m=-1; m <=nlstate+ndeath; m++){
3400: if(jk!=0 && m!=0)
3401: fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
3402: }
3403: }
3404: fprintf(ficresphtmfr, "\n");
3405:
3406: /* For each age */
3407: for(i=iagemin; i <= iagemax+3; i++){
3408: fprintf(ficresphtm,"<tr>");
3409: if(i==iagemax+1){
3410: fprintf(ficlog,"1");
3411: fprintf(ficresphtmfr,"<tr><th>0</th> ");
3412: }else if(i==iagemax+2){
3413: fprintf(ficlog,"0");
3414: fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
3415: }else if(i==iagemax+3){
3416: fprintf(ficlog,"Total");
3417: fprintf(ficresphtmfr,"<tr><th>Total</th> ");
3418: }else{
3419: if(first==1){
3420: first=0;
3421: printf("See log file for details...\n");
3422: }
3423: fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
3424: fprintf(ficlog,"Age %d", i);
3425: }
3426: for(jk=1; jk <=nlstate ; jk++){
3427: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3428: pp[jk] += freq[jk][m][i];
3429: }
3430: for(jk=1; jk <=nlstate ; jk++){
3431: for(m=-1, pos=0; m <=0 ; m++)
3432: pos += freq[jk][m][i];
3433: if(pp[jk]>=1.e-10){
3434: if(first==1){
3435: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3436: }
3437: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3438: }else{
3439: if(first==1)
3440: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3441: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3442: }
3443: }
3444:
3445: for(jk=1; jk <=nlstate ; jk++){
3446: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3447: pp[jk] += freq[jk][m][i];
3448: }
3449: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3450: pos += pp[jk];
3451: posprop += prop[jk][i];
3452: }
3453: for(jk=1; jk <=nlstate ; jk++){
3454: if(pos>=1.e-5){
3455: if(first==1)
3456: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3457: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3458: }else{
3459: if(first==1)
3460: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3461: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3462: }
3463: if( i <= iagemax){
3464: if(pos>=1.e-5){
3465: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3466: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3467: /*probs[i][jk][j1]= pp[jk]/pos;*/
3468: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3469: }
3470: else{
3471: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3472: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
3473: }
3474: }
3475: }
3476:
3477: for(jk=-1; jk <=nlstate+ndeath; jk++){
3478: for(m=-1; m <=nlstate+ndeath; m++){
3479: if(freq[jk][m][i] !=0 ) { /* minimizing output */
3480: if(first==1){
3481: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3482: }
3483: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3484: }
3485: if(jk!=0 && m!=0)
3486: fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
3487: }
3488: }
3489: fprintf(ficresphtmfr,"</tr>\n ");
3490: if(i <= iagemax){
3491: fprintf(ficresp,"\n");
3492: fprintf(ficresphtm,"</tr>\n");
3493: }
3494: if(first==1)
3495: printf("Others in log...\n");
3496: fprintf(ficlog,"\n");
3497: } /* end loop i */
3498: fprintf(ficresphtm,"</table>\n");
3499: fprintf(ficresphtmfr,"</table>\n");
3500: /*}*/
3501: } /* end j1 */
3502: dateintmean=dateintsum/k2cpt;
3503:
3504: fclose(ficresp);
3505: fclose(ficresphtm);
3506: fclose(ficresphtmfr);
3507: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3508: free_vector(pp,1,nlstate);
3509: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3510: /* End of Freq */
3511: }
3512:
3513: /************ Prevalence ********************/
3514: 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)
3515: {
3516: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3517: in each health status at the date of interview (if between dateprev1 and dateprev2).
3518: We still use firstpass and lastpass as another selection.
3519: */
3520:
3521: int i, m, jk, j1, bool, z1,j;
3522: int mi; /* Effective wave */
3523: int iage;
3524: double agebegin, ageend;
3525:
3526: double **prop;
3527: double posprop;
3528: double y2; /* in fractional years */
3529: int iagemin, iagemax;
3530: int first; /** to stop verbosity which is redirected to log file */
3531:
3532: iagemin= (int) agemin;
3533: iagemax= (int) agemax;
3534: /*pp=vector(1,nlstate);*/
3535: prop=matrix(1,nlstate,iagemin,iagemax+3);
3536: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3537: j1=0;
3538:
3539: /*j=cptcoveff;*/
3540: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3541:
3542: first=1;
3543: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3544: for (i=1; i<=nlstate; i++)
3545: for(iage=iagemin; iage <= iagemax+3; iage++)
3546: prop[i][iage]=0.0;
3547:
3548: for (i=1; i<=imx; i++) { /* Each individual */
3549: bool=1;
3550: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3551: for (z1=1; z1<=cptcoveff; z1++)
3552: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3553: bool=0;
3554: }
3555: if (bool==1) {
3556: /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
3557: for(mi=1; mi<wav[i];mi++){
3558: m=mw[mi][i];
3559: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3560: /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
3561: if(m >=firstpass && m <=lastpass){
3562: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3563: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3564: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3565: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3566: 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);
3567: if (s[m][i]>0 && s[m][i]<=nlstate) {
3568: /*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]]);*/
3569: prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
3570: prop[s[m][i]][iagemax+3] += weight[i];
3571: } /* end valid statuses */
3572: } /* end selection of dates */
3573: } /* end selection of waves */
3574: } /* end effective waves */
3575: } /* end bool */
3576: }
3577: for(i=iagemin; i <= iagemax+3; i++){
3578: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3579: posprop += prop[jk][i];
3580: }
3581:
3582: for(jk=1; jk <=nlstate ; jk++){
3583: if( i <= iagemax){
3584: if(posprop>=1.e-5){
3585: probs[i][jk][j1]= prop[jk][i]/posprop;
3586: } else{
3587: if(first==1){
3588: first=0;
3589: 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]);
3590: }
3591: }
3592: }
3593: }/* end jk */
3594: }/* end i */
3595: /*} *//* end i1 */
3596: } /* end j1 */
3597:
3598: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3599: /*free_vector(pp,1,nlstate);*/
3600: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3601: } /* End of prevalence */
3602:
3603: /************* Waves Concatenation ***************/
3604:
3605: 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)
3606: {
3607: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3608: Death is a valid wave (if date is known).
3609: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3610: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3611: and mw[mi+1][i]. dh depends on stepm.
3612: */
3613:
3614: int i, mi, m;
3615: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3616: double sum=0., jmean=0.;*/
3617: int first, firstwo;
3618: int j, k=0,jk, ju, jl;
3619: double sum=0.;
3620: first=0;
3621: firstwo=0;
3622: jmin=100000;
3623: jmax=-1;
3624: jmean=0.;
3625: for(i=1; i<=imx; i++){ /* For simple cases and if state is death */
3626: mi=0;
3627: m=firstpass;
3628: while(s[m][i] <= nlstate){ /* a live state */
3629: if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
3630: mw[++mi][i]=m;
3631: }
3632: if(m >=lastpass){
3633: if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
3634: printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
3635: fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
3636: mw[++mi][i]=m;
3637: }
3638: if(s[m][i]==-2){ /* Vital status is really unknown */
3639: nbwarn++;
3640: if((int)anint[m][i] == 9999){ /* Has the vital status really been verified? */
3641: printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
3642: fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
3643: }
3644: break;
3645: }
3646: break;
3647: }
3648: else
3649: m++;
3650: }/* end while */
3651:
3652: /* After last pass */
3653: if (s[m][i] > nlstate){ /* In a death state */
3654: mi++; /* Death is another wave */
3655: /* if(mi==0) never been interviewed correctly before death */
3656: /* Only death is a correct wave */
3657: mw[mi][i]=m;
3658: }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
3659: /* m++; */
3660: /* mi++; */
3661: /* s[m][i]=nlstate+1; /\* We are setting the status to the last of non live state *\/ */
3662: /* mw[mi][i]=m; */
3663: nberr++;
3664: if(firstwo==0){
3665: printf("Error! Death for individual %ld line=%d occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
3666: fprintf(ficlog,"Error! Death for individual %ld line=%d occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
3667: firstwo=1;
3668: }else if(firstwo==1){
3669: fprintf(ficlog,"Error! Death for individual %ld line=%d occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
3670: }
3671: }
3672: wav[i]=mi;
3673: if(mi==0){
3674: nbwarn++;
3675: if(first==0){
3676: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3677: first=1;
3678: }
3679: if(first==1){
3680: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3681: }
3682: } /* end mi==0 */
3683: } /* End individuals */
3684: /* wav and mw are no more changed */
3685:
3686:
3687: for(i=1; i<=imx; i++){
3688: for(mi=1; mi<wav[i];mi++){
3689: if (stepm <=0)
3690: dh[mi][i]=1;
3691: else{
3692: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3693: if (agedc[i] < 2*AGESUP) {
3694: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3695: if(j==0) j=1; /* Survives at least one month after exam */
3696: else if(j<0){
3697: nberr++;
3698: 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]);
3699: j=1; /* Temporary Dangerous patch */
3700: 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);
3701: 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]);
3702: 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);
3703: }
3704: k=k+1;
3705: if (j >= jmax){
3706: jmax=j;
3707: ijmax=i;
3708: }
3709: if (j <= jmin){
3710: jmin=j;
3711: ijmin=i;
3712: }
3713: sum=sum+j;
3714: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3715: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3716: }
3717: }
3718: else{
3719: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3720: /* 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]); */
3721:
3722: k=k+1;
3723: if (j >= jmax) {
3724: jmax=j;
3725: ijmax=i;
3726: }
3727: else if (j <= jmin){
3728: jmin=j;
3729: ijmin=i;
3730: }
3731: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3732: /*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]);*/
3733: if(j<0){
3734: nberr++;
3735: 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]);
3736: 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]);
3737: }
3738: sum=sum+j;
3739: }
3740: jk= j/stepm;
3741: jl= j -jk*stepm;
3742: ju= j -(jk+1)*stepm;
3743: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3744: if(jl==0){
3745: dh[mi][i]=jk;
3746: bh[mi][i]=0;
3747: }else{ /* We want a negative bias in order to only have interpolation ie
3748: * to avoid the price of an extra matrix product in likelihood */
3749: dh[mi][i]=jk+1;
3750: bh[mi][i]=ju;
3751: }
3752: }else{
3753: if(jl <= -ju){
3754: dh[mi][i]=jk;
3755: bh[mi][i]=jl; /* bias is positive if real duration
3756: * is higher than the multiple of stepm and negative otherwise.
3757: */
3758: }
3759: else{
3760: dh[mi][i]=jk+1;
3761: bh[mi][i]=ju;
3762: }
3763: if(dh[mi][i]==0){
3764: dh[mi][i]=1; /* At least one step */
3765: bh[mi][i]=ju; /* At least one step */
3766: /* 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);*/
3767: }
3768: } /* end if mle */
3769: }
3770: } /* end wave */
3771: }
3772: jmean=sum/k;
3773: 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);
3774: 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);
3775: }
3776:
3777: /*********** Tricode ****************************/
3778: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3779: {
3780: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3781: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3782: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3783: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3784: * nbcode[Tvar[j]][1]=
3785: */
3786:
3787: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3788: int modmaxcovj=0; /* Modality max of covariates j */
3789: int cptcode=0; /* Modality max of covariates j */
3790: int modmincovj=0; /* Modality min of covariates j */
3791:
3792:
3793: cptcoveff=0;
3794:
3795: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3796:
3797: /* Loop on covariates without age and products */
3798: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3799: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3800: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3801: modality of this covariate Vj*/
3802: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3803: * If product of Vn*Vm, still boolean *:
3804: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3805: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3806: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3807: modality of the nth covariate of individual i. */
3808: if (ij > modmaxcovj)
3809: modmaxcovj=ij;
3810: else if (ij < modmincovj)
3811: modmincovj=ij;
3812: if ((ij < -1) && (ij > NCOVMAX)){
3813: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3814: exit(1);
3815: }else
3816: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3817: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3818: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3819: /* getting the maximum value of the modality of the covariate
3820: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3821: female is 1, then modmaxcovj=1.*/
3822: } /* end for loop on individuals i */
3823: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3824: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3825: cptcode=modmaxcovj;
3826: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3827: /*for (i=0; i<=cptcode; i++) {*/
3828: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3829: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3830: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3831: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3832: if( k != -1){
3833: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3834: covariate for which somebody answered excluding
3835: undefined. Usually 2: 0 and 1. */
3836: }
3837: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3838: covariate for which somebody answered including
3839: undefined. Usually 3: -1, 0 and 1. */
3840: }
3841: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3842: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3843: } /* Ndum[-1] number of undefined modalities */
3844:
3845: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3846: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3847: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3848: modmincovj=3; modmaxcovj = 7;
3849: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3850: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3851: defining two dummy variables: variables V1_1 and V1_2.
3852: nbcode[Tvar[j]][ij]=k;
3853: nbcode[Tvar[j]][1]=0;
3854: nbcode[Tvar[j]][2]=1;
3855: nbcode[Tvar[j]][3]=2;
3856: To be continued (not working yet).
3857: */
3858: ij=0; /* ij is similar to i but can jump over null modalities */
3859: 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*/
3860: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3861: break;
3862: }
3863: ij++;
3864: 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.*/
3865: cptcode = ij; /* New max modality for covar j */
3866: } /* end of loop on modality i=-1 to 1 or more */
3867:
3868: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3869: /* /\*recode from 0 *\/ */
3870: /* k is a modality. If we have model=V1+V1*sex */
3871: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3872: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3873: /* } */
3874: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3875: /* if (ij > ncodemax[j]) { */
3876: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3877: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3878: /* break; */
3879: /* } */
3880: /* } /\* end of loop on modality k *\/ */
3881: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3882:
3883: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3884:
3885: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3886: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3887: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3888: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3889: }
3890:
3891: ij=0;
3892: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3893: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3894: if((Ndum[i]!=0) && (i<=ncovcol)){
3895: ij++;
3896: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3897: Tvaraff[ij]=i; /*For printing (unclear) */
3898: }else{
3899: /* Tvaraff[ij]=0; */
3900: }
3901: }
3902: /* ij--; */
3903: cptcoveff=ij; /*Number of total covariates*/
3904:
3905: }
3906:
3907:
3908: /*********** Health Expectancies ****************/
3909:
3910: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3911:
3912: {
3913: /* Health expectancies, no variances */
3914: int i, j, nhstepm, hstepm, h, nstepm;
3915: int nhstepma, nstepma; /* Decreasing with age */
3916: double age, agelim, hf;
3917: double ***p3mat;
3918: double eip;
3919:
3920: pstamp(ficreseij);
3921: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3922: fprintf(ficreseij,"# Age");
3923: for(i=1; i<=nlstate;i++){
3924: for(j=1; j<=nlstate;j++){
3925: fprintf(ficreseij," e%1d%1d ",i,j);
3926: }
3927: fprintf(ficreseij," e%1d. ",i);
3928: }
3929: fprintf(ficreseij,"\n");
3930:
3931:
3932: if(estepm < stepm){
3933: printf ("Problem %d lower than %d\n",estepm, stepm);
3934: }
3935: else hstepm=estepm;
3936: /* We compute the life expectancy from trapezoids spaced every estepm months
3937: * This is mainly to measure the difference between two models: for example
3938: * if stepm=24 months pijx are given only every 2 years and by summing them
3939: * we are calculating an estimate of the Life Expectancy assuming a linear
3940: * progression in between and thus overestimating or underestimating according
3941: * to the curvature of the survival function. If, for the same date, we
3942: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3943: * to compare the new estimate of Life expectancy with the same linear
3944: * hypothesis. A more precise result, taking into account a more precise
3945: * curvature will be obtained if estepm is as small as stepm. */
3946:
3947: /* For example we decided to compute the life expectancy with the smallest unit */
3948: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3949: nhstepm is the number of hstepm from age to agelim
3950: nstepm is the number of stepm from age to agelin.
3951: Look at hpijx to understand the reason of that which relies in memory size
3952: and note for a fixed period like estepm months */
3953: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3954: survival function given by stepm (the optimization length). Unfortunately it
3955: means that if the survival funtion is printed only each two years of age and if
3956: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3957: results. So we changed our mind and took the option of the best precision.
3958: */
3959: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3960:
3961: agelim=AGESUP;
3962: /* If stepm=6 months */
3963: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3964: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3965:
3966: /* nhstepm age range expressed in number of stepm */
3967: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3968: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3969: /* if (stepm >= YEARM) hstepm=1;*/
3970: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3971: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3972:
3973: for (age=bage; age<=fage; age ++){
3974: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3975: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3976: /* if (stepm >= YEARM) hstepm=1;*/
3977: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3978:
3979: /* If stepm=6 months */
3980: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3981: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3982:
3983: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3984:
3985: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3986:
3987: printf("%d|",(int)age);fflush(stdout);
3988: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3989:
3990: /* Computing expectancies */
3991: for(i=1; i<=nlstate;i++)
3992: for(j=1; j<=nlstate;j++)
3993: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3994: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3995:
3996: /* 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]);*/
3997:
3998: }
3999:
4000: fprintf(ficreseij,"%3.0f",age );
4001: for(i=1; i<=nlstate;i++){
4002: eip=0;
4003: for(j=1; j<=nlstate;j++){
4004: eip +=eij[i][j][(int)age];
4005: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
4006: }
4007: fprintf(ficreseij,"%9.4f", eip );
4008: }
4009: fprintf(ficreseij,"\n");
4010:
4011: }
4012: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4013: printf("\n");
4014: fprintf(ficlog,"\n");
4015:
4016: }
4017:
4018: 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[] )
4019:
4020: {
4021: /* Covariances of health expectancies eij and of total life expectancies according
4022: to initial status i, ei. .
4023: */
4024: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
4025: int nhstepma, nstepma; /* Decreasing with age */
4026: double age, agelim, hf;
4027: double ***p3matp, ***p3matm, ***varhe;
4028: double **dnewm,**doldm;
4029: double *xp, *xm;
4030: double **gp, **gm;
4031: double ***gradg, ***trgradg;
4032: int theta;
4033:
4034: double eip, vip;
4035:
4036: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
4037: xp=vector(1,npar);
4038: xm=vector(1,npar);
4039: dnewm=matrix(1,nlstate*nlstate,1,npar);
4040: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
4041:
4042: pstamp(ficresstdeij);
4043: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
4044: fprintf(ficresstdeij,"# Age");
4045: for(i=1; i<=nlstate;i++){
4046: for(j=1; j<=nlstate;j++)
4047: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
4048: fprintf(ficresstdeij," e%1d. ",i);
4049: }
4050: fprintf(ficresstdeij,"\n");
4051:
4052: pstamp(ficrescveij);
4053: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
4054: fprintf(ficrescveij,"# Age");
4055: for(i=1; i<=nlstate;i++)
4056: for(j=1; j<=nlstate;j++){
4057: cptj= (j-1)*nlstate+i;
4058: for(i2=1; i2<=nlstate;i2++)
4059: for(j2=1; j2<=nlstate;j2++){
4060: cptj2= (j2-1)*nlstate+i2;
4061: if(cptj2 <= cptj)
4062: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
4063: }
4064: }
4065: fprintf(ficrescveij,"\n");
4066:
4067: if(estepm < stepm){
4068: printf ("Problem %d lower than %d\n",estepm, stepm);
4069: }
4070: else hstepm=estepm;
4071: /* We compute the life expectancy from trapezoids spaced every estepm months
4072: * This is mainly to measure the difference between two models: for example
4073: * if stepm=24 months pijx are given only every 2 years and by summing them
4074: * we are calculating an estimate of the Life Expectancy assuming a linear
4075: * progression in between and thus overestimating or underestimating according
4076: * to the curvature of the survival function. If, for the same date, we
4077: * estimate the model with stepm=1 month, we can keep estepm to 24 months
4078: * to compare the new estimate of Life expectancy with the same linear
4079: * hypothesis. A more precise result, taking into account a more precise
4080: * curvature will be obtained if estepm is as small as stepm. */
4081:
4082: /* For example we decided to compute the life expectancy with the smallest unit */
4083: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4084: nhstepm is the number of hstepm from age to agelim
4085: nstepm is the number of stepm from age to agelin.
4086: Look at hpijx to understand the reason of that which relies in memory size
4087: and note for a fixed period like estepm months */
4088: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4089: survival function given by stepm (the optimization length). Unfortunately it
4090: means that if the survival funtion is printed only each two years of age and if
4091: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4092: results. So we changed our mind and took the option of the best precision.
4093: */
4094: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4095:
4096: /* If stepm=6 months */
4097: /* nhstepm age range expressed in number of stepm */
4098: agelim=AGESUP;
4099: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
4100: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4101: /* if (stepm >= YEARM) hstepm=1;*/
4102: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4103:
4104: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4105: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4106: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
4107: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
4108: gp=matrix(0,nhstepm,1,nlstate*nlstate);
4109: gm=matrix(0,nhstepm,1,nlstate*nlstate);
4110:
4111: for (age=bage; age<=fage; age ++){
4112: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4113: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4114: /* if (stepm >= YEARM) hstepm=1;*/
4115: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
4116:
4117: /* If stepm=6 months */
4118: /* Computed by stepm unit matrices, product of hstepma matrices, stored
4119: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
4120:
4121: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4122:
4123: /* Computing Variances of health expectancies */
4124: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
4125: decrease memory allocation */
4126: for(theta=1; theta <=npar; theta++){
4127: for(i=1; i<=npar; i++){
4128: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4129: xm[i] = x[i] - (i==theta ?delti[theta]:0);
4130: }
4131: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
4132: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
4133:
4134: for(j=1; j<= nlstate; j++){
4135: for(i=1; i<=nlstate; i++){
4136: for(h=0; h<=nhstepm-1; h++){
4137: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
4138: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
4139: }
4140: }
4141: }
4142:
4143: for(ij=1; ij<= nlstate*nlstate; ij++)
4144: for(h=0; h<=nhstepm-1; h++){
4145: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
4146: }
4147: }/* End theta */
4148:
4149:
4150: for(h=0; h<=nhstepm-1; h++)
4151: for(j=1; j<=nlstate*nlstate;j++)
4152: for(theta=1; theta <=npar; theta++)
4153: trgradg[h][j][theta]=gradg[h][theta][j];
4154:
4155:
4156: for(ij=1;ij<=nlstate*nlstate;ij++)
4157: for(ji=1;ji<=nlstate*nlstate;ji++)
4158: varhe[ij][ji][(int)age] =0.;
4159:
4160: printf("%d|",(int)age);fflush(stdout);
4161: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4162: for(h=0;h<=nhstepm-1;h++){
4163: for(k=0;k<=nhstepm-1;k++){
4164: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
4165: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
4166: for(ij=1;ij<=nlstate*nlstate;ij++)
4167: for(ji=1;ji<=nlstate*nlstate;ji++)
4168: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
4169: }
4170: }
4171:
4172: /* Computing expectancies */
4173: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4174: for(i=1; i<=nlstate;i++)
4175: for(j=1; j<=nlstate;j++)
4176: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4177: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
4178:
4179: /* 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]);*/
4180:
4181: }
4182:
4183: fprintf(ficresstdeij,"%3.0f",age );
4184: for(i=1; i<=nlstate;i++){
4185: eip=0.;
4186: vip=0.;
4187: for(j=1; j<=nlstate;j++){
4188: eip += eij[i][j][(int)age];
4189: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4190: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4191: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4192: }
4193: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4194: }
4195: fprintf(ficresstdeij,"\n");
4196:
4197: fprintf(ficrescveij,"%3.0f",age );
4198: for(i=1; i<=nlstate;i++)
4199: for(j=1; j<=nlstate;j++){
4200: cptj= (j-1)*nlstate+i;
4201: for(i2=1; i2<=nlstate;i2++)
4202: for(j2=1; j2<=nlstate;j2++){
4203: cptj2= (j2-1)*nlstate+i2;
4204: if(cptj2 <= cptj)
4205: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4206: }
4207: }
4208: fprintf(ficrescveij,"\n");
4209:
4210: }
4211: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4212: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4213: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4214: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4215: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4216: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4217: printf("\n");
4218: fprintf(ficlog,"\n");
4219:
4220: free_vector(xm,1,npar);
4221: free_vector(xp,1,npar);
4222: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4223: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4224: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4225: }
4226:
4227: /************ Variance ******************/
4228: 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[])
4229: {
4230: /* Variance of health expectancies */
4231: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4232: /* double **newm;*/
4233: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4234:
4235: int movingaverage();
4236: double **dnewm,**doldm;
4237: double **dnewmp,**doldmp;
4238: int i, j, nhstepm, hstepm, h, nstepm ;
4239: int k;
4240: double *xp;
4241: double **gp, **gm; /* for var eij */
4242: double ***gradg, ***trgradg; /*for var eij */
4243: double **gradgp, **trgradgp; /* for var p point j */
4244: double *gpp, *gmp; /* for var p point j */
4245: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4246: double ***p3mat;
4247: double age,agelim, hf;
4248: double ***mobaverage;
4249: int theta;
4250: char digit[4];
4251: char digitp[25];
4252:
4253: char fileresprobmorprev[FILENAMELENGTH];
4254:
4255: if(popbased==1){
4256: if(mobilav!=0)
4257: strcpy(digitp,"-POPULBASED-MOBILAV_");
4258: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4259: }
4260: else
4261: strcpy(digitp,"-STABLBASED_");
4262:
4263: if (mobilav!=0) {
4264: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4265: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4266: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4267: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4268: }
4269: }
4270:
4271: strcpy(fileresprobmorprev,"PRMORPREV-");
4272: sprintf(digit,"%-d",ij);
4273: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4274: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4275: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4276: strcat(fileresprobmorprev,fileresu);
4277: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4278: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4279: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4280: }
4281: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4282: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4283: pstamp(ficresprobmorprev);
4284: 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);
4285: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4286: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4287: fprintf(ficresprobmorprev," p.%-d SE",j);
4288: for(i=1; i<=nlstate;i++)
4289: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4290: }
4291: fprintf(ficresprobmorprev,"\n");
4292:
4293: fprintf(ficgp,"\n# Routine varevsij");
4294: fprintf(ficgp,"\nunset title \n");
4295: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4296: 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");
4297: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4298: /* } */
4299: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4300: pstamp(ficresvij);
4301: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4302: if(popbased==1)
4303: 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);
4304: else
4305: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4306: fprintf(ficresvij,"# Age");
4307: for(i=1; i<=nlstate;i++)
4308: for(j=1; j<=nlstate;j++)
4309: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4310: fprintf(ficresvij,"\n");
4311:
4312: xp=vector(1,npar);
4313: dnewm=matrix(1,nlstate,1,npar);
4314: doldm=matrix(1,nlstate,1,nlstate);
4315: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4316: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4317:
4318: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4319: gpp=vector(nlstate+1,nlstate+ndeath);
4320: gmp=vector(nlstate+1,nlstate+ndeath);
4321: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4322:
4323: if(estepm < stepm){
4324: printf ("Problem %d lower than %d\n",estepm, stepm);
4325: }
4326: else hstepm=estepm;
4327: /* For example we decided to compute the life expectancy with the smallest unit */
4328: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4329: nhstepm is the number of hstepm from age to agelim
4330: nstepm is the number of stepm from age to agelim.
4331: Look at function hpijx to understand why because of memory size limitations,
4332: we decided (b) to get a life expectancy respecting the most precise curvature of the
4333: survival function given by stepm (the optimization length). Unfortunately it
4334: means that if the survival funtion is printed every two years of age and if
4335: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4336: results. So we changed our mind and took the option of the best precision.
4337: */
4338: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4339: agelim = AGESUP;
4340: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4341: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4342: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4343: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4344: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4345: gp=matrix(0,nhstepm,1,nlstate);
4346: gm=matrix(0,nhstepm,1,nlstate);
4347:
4348:
4349: for(theta=1; theta <=npar; theta++){
4350: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4351: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4352: }
4353:
4354: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4355:
4356: if (popbased==1) {
4357: if(mobilav ==0){
4358: for(i=1; i<=nlstate;i++)
4359: prlim[i][i]=probs[(int)age][i][ij];
4360: }else{ /* mobilav */
4361: for(i=1; i<=nlstate;i++)
4362: prlim[i][i]=mobaverage[(int)age][i][ij];
4363: }
4364: }
4365:
4366: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
4367: for(j=1; j<= nlstate; j++){
4368: for(h=0; h<=nhstepm; h++){
4369: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4370: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4371: }
4372: }
4373: /* Next for computing probability of death (h=1 means
4374: computed over hstepm matrices product = hstepm*stepm months)
4375: as a weighted average of prlim.
4376: */
4377: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4378: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4379: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4380: }
4381: /* end probability of death */
4382:
4383: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4384: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4385:
4386: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
4387:
4388: if (popbased==1) {
4389: if(mobilav ==0){
4390: for(i=1; i<=nlstate;i++)
4391: prlim[i][i]=probs[(int)age][i][ij];
4392: }else{ /* mobilav */
4393: for(i=1; i<=nlstate;i++)
4394: prlim[i][i]=mobaverage[(int)age][i][ij];
4395: }
4396: }
4397:
4398: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4399:
4400: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4401: for(h=0; h<=nhstepm; h++){
4402: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4403: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4404: }
4405: }
4406: /* This for computing probability of death (h=1 means
4407: computed over hstepm matrices product = hstepm*stepm months)
4408: as a weighted average of prlim.
4409: */
4410: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4411: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4412: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4413: }
4414: /* end probability of death */
4415:
4416: for(j=1; j<= nlstate; j++) /* vareij */
4417: for(h=0; h<=nhstepm; h++){
4418: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4419: }
4420:
4421: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4422: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4423: }
4424:
4425: } /* End theta */
4426:
4427: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4428:
4429: for(h=0; h<=nhstepm; h++) /* veij */
4430: for(j=1; j<=nlstate;j++)
4431: for(theta=1; theta <=npar; theta++)
4432: trgradg[h][j][theta]=gradg[h][theta][j];
4433:
4434: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4435: for(theta=1; theta <=npar; theta++)
4436: trgradgp[j][theta]=gradgp[theta][j];
4437:
4438:
4439: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4440: for(i=1;i<=nlstate;i++)
4441: for(j=1;j<=nlstate;j++)
4442: vareij[i][j][(int)age] =0.;
4443:
4444: for(h=0;h<=nhstepm;h++){
4445: for(k=0;k<=nhstepm;k++){
4446: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4447: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4448: for(i=1;i<=nlstate;i++)
4449: for(j=1;j<=nlstate;j++)
4450: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4451: }
4452: }
4453:
4454: /* pptj */
4455: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4456: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4457: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4458: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4459: varppt[j][i]=doldmp[j][i];
4460: /* end ppptj */
4461: /* x centered again */
4462:
4463: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
4464:
4465: if (popbased==1) {
4466: if(mobilav ==0){
4467: for(i=1; i<=nlstate;i++)
4468: prlim[i][i]=probs[(int)age][i][ij];
4469: }else{ /* mobilav */
4470: for(i=1; i<=nlstate;i++)
4471: prlim[i][i]=mobaverage[(int)age][i][ij];
4472: }
4473: }
4474:
4475: /* This for computing probability of death (h=1 means
4476: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4477: as a weighted average of prlim.
4478: */
4479: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4480: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4481: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4482: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4483: }
4484: /* end probability of death */
4485:
4486: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4487: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4488: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4489: for(i=1; i<=nlstate;i++){
4490: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4491: }
4492: }
4493: fprintf(ficresprobmorprev,"\n");
4494:
4495: fprintf(ficresvij,"%.0f ",age );
4496: for(i=1; i<=nlstate;i++)
4497: for(j=1; j<=nlstate;j++){
4498: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4499: }
4500: fprintf(ficresvij,"\n");
4501: free_matrix(gp,0,nhstepm,1,nlstate);
4502: free_matrix(gm,0,nhstepm,1,nlstate);
4503: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4504: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4505: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4506: } /* End age */
4507: free_vector(gpp,nlstate+1,nlstate+ndeath);
4508: free_vector(gmp,nlstate+1,nlstate+ndeath);
4509: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4510: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4511: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4512: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4513: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4514: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4515: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4516: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4517: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4518: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4519: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4520: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4521: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4522: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4523: 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);
4524: /* 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);
4525: */
4526: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4527: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4528:
4529: free_vector(xp,1,npar);
4530: free_matrix(doldm,1,nlstate,1,nlstate);
4531: free_matrix(dnewm,1,nlstate,1,npar);
4532: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4533: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4534: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4535: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4536: fclose(ficresprobmorprev);
4537: fflush(ficgp);
4538: fflush(fichtm);
4539: } /* end varevsij */
4540:
4541: /************ Variance of prevlim ******************/
4542: 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[])
4543: {
4544: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4545: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4546:
4547: double **dnewm,**doldm;
4548: int i, j, nhstepm, hstepm;
4549: double *xp;
4550: double *gp, *gm;
4551: double **gradg, **trgradg;
4552: double **mgm, **mgp;
4553: double age,agelim;
4554: int theta;
4555:
4556: pstamp(ficresvpl);
4557: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4558: fprintf(ficresvpl,"# Age");
4559: for(i=1; i<=nlstate;i++)
4560: fprintf(ficresvpl," %1d-%1d",i,i);
4561: fprintf(ficresvpl,"\n");
4562:
4563: xp=vector(1,npar);
4564: dnewm=matrix(1,nlstate,1,npar);
4565: doldm=matrix(1,nlstate,1,nlstate);
4566:
4567: hstepm=1*YEARM; /* Every year of age */
4568: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4569: agelim = AGESUP;
4570: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4571: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4572: if (stepm >= YEARM) hstepm=1;
4573: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4574: gradg=matrix(1,npar,1,nlstate);
4575: mgp=matrix(1,npar,1,nlstate);
4576: mgm=matrix(1,npar,1,nlstate);
4577: gp=vector(1,nlstate);
4578: gm=vector(1,nlstate);
4579:
4580: for(theta=1; theta <=npar; theta++){
4581: for(i=1; i<=npar; i++){ /* Computes gradient */
4582: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4583: }
4584: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4585: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4586: else
4587: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4588: for(i=1;i<=nlstate;i++){
4589: gp[i] = prlim[i][i];
4590: mgp[theta][i] = prlim[i][i];
4591: }
4592: for(i=1; i<=npar; i++) /* Computes gradient */
4593: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4594: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4595: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4596: else
4597: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4598: for(i=1;i<=nlstate;i++){
4599: gm[i] = prlim[i][i];
4600: mgm[theta][i] = prlim[i][i];
4601: }
4602: for(i=1;i<=nlstate;i++)
4603: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4604: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
4605: } /* End theta */
4606:
4607: trgradg =matrix(1,nlstate,1,npar);
4608:
4609: for(j=1; j<=nlstate;j++)
4610: for(theta=1; theta <=npar; theta++)
4611: trgradg[j][theta]=gradg[theta][j];
4612: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4613: /* printf("\nmgm mgp %d ",(int)age); */
4614: /* for(j=1; j<=nlstate;j++){ */
4615: /* printf(" %d ",j); */
4616: /* for(theta=1; theta <=npar; theta++) */
4617: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4618: /* printf("\n "); */
4619: /* } */
4620: /* } */
4621: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4622: /* printf("\n gradg %d ",(int)age); */
4623: /* for(j=1; j<=nlstate;j++){ */
4624: /* printf("%d ",j); */
4625: /* for(theta=1; theta <=npar; theta++) */
4626: /* printf("%d %lf ",theta,gradg[theta][j]); */
4627: /* printf("\n "); */
4628: /* } */
4629: /* } */
4630:
4631: for(i=1;i<=nlstate;i++)
4632: varpl[i][(int)age] =0.;
4633: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
4634: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4635: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4636: }else{
4637: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4638: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4639: }
4640: for(i=1;i<=nlstate;i++)
4641: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4642:
4643: fprintf(ficresvpl,"%.0f ",age );
4644: for(i=1; i<=nlstate;i++)
4645: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4646: fprintf(ficresvpl,"\n");
4647: free_vector(gp,1,nlstate);
4648: free_vector(gm,1,nlstate);
4649: free_matrix(mgm,1,npar,1,nlstate);
4650: free_matrix(mgp,1,npar,1,nlstate);
4651: free_matrix(gradg,1,npar,1,nlstate);
4652: free_matrix(trgradg,1,nlstate,1,npar);
4653: } /* End age */
4654:
4655: free_vector(xp,1,npar);
4656: free_matrix(doldm,1,nlstate,1,npar);
4657: free_matrix(dnewm,1,nlstate,1,nlstate);
4658:
4659: }
4660:
4661: /************ Variance of one-step probabilities ******************/
4662: 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[])
4663: {
4664: int i, j=0, k1, l1, tj;
4665: int k2, l2, j1, z1;
4666: int k=0, l;
4667: int first=1, first1, first2;
4668: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4669: double **dnewm,**doldm;
4670: double *xp;
4671: double *gp, *gm;
4672: double **gradg, **trgradg;
4673: double **mu;
4674: double age, cov[NCOVMAX+1];
4675: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4676: int theta;
4677: char fileresprob[FILENAMELENGTH];
4678: char fileresprobcov[FILENAMELENGTH];
4679: char fileresprobcor[FILENAMELENGTH];
4680: double ***varpij;
4681:
4682: strcpy(fileresprob,"PROB_");
4683: strcat(fileresprob,fileres);
4684: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4685: printf("Problem with resultfile: %s\n", fileresprob);
4686: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4687: }
4688: strcpy(fileresprobcov,"PROBCOV_");
4689: strcat(fileresprobcov,fileresu);
4690: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4691: printf("Problem with resultfile: %s\n", fileresprobcov);
4692: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4693: }
4694: strcpy(fileresprobcor,"PROBCOR_");
4695: strcat(fileresprobcor,fileresu);
4696: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4697: printf("Problem with resultfile: %s\n", fileresprobcor);
4698: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4699: }
4700: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4701: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4702: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4703: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4704: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4705: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4706: pstamp(ficresprob);
4707: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4708: fprintf(ficresprob,"# Age");
4709: pstamp(ficresprobcov);
4710: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4711: fprintf(ficresprobcov,"# Age");
4712: pstamp(ficresprobcor);
4713: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4714: fprintf(ficresprobcor,"# Age");
4715:
4716:
4717: for(i=1; i<=nlstate;i++)
4718: for(j=1; j<=(nlstate+ndeath);j++){
4719: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4720: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4721: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4722: }
4723: /* fprintf(ficresprob,"\n");
4724: fprintf(ficresprobcov,"\n");
4725: fprintf(ficresprobcor,"\n");
4726: */
4727: xp=vector(1,npar);
4728: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4729: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4730: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4731: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4732: first=1;
4733: fprintf(ficgp,"\n# Routine varprob");
4734: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4735: fprintf(fichtm,"\n");
4736:
4737: 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);
4738: 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);
4739: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4740: and drawn. It helps understanding how is the covariance between two incidences.\
4741: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4742: 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. \
4743: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4744: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4745: standard deviations wide on each axis. <br>\
4746: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4747: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4748: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4749:
4750: cov[1]=1;
4751: /* tj=cptcoveff; */
4752: tj = (int) pow(2,cptcoveff);
4753: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4754: j1=0;
4755: for(j1=1; j1<=tj;j1++){
4756: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4757: /*j1++;*/
4758: if (cptcovn>0) {
4759: fprintf(ficresprob, "\n#********** Variable ");
4760: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4761: fprintf(ficresprob, "**********\n#\n");
4762: fprintf(ficresprobcov, "\n#********** Variable ");
4763: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4764: fprintf(ficresprobcov, "**********\n#\n");
4765:
4766: fprintf(ficgp, "\n#********** Variable ");
4767: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4768: fprintf(ficgp, "**********\n#\n");
4769:
4770:
4771: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4772: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4773: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4774:
4775: fprintf(ficresprobcor, "\n#********** Variable ");
4776: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4777: fprintf(ficresprobcor, "**********\n#");
4778: }
4779:
4780: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4781: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4782: gp=vector(1,(nlstate)*(nlstate+ndeath));
4783: gm=vector(1,(nlstate)*(nlstate+ndeath));
4784: for (age=bage; age<=fage; age ++){
4785: cov[2]=age;
4786: if(nagesqr==1)
4787: cov[3]= age*age;
4788: for (k=1; k<=cptcovn;k++) {
4789: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4790: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4791: * 1 1 1 1 1
4792: * 2 2 1 1 1
4793: * 3 1 2 1 1
4794: */
4795: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4796: }
4797: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4798: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4799: for (k=1; k<=cptcovprod;k++)
4800: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4801:
4802:
4803: for(theta=1; theta <=npar; theta++){
4804: for(i=1; i<=npar; i++)
4805: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4806:
4807: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4808:
4809: k=0;
4810: for(i=1; i<= (nlstate); i++){
4811: for(j=1; j<=(nlstate+ndeath);j++){
4812: k=k+1;
4813: gp[k]=pmmij[i][j];
4814: }
4815: }
4816:
4817: for(i=1; i<=npar; i++)
4818: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4819:
4820: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4821: k=0;
4822: for(i=1; i<=(nlstate); i++){
4823: for(j=1; j<=(nlstate+ndeath);j++){
4824: k=k+1;
4825: gm[k]=pmmij[i][j];
4826: }
4827: }
4828:
4829: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4830: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4831: }
4832:
4833: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4834: for(theta=1; theta <=npar; theta++)
4835: trgradg[j][theta]=gradg[theta][j];
4836:
4837: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4838: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4839:
4840: pmij(pmmij,cov,ncovmodel,x,nlstate);
4841:
4842: k=0;
4843: for(i=1; i<=(nlstate); i++){
4844: for(j=1; j<=(nlstate+ndeath);j++){
4845: k=k+1;
4846: mu[k][(int) age]=pmmij[i][j];
4847: }
4848: }
4849: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4850: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4851: varpij[i][j][(int)age] = doldm[i][j];
4852:
4853: /*printf("\n%d ",(int)age);
4854: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4855: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4856: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4857: }*/
4858:
4859: fprintf(ficresprob,"\n%d ",(int)age);
4860: fprintf(ficresprobcov,"\n%d ",(int)age);
4861: fprintf(ficresprobcor,"\n%d ",(int)age);
4862:
4863: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4864: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4865: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4866: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4867: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4868: }
4869: i=0;
4870: for (k=1; k<=(nlstate);k++){
4871: for (l=1; l<=(nlstate+ndeath);l++){
4872: i++;
4873: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4874: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4875: for (j=1; j<=i;j++){
4876: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4877: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4878: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4879: }
4880: }
4881: }/* end of loop for state */
4882: } /* end of loop for age */
4883: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4884: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4885: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4886: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4887:
4888: /* Confidence intervalle of pij */
4889: /*
4890: fprintf(ficgp,"\nunset parametric;unset label");
4891: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4892: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4893: 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);
4894: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4895: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4896: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4897: */
4898:
4899: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4900: first1=1;first2=2;
4901: for (k2=1; k2<=(nlstate);k2++){
4902: for (l2=1; l2<=(nlstate+ndeath);l2++){
4903: if(l2==k2) continue;
4904: j=(k2-1)*(nlstate+ndeath)+l2;
4905: for (k1=1; k1<=(nlstate);k1++){
4906: for (l1=1; l1<=(nlstate+ndeath);l1++){
4907: if(l1==k1) continue;
4908: i=(k1-1)*(nlstate+ndeath)+l1;
4909: if(i<=j) continue;
4910: for (age=bage; age<=fage; age ++){
4911: if ((int)age %5==0){
4912: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4913: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4914: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4915: mu1=mu[i][(int) age]/stepm*YEARM ;
4916: mu2=mu[j][(int) age]/stepm*YEARM;
4917: c12=cv12/sqrt(v1*v2);
4918: /* Computing eigen value of matrix of covariance */
4919: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4920: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4921: if ((lc2 <0) || (lc1 <0) ){
4922: if(first2==1){
4923: first1=0;
4924: 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);
4925: }
4926: 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);
4927: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4928: /* lc2=fabs(lc2); */
4929: }
4930:
4931: /* Eigen vectors */
4932: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4933: /*v21=sqrt(1.-v11*v11); *//* error */
4934: v21=(lc1-v1)/cv12*v11;
4935: v12=-v21;
4936: v22=v11;
4937: tnalp=v21/v11;
4938: if(first1==1){
4939: first1=0;
4940: 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);
4941: }
4942: 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);
4943: /*printf(fignu*/
4944: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4945: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4946: if(first==1){
4947: first=0;
4948: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4949: fprintf(ficgp,"\nset parametric;unset label");
4950: 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);
4951: fprintf(ficgp,"\nset ter svg size 640, 480");
4952: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4953: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4954: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4955: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4956: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4957: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4958: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4959: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4960: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4961: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4962: 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",\
4963: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4964: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4965: }else{
4966: first=0;
4967: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4968: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4969: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4970: 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",\
4971: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4972: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4973: }/* if first */
4974: } /* age mod 5 */
4975: } /* end loop age */
4976: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4977: first=1;
4978: } /*l12 */
4979: } /* k12 */
4980: } /*l1 */
4981: }/* k1 */
4982: /* } */ /* loop covariates */
4983: }
4984: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4985: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4986: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4987: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4988: free_vector(xp,1,npar);
4989: fclose(ficresprob);
4990: fclose(ficresprobcov);
4991: fclose(ficresprobcor);
4992: fflush(ficgp);
4993: fflush(fichtmcov);
4994: }
4995:
4996:
4997: /******************* Printing html file ***********/
4998: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4999: int lastpass, int stepm, int weightopt, char model[],\
5000: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
5001: int popforecast, int prevfcast, int estepm , \
5002: double jprev1, double mprev1,double anprev1, double dateprev1, \
5003: double jprev2, double mprev2,double anprev2, double dateprev2){
5004: int jj1, k1, i1, cpt;
5005:
5006: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
5007: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
5008: </ul>");
5009: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
5010: fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
5011: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
5012: fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
5013: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
5014: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
5015: fprintf(fichtm,"\
5016: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
5017: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
5018: fprintf(fichtm,"\
5019: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
5020: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
5021: fprintf(fichtm,"\
5022: - (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): \
5023: <a href=\"%s\">%s</a> <br>\n",
5024: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
5025: if(prevfcast==1){
5026: fprintf(fichtm,"\
5027: - Prevalence projections by age and states: \
5028: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
5029: }
5030:
5031: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
5032:
5033: m=pow(2,cptcoveff);
5034: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5035:
5036: jj1=0;
5037: for(k1=1; k1<=m;k1++){
5038: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5039: jj1++;
5040: if (cptcovn > 0) {
5041: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5042: for (cpt=1; cpt<=cptcoveff;cpt++){
5043: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5044: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
5045: }
5046: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5047: }
5048: /* aij, bij */
5049: 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> \
5050: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5051: /* Pij */
5052: 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> \
5053: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5054: /* Quasi-incidences */
5055: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
5056: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
5057: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
5058: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
5059: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5060: /* Survival functions (period) in state j */
5061: for(cpt=1; cpt<=nlstate;cpt++){
5062: 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> \
5063: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
5064: }
5065: /* State specific survival functions (period) */
5066: for(cpt=1; cpt<=nlstate;cpt++){
5067: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
5068: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
5069: <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);
5070: }
5071: /* Period (stable) prevalence in each health state */
5072: for(cpt=1; cpt<=nlstate;cpt++){
5073: 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> \
5074: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
5075: }
5076: if(prevfcast==1){
5077: /* Projection of prevalence up to period (stable) prevalence in each health state */
5078: for(cpt=1; cpt<=nlstate;cpt++){
5079: fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) 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> \
5080: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
5081: }
5082: }
5083:
5084: for(cpt=1; cpt<=nlstate;cpt++) {
5085: 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> \
5086: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
5087: }
5088: /* } /\* end i1 *\/ */
5089: }/* End k1 */
5090: fprintf(fichtm,"</ul>");
5091:
5092: fprintf(fichtm,"\
5093: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
5094: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
5095: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
5096: But because parameters are usually highly correlated (a higher incidence of disability \
5097: and a higher incidence of recovery can give very close observed transition) it might \
5098: be very useful to look not only at linear confidence intervals estimated from the \
5099: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
5100: (parameters) of the logistic regression, it might be more meaningful to visualize the \
5101: covariance matrix of the one-step probabilities. \
5102: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
5103:
5104: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5105: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
5106: fprintf(fichtm,"\
5107: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5108: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
5109:
5110: fprintf(fichtm,"\
5111: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5112: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
5113: fprintf(fichtm,"\
5114: - 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): \
5115: <a href=\"%s\">%s</a> <br>\n</li>",
5116: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
5117: fprintf(fichtm,"\
5118: - (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): \
5119: <a href=\"%s\">%s</a> <br>\n</li>",
5120: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
5121: fprintf(fichtm,"\
5122: - 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",
5123: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
5124: fprintf(fichtm,"\
5125: - 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",
5126: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
5127: fprintf(fichtm,"\
5128: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
5129: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
5130:
5131: /* if(popforecast==1) fprintf(fichtm,"\n */
5132: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
5133: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
5134: /* <br>",fileres,fileres,fileres,fileres); */
5135: /* else */
5136: /* 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); */
5137: fflush(fichtm);
5138: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
5139:
5140: m=pow(2,cptcoveff);
5141: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5142:
5143: jj1=0;
5144: for(k1=1; k1<=m;k1++){
5145: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5146: jj1++;
5147: if (cptcovn > 0) {
5148: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5149: for (cpt=1; cpt<=cptcoveff;cpt++)
5150: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5151: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5152: }
5153: for(cpt=1; cpt<=nlstate;cpt++) {
5154: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
5155: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
5156: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
5157: }
5158: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
5159: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
5160: true period expectancies (those weighted with period prevalences are also\
5161: drawn in addition to the population based expectancies computed using\
5162: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
5163: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
5164: /* } /\* end i1 *\/ */
5165: }/* End k1 */
5166: fprintf(fichtm,"</ul>");
5167: fflush(fichtm);
5168: }
5169:
5170: /******************* Gnuplot file **************/
5171: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
5172:
5173: char dirfileres[132],optfileres[132];
5174: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
5175: int lv=0, vlv=0, kl=0;
5176: int ng=0;
5177: int vpopbased;
5178: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
5179: /* printf("Problem with file %s",optionfilegnuplot); */
5180: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
5181: /* } */
5182:
5183: /*#ifdef windows */
5184: fprintf(ficgp,"cd \"%s\" \n",pathc);
5185: /*#endif */
5186: m=pow(2,cptcoveff);
5187:
5188: /* Contribution to likelihood */
5189: /* Plot the probability implied in the likelihood */
5190: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5191: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5192: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
5193: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
5194: /* nice for mle=4 plot by number of matrix products.
5195: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5196: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5197: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
5198: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
5199: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
5200: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
5201: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
5202: for (i=1; i<= nlstate ; i ++) {
5203: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
5204: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5205: fprintf(ficgp," u 2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
5206: for (j=2; j<= nlstate+ndeath ; j ++) {
5207: fprintf(ficgp,",\\\n \"\" u 2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
5208: }
5209: fprintf(ficgp,";\nset out; unset ylabel;\n");
5210: }
5211: /* 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 */
5212: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5213: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
5214: fprintf(ficgp,"\nset out;unset log\n");
5215: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5216:
5217: strcpy(dirfileres,optionfilefiname);
5218: strcpy(optfileres,"vpl");
5219: /* 1eme*/
5220: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5221: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5222: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5223: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5224: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5225: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5226: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5227: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5228: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5229: vlv= nbcode[Tvaraff[lv]][lv];
5230: fprintf(ficgp," V%d=%d ",k,vlv);
5231: }
5232: fprintf(ficgp,"\n#\n");
5233:
5234: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5235: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5236: fprintf(ficgp,"set xlabel \"Age\" \n\
5237: set ylabel \"Probability\" \n\
5238: set ter svg size 640, 480\n\
5239: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5240:
5241: for (i=1; i<= nlstate ; i ++) {
5242: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5243: else fprintf(ficgp," %%*lf (%%*lf)");
5244: }
5245: 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);
5246: for (i=1; i<= nlstate ; i ++) {
5247: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5248: else fprintf(ficgp," %%*lf (%%*lf)");
5249: }
5250: 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);
5251: for (i=1; i<= nlstate ; i ++) {
5252: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5253: else fprintf(ficgp," %%*lf (%%*lf)");
5254: }
5255: 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));
5256: fprintf(ficgp,"\nset out \n");
5257: } /* k1 */
5258: } /* cpt */
5259: /*2 eme*/
5260: for (k1=1; k1<= m ; k1 ++) {
5261: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5262: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5263: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5264: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5265: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5266: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5267: vlv= nbcode[Tvaraff[lv]][lv];
5268: fprintf(ficgp," V%d=%d ",k,vlv);
5269: }
5270: fprintf(ficgp,"\n#\n");
5271:
5272: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5273: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5274: if(vpopbased==0)
5275: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5276: else
5277: fprintf(ficgp,"\nreplot ");
5278: for (i=1; i<= nlstate+1 ; i ++) {
5279: k=2*i;
5280: 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);
5281: for (j=1; j<= nlstate+1 ; j ++) {
5282: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5283: else fprintf(ficgp," %%*lf (%%*lf)");
5284: }
5285: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5286: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5287: 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);
5288: for (j=1; j<= nlstate+1 ; j ++) {
5289: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5290: else fprintf(ficgp," %%*lf (%%*lf)");
5291: }
5292: fprintf(ficgp,"\" t\"\" w l lt 0,");
5293: 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);
5294: for (j=1; j<= nlstate+1 ; j ++) {
5295: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5296: else fprintf(ficgp," %%*lf (%%*lf)");
5297: }
5298: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5299: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5300: } /* state */
5301: } /* vpopbased */
5302: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5303: } /* k1 */
5304:
5305:
5306: /*3eme*/
5307: for (k1=1; k1<= m ; k1 ++) {
5308: for (cpt=1; cpt<= nlstate ; cpt ++) {
5309: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5310: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5311: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5312: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5313: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5314: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5315: vlv= nbcode[Tvaraff[lv]][lv];
5316: fprintf(ficgp," V%d=%d ",k,vlv);
5317: }
5318: fprintf(ficgp,"\n#\n");
5319:
5320: /* k=2+nlstate*(2*cpt-2); */
5321: k=2+(nlstate+1)*(cpt-1);
5322: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5323: fprintf(ficgp,"set ter svg size 640, 480\n\
5324: 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);
5325: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5326: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5327: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5328: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5329: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5330: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5331:
5332: */
5333: for (i=1; i< nlstate ; i ++) {
5334: 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);
5335: /* 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);*/
5336:
5337: }
5338: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5339: }
5340: }
5341:
5342: /* Survival functions (period) from state i in state j by initial state i */
5343: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5344: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5345: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5346: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5347: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5348: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5349: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5350: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5351: vlv= nbcode[Tvaraff[lv]][lv];
5352: fprintf(ficgp," V%d=%d ",k,vlv);
5353: }
5354: fprintf(ficgp,"\n#\n");
5355:
5356: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5357: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5358: set ter svg size 640, 480\n\
5359: unset log y\n\
5360: plot [%.f:%.f] ", ageminpar, agemaxpar);
5361: k=3;
5362: for (i=1; i<= nlstate ; i ++){
5363: if(i==1)
5364: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5365: else
5366: fprintf(ficgp,", '' ");
5367: l=(nlstate+ndeath)*(i-1)+1;
5368: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5369: for (j=2; j<= nlstate+ndeath ; j ++)
5370: fprintf(ficgp,"+$%d",k+l+j-1);
5371: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5372: } /* nlstate */
5373: fprintf(ficgp,"\nset out\n");
5374: } /* end cpt state*/
5375: } /* end covariate */
5376:
5377: /* Survival functions (period) from state i in state j by final state j */
5378: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5379: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5380: 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);
5381: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5382: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5383: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5384: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5385: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5386: vlv= nbcode[Tvaraff[lv]][lv];
5387: fprintf(ficgp," V%d=%d ",k,vlv);
5388: }
5389: fprintf(ficgp,"\n#\n");
5390:
5391: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5392: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5393: set ter svg size 640, 480\n\
5394: unset log y\n\
5395: plot [%.f:%.f] ", ageminpar, agemaxpar);
5396: k=3;
5397: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5398: if(j==1)
5399: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5400: else
5401: fprintf(ficgp,", '' ");
5402: l=(nlstate+ndeath)*(cpt-1) +j;
5403: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5404: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5405: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5406: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5407: } /* nlstate */
5408: fprintf(ficgp,", '' ");
5409: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5410: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5411: l=(nlstate+ndeath)*(cpt-1) +j;
5412: if(j < nlstate)
5413: fprintf(ficgp,"$%d +",k+l);
5414: else
5415: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5416: }
5417: fprintf(ficgp,"\nset out\n");
5418: } /* end cpt state*/
5419: } /* end covariate */
5420:
5421: /* CV preval stable (period) for each covariate */
5422: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5423: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5424: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5425: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5426: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5427: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5428: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5429: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5430: vlv= nbcode[Tvaraff[lv]][lv];
5431: fprintf(ficgp," V%d=%d ",k,vlv);
5432: }
5433: fprintf(ficgp,"\n#\n");
5434:
5435: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5436: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5437: set ter svg size 640, 480\n\
5438: unset log y\n\
5439: plot [%.f:%.f] ", ageminpar, agemaxpar);
5440: k=3; /* Offset */
5441: for (i=1; i<= nlstate ; i ++){
5442: if(i==1)
5443: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5444: else
5445: fprintf(ficgp,", '' ");
5446: l=(nlstate+ndeath)*(i-1)+1;
5447: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5448: for (j=2; j<= nlstate ; j ++)
5449: fprintf(ficgp,"+$%d",k+l+j-1);
5450: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5451: } /* nlstate */
5452: fprintf(ficgp,"\nset out\n");
5453: } /* end cpt state*/
5454: } /* end covariate */
5455:
5456: if(prevfcast==1){
5457: /* Projection from cross-sectional to stable (period) for each covariate */
5458:
5459: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5460: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5461: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5462: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5463: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5464: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5465: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5466: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5467: vlv= nbcode[Tvaraff[lv]][lv];
5468: fprintf(ficgp," V%d=%d ",k,vlv);
5469: }
5470: fprintf(ficgp,"\n#\n");
5471:
5472: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
5473: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
5474: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
5475: set ter svg size 640, 480\n\
5476: unset log y\n\
5477: plot [%.f:%.f] ", ageminpar, agemaxpar);
5478: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
5479: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5480: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5481: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5482: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5483: if(i==1){
5484: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
5485: }else{
5486: fprintf(ficgp,",\\\n '' ");
5487: }
5488: if(cptcoveff ==0){ /* No covariate */
5489: fprintf(ficgp," u 2:("); /* Age is in 2 */
5490: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
5491: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
5492: if(i==nlstate+1)
5493: fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
5494: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,cpt );
5495: else
5496: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
5497: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5498: }else{
5499: fprintf(ficgp,"u 6:(("); /* Age is in 6 */
5500: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5501: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5502: kl=0;
5503: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
5504: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5505: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5506: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5507: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5508: vlv= nbcode[Tvaraff[lv]][lv];
5509: kl++;
5510: /* 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 *\/ */
5511: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5512: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5513: /* '' 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*/
5514: if(k==cptcoveff)
5515: if(i==nlstate+1)
5516: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5517: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,cpt );
5518: else
5519: 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], \
5520: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5521: else{
5522: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
5523: kl++;
5524: }
5525: } /* end covariate */
5526: } /* end if covariate */
5527: } /* nlstate */
5528: fprintf(ficgp,"\nset out\n");
5529: } /* end cpt state*/
5530: } /* end covariate */
5531: } /* End if prevfcast */
5532:
5533:
5534: /* proba elementaires */
5535: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5536: for(i=1,jk=1; i <=nlstate; i++){
5537: fprintf(ficgp,"# initial state %d\n",i);
5538: for(k=1; k <=(nlstate+ndeath); k++){
5539: if (k != i) {
5540: fprintf(ficgp,"# current state %d\n",k);
5541: for(j=1; j <=ncovmodel; j++){
5542: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5543: jk++;
5544: }
5545: fprintf(ficgp,"\n");
5546: }
5547: }
5548: }
5549: fprintf(ficgp,"##############\n#\n");
5550:
5551: /*goto avoid;*/
5552: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5553: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5554: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5555: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5556: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5557: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5558: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5559: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5560: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5561: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5562: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5563: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5564: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5565: fprintf(ficgp,"#\n");
5566: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5567: fprintf(ficgp,"# ng=%d\n",ng);
5568: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5569: for(jk=1; jk <=m; jk++) {
5570: fprintf(ficgp,"# jk=%d\n",jk);
5571: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5572: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5573: if (ng==1){
5574: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5575: fprintf(ficgp,"\nunset log y");
5576: }else if (ng==2){
5577: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5578: fprintf(ficgp,"\nset log y");
5579: }else if (ng==3){
5580: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5581: fprintf(ficgp,"\nset log y");
5582: }else
5583: fprintf(ficgp,"\nunset title ");
5584: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5585: i=1;
5586: for(k2=1; k2<=nlstate; k2++) {
5587: k3=i;
5588: for(k=1; k<=(nlstate+ndeath); k++) {
5589: if (k != k2){
5590: switch( ng) {
5591: case 1:
5592: if(nagesqr==0)
5593: fprintf(ficgp," p%d+p%d*x",i,i+1);
5594: else /* nagesqr =1 */
5595: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5596: break;
5597: case 2: /* ng=2 */
5598: if(nagesqr==0)
5599: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5600: else /* nagesqr =1 */
5601: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5602: break;
5603: case 3:
5604: if(nagesqr==0)
5605: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5606: else /* nagesqr =1 */
5607: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5608: break;
5609: }
5610: ij=1;/* To be checked else nbcode[0][0] wrong */
5611: for(j=3; j <=ncovmodel-nagesqr; j++) {
5612: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5613: if(ij <=cptcovage) { /* Bug valgrind */
5614: if((j-2)==Tage[ij]) { /* Bug valgrind */
5615: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5616: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5617: ij++;
5618: }
5619: }
5620: else
5621: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5622: }
5623: if(ng != 1){
5624: fprintf(ficgp,")/(1");
5625:
5626: for(k1=1; k1 <=nlstate; k1++){
5627: if(nagesqr==0)
5628: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5629: else /* nagesqr =1 */
5630: 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);
5631:
5632: ij=1;
5633: for(j=3; j <=ncovmodel-nagesqr; j++){
5634: if(ij <=cptcovage) { /* Bug valgrind */
5635: if((j-2)==Tage[ij]) { /* Bug valgrind */
5636: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5637: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5638: ij++;
5639: }
5640: }
5641: else
5642: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5643: }
5644: fprintf(ficgp,")");
5645: }
5646: fprintf(ficgp,")");
5647: if(ng ==2)
5648: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5649: else /* ng= 3 */
5650: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5651: }else{ /* end ng <> 1 */
5652: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5653: }
5654: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5655: i=i+ncovmodel;
5656: }
5657: } /* end k */
5658: } /* end k2 */
5659: fprintf(ficgp,"\n set out\n");
5660: } /* end jk */
5661: } /* end ng */
5662: /* avoid: */
5663: fflush(ficgp);
5664: } /* end gnuplot */
5665:
5666:
5667: /*************** Moving average **************/
5668: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5669:
5670: int i, cpt, cptcod;
5671: int modcovmax =1;
5672: int mobilavrange, mob;
5673: double age;
5674:
5675: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5676: a covariate has 2 modalities */
5677: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5678:
5679: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5680: if(mobilav==1) mobilavrange=5; /* default */
5681: else mobilavrange=mobilav;
5682: for (age=bage; age<=fage; age++)
5683: for (i=1; i<=nlstate;i++)
5684: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5685: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5686: /* We keep the original values on the extreme ages bage, fage and for
5687: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5688: we use a 5 terms etc. until the borders are no more concerned.
5689: */
5690: for (mob=3;mob <=mobilavrange;mob=mob+2){
5691: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5692: for (i=1; i<=nlstate;i++){
5693: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5694: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5695: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5696: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5697: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5698: }
5699: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5700: }
5701: }
5702: }/* end age */
5703: }/* end mob */
5704: }else return -1;
5705: return 0;
5706: }/* End movingaverage */
5707:
5708:
5709: /************** Forecasting ******************/
5710: 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){
5711: /* proj1, year, month, day of starting projection
5712: agemin, agemax range of age
5713: dateprev1 dateprev2 range of dates during which prevalence is computed
5714: anproj2 year of en of projection (same day and month as proj1).
5715: */
5716: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5717: double agec; /* generic age */
5718: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5719: double *popeffectif,*popcount;
5720: double ***p3mat;
5721: double ***mobaverage;
5722: char fileresf[FILENAMELENGTH];
5723:
5724: agelim=AGESUP;
5725: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
5726: in each health status at the date of interview (if between dateprev1 and dateprev2).
5727: We still use firstpass and lastpass as another selection.
5728: */
5729: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
5730: /* firstpass, lastpass, stepm, weightopt, model); */
5731: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5732:
5733: strcpy(fileresf,"F_");
5734: strcat(fileresf,fileresu);
5735: if((ficresf=fopen(fileresf,"w"))==NULL) {
5736: printf("Problem with forecast resultfile: %s\n", fileresf);
5737: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5738: }
5739: printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
5740: fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
5741:
5742: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5743:
5744: if (mobilav!=0) {
5745: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5746: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5747: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5748: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5749: }
5750: }
5751:
5752: stepsize=(int) (stepm+YEARM-1)/YEARM;
5753: if (stepm<=12) stepsize=1;
5754: if(estepm < stepm){
5755: printf ("Problem %d lower than %d\n",estepm, stepm);
5756: }
5757: else hstepm=estepm;
5758:
5759: hstepm=hstepm/stepm;
5760: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5761: fractional in yp1 */
5762: anprojmean=yp;
5763: yp2=modf((yp1*12),&yp);
5764: mprojmean=yp;
5765: yp1=modf((yp2*30.5),&yp);
5766: jprojmean=yp;
5767: if(jprojmean==0) jprojmean=1;
5768: if(mprojmean==0) jprojmean=1;
5769:
5770: i1=cptcoveff;
5771: if (cptcovn < 1){i1=1;}
5772:
5773: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5774:
5775: fprintf(ficresf,"#****** Routine prevforecast **\n");
5776:
5777: /* if (h==(int)(YEARM*yearp)){ */
5778: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5779: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5780: k=k+1;
5781: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
5782: for(j=1;j<=cptcoveff;j++) {
5783: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5784: }
5785: fprintf(ficresf," yearproj age");
5786: for(j=1; j<=nlstate+ndeath;j++){
5787: for(i=1; i<=nlstate;i++)
5788: fprintf(ficresf," p%d%d",i,j);
5789: fprintf(ficresf," p.%d",j);
5790: }
5791: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5792: fprintf(ficresf,"\n");
5793: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5794:
5795: for (agec=fage; agec>=(ageminpar-1); agec--){
5796: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5797: nhstepm = nhstepm/hstepm;
5798: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5799: oldm=oldms;savm=savms;
5800: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5801:
5802: for (h=0; h<=nhstepm; h++){
5803: if (h*hstepm/YEARM*stepm ==yearp) {
5804: fprintf(ficresf,"\n");
5805: for(j=1;j<=cptcoveff;j++)
5806: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5807: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5808: }
5809: for(j=1; j<=nlstate+ndeath;j++) {
5810: ppij=0.;
5811: for(i=1; i<=nlstate;i++) {
5812: if (mobilav==1)
5813: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5814: else {
5815: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5816: }
5817: if (h*hstepm/YEARM*stepm== yearp) {
5818: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5819: }
5820: } /* end i */
5821: if (h*hstepm/YEARM*stepm==yearp) {
5822: fprintf(ficresf," %.3f", ppij);
5823: }
5824: }/* end j */
5825: } /* end h */
5826: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5827: } /* end agec */
5828: } /* end yearp */
5829: } /* end cptcod */
5830: } /* end cptcov */
5831:
5832: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5833:
5834: fclose(ficresf);
5835: printf("End of Computing forecasting \n");
5836: fprintf(ficlog,"End of Computing forecasting\n");
5837:
5838: }
5839:
5840: /************** Forecasting *****not tested NB*************/
5841: 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){
5842:
5843: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5844: int *popage;
5845: double calagedatem, agelim, kk1, kk2;
5846: double *popeffectif,*popcount;
5847: double ***p3mat,***tabpop,***tabpopprev;
5848: double ***mobaverage;
5849: char filerespop[FILENAMELENGTH];
5850:
5851: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5852: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5853: agelim=AGESUP;
5854: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5855:
5856: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5857:
5858:
5859: strcpy(filerespop,"POP_");
5860: strcat(filerespop,fileresu);
5861: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5862: printf("Problem with forecast resultfile: %s\n", filerespop);
5863: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5864: }
5865: printf("Computing forecasting: result on file '%s' \n", filerespop);
5866: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5867:
5868: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5869:
5870: if (mobilav!=0) {
5871: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5872: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5873: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5874: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5875: }
5876: }
5877:
5878: stepsize=(int) (stepm+YEARM-1)/YEARM;
5879: if (stepm<=12) stepsize=1;
5880:
5881: agelim=AGESUP;
5882:
5883: hstepm=1;
5884: hstepm=hstepm/stepm;
5885:
5886: if (popforecast==1) {
5887: if((ficpop=fopen(popfile,"r"))==NULL) {
5888: printf("Problem with population file : %s\n",popfile);exit(0);
5889: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5890: }
5891: popage=ivector(0,AGESUP);
5892: popeffectif=vector(0,AGESUP);
5893: popcount=vector(0,AGESUP);
5894:
5895: i=1;
5896: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5897:
5898: imx=i;
5899: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5900: }
5901:
5902: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5903: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5904: k=k+1;
5905: fprintf(ficrespop,"\n#******");
5906: for(j=1;j<=cptcoveff;j++) {
5907: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5908: }
5909: fprintf(ficrespop,"******\n");
5910: fprintf(ficrespop,"# Age");
5911: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5912: if (popforecast==1) fprintf(ficrespop," [Population]");
5913:
5914: for (cpt=0; cpt<=0;cpt++) {
5915: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5916:
5917: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5918: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5919: nhstepm = nhstepm/hstepm;
5920:
5921: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5922: oldm=oldms;savm=savms;
5923: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5924:
5925: for (h=0; h<=nhstepm; h++){
5926: if (h==(int) (calagedatem+YEARM*cpt)) {
5927: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5928: }
5929: for(j=1; j<=nlstate+ndeath;j++) {
5930: kk1=0.;kk2=0;
5931: for(i=1; i<=nlstate;i++) {
5932: if (mobilav==1)
5933: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5934: else {
5935: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5936: }
5937: }
5938: if (h==(int)(calagedatem+12*cpt)){
5939: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5940: /*fprintf(ficrespop," %.3f", kk1);
5941: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5942: }
5943: }
5944: for(i=1; i<=nlstate;i++){
5945: kk1=0.;
5946: for(j=1; j<=nlstate;j++){
5947: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5948: }
5949: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5950: }
5951:
5952: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5953: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5954: }
5955: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5956: }
5957: }
5958:
5959: /******/
5960:
5961: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5962: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5963: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5964: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5965: nhstepm = nhstepm/hstepm;
5966:
5967: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5968: oldm=oldms;savm=savms;
5969: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5970: for (h=0; h<=nhstepm; h++){
5971: if (h==(int) (calagedatem+YEARM*cpt)) {
5972: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5973: }
5974: for(j=1; j<=nlstate+ndeath;j++) {
5975: kk1=0.;kk2=0;
5976: for(i=1; i<=nlstate;i++) {
5977: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5978: }
5979: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5980: }
5981: }
5982: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5983: }
5984: }
5985: }
5986: }
5987:
5988: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5989:
5990: if (popforecast==1) {
5991: free_ivector(popage,0,AGESUP);
5992: free_vector(popeffectif,0,AGESUP);
5993: free_vector(popcount,0,AGESUP);
5994: }
5995: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5996: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5997: fclose(ficrespop);
5998: } /* End of popforecast */
5999:
6000: int fileappend(FILE *fichier, char *optionfich)
6001: {
6002: if((fichier=fopen(optionfich,"a"))==NULL) {
6003: printf("Problem with file: %s\n", optionfich);
6004: fprintf(ficlog,"Problem with file: %s\n", optionfich);
6005: return (0);
6006: }
6007: fflush(fichier);
6008: return (1);
6009: }
6010:
6011:
6012: /**************** function prwizard **********************/
6013: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
6014: {
6015:
6016: /* Wizard to print covariance matrix template */
6017:
6018: char ca[32], cb[32];
6019: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
6020: int numlinepar;
6021:
6022: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6023: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6024: for(i=1; i <=nlstate; i++){
6025: jj=0;
6026: for(j=1; j <=nlstate+ndeath; j++){
6027: if(j==i) continue;
6028: jj++;
6029: /*ca[0]= k+'a'-1;ca[1]='\0';*/
6030: printf("%1d%1d",i,j);
6031: fprintf(ficparo,"%1d%1d",i,j);
6032: for(k=1; k<=ncovmodel;k++){
6033: /* printf(" %lf",param[i][j][k]); */
6034: /* fprintf(ficparo," %lf",param[i][j][k]); */
6035: printf(" 0.");
6036: fprintf(ficparo," 0.");
6037: }
6038: printf("\n");
6039: fprintf(ficparo,"\n");
6040: }
6041: }
6042: printf("# Scales (for hessian or gradient estimation)\n");
6043: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
6044: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
6045: for(i=1; i <=nlstate; i++){
6046: jj=0;
6047: for(j=1; j <=nlstate+ndeath; j++){
6048: if(j==i) continue;
6049: jj++;
6050: fprintf(ficparo,"%1d%1d",i,j);
6051: printf("%1d%1d",i,j);
6052: fflush(stdout);
6053: for(k=1; k<=ncovmodel;k++){
6054: /* printf(" %le",delti3[i][j][k]); */
6055: /* fprintf(ficparo," %le",delti3[i][j][k]); */
6056: printf(" 0.");
6057: fprintf(ficparo," 0.");
6058: }
6059: numlinepar++;
6060: printf("\n");
6061: fprintf(ficparo,"\n");
6062: }
6063: }
6064: printf("# Covariance matrix\n");
6065: /* # 121 Var(a12)\n\ */
6066: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6067: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6068: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6069: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6070: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6071: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6072: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6073: fflush(stdout);
6074: fprintf(ficparo,"# Covariance matrix\n");
6075: /* # 121 Var(a12)\n\ */
6076: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6077: /* # ...\n\ */
6078: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6079:
6080: for(itimes=1;itimes<=2;itimes++){
6081: jj=0;
6082: for(i=1; i <=nlstate; i++){
6083: for(j=1; j <=nlstate+ndeath; j++){
6084: if(j==i) continue;
6085: for(k=1; k<=ncovmodel;k++){
6086: jj++;
6087: ca[0]= k+'a'-1;ca[1]='\0';
6088: if(itimes==1){
6089: printf("#%1d%1d%d",i,j,k);
6090: fprintf(ficparo,"#%1d%1d%d",i,j,k);
6091: }else{
6092: printf("%1d%1d%d",i,j,k);
6093: fprintf(ficparo,"%1d%1d%d",i,j,k);
6094: /* printf(" %.5le",matcov[i][j]); */
6095: }
6096: ll=0;
6097: for(li=1;li <=nlstate; li++){
6098: for(lj=1;lj <=nlstate+ndeath; lj++){
6099: if(lj==li) continue;
6100: for(lk=1;lk<=ncovmodel;lk++){
6101: ll++;
6102: if(ll<=jj){
6103: cb[0]= lk +'a'-1;cb[1]='\0';
6104: if(ll<jj){
6105: if(itimes==1){
6106: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6107: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6108: }else{
6109: printf(" 0.");
6110: fprintf(ficparo," 0.");
6111: }
6112: }else{
6113: if(itimes==1){
6114: printf(" Var(%s%1d%1d)",ca,i,j);
6115: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
6116: }else{
6117: printf(" 0.");
6118: fprintf(ficparo," 0.");
6119: }
6120: }
6121: }
6122: } /* end lk */
6123: } /* end lj */
6124: } /* end li */
6125: printf("\n");
6126: fprintf(ficparo,"\n");
6127: numlinepar++;
6128: } /* end k*/
6129: } /*end j */
6130: } /* end i */
6131: } /* end itimes */
6132:
6133: } /* end of prwizard */
6134: /******************* Gompertz Likelihood ******************************/
6135: double gompertz(double x[])
6136: {
6137: double A,B,L=0.0,sump=0.,num=0.;
6138: int i,n=0; /* n is the size of the sample */
6139:
6140: for (i=0;i<=imx-1 ; i++) {
6141: sump=sump+weight[i];
6142: /* sump=sump+1;*/
6143: num=num+1;
6144: }
6145:
6146:
6147: /* for (i=0; i<=imx; i++)
6148: 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]);*/
6149:
6150: for (i=1;i<=imx ; i++)
6151: {
6152: if (cens[i] == 1 && wav[i]>1)
6153: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
6154:
6155: if (cens[i] == 0 && wav[i]>1)
6156: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
6157: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
6158:
6159: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6160: if (wav[i] > 1 ) { /* ??? */
6161: L=L+A*weight[i];
6162: /* 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]);*/
6163: }
6164: }
6165:
6166: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6167:
6168: return -2*L*num/sump;
6169: }
6170:
6171: #ifdef GSL
6172: /******************* Gompertz_f Likelihood ******************************/
6173: double gompertz_f(const gsl_vector *v, void *params)
6174: {
6175: double A,B,LL=0.0,sump=0.,num=0.;
6176: double *x= (double *) v->data;
6177: int i,n=0; /* n is the size of the sample */
6178:
6179: for (i=0;i<=imx-1 ; i++) {
6180: sump=sump+weight[i];
6181: /* sump=sump+1;*/
6182: num=num+1;
6183: }
6184:
6185:
6186: /* for (i=0; i<=imx; i++)
6187: 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]);*/
6188: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
6189: for (i=1;i<=imx ; i++)
6190: {
6191: if (cens[i] == 1 && wav[i]>1)
6192: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
6193:
6194: if (cens[i] == 0 && wav[i]>1)
6195: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6196: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6197:
6198: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6199: if (wav[i] > 1 ) { /* ??? */
6200: LL=LL+A*weight[i];
6201: /* 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]);*/
6202: }
6203: }
6204:
6205: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6206: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6207:
6208: return -2*LL*num/sump;
6209: }
6210: #endif
6211:
6212: /******************* Printing html file ***********/
6213: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
6214: int lastpass, int stepm, int weightopt, char model[],\
6215: int imx, double p[],double **matcov,double agemortsup){
6216: int i,k;
6217:
6218: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
6219: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
6220: for (i=1;i<=2;i++)
6221: 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]));
6222: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
6223: fprintf(fichtm,"</ul>");
6224:
6225: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
6226:
6227: 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>");
6228:
6229: for (k=agegomp;k<(agemortsup-2);k++)
6230: 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]);
6231:
6232:
6233: fflush(fichtm);
6234: }
6235:
6236: /******************* Gnuplot file **************/
6237: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
6238:
6239: char dirfileres[132],optfileres[132];
6240:
6241: int ng;
6242:
6243:
6244: /*#ifdef windows */
6245: fprintf(ficgp,"cd \"%s\" \n",pathc);
6246: /*#endif */
6247:
6248:
6249: strcpy(dirfileres,optionfilefiname);
6250: strcpy(optfileres,"vpl");
6251: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
6252: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
6253: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
6254: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
6255: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
6256:
6257: }
6258:
6259: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
6260: {
6261:
6262: /*-------- data file ----------*/
6263: FILE *fic;
6264: char dummy[]=" ";
6265: int i=0, j=0, n=0;
6266: int linei, month, year,iout;
6267: char line[MAXLINE], linetmp[MAXLINE];
6268: char stra[MAXLINE], strb[MAXLINE];
6269: char *stratrunc;
6270: int lstra;
6271:
6272:
6273: if((fic=fopen(datafile,"r"))==NULL) {
6274: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
6275: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
6276: }
6277:
6278: i=1;
6279: linei=0;
6280: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
6281: linei=linei+1;
6282: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
6283: if(line[j] == '\t')
6284: line[j] = ' ';
6285: }
6286: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
6287: ;
6288: };
6289: line[j+1]=0; /* Trims blanks at end of line */
6290: if(line[0]=='#'){
6291: fprintf(ficlog,"Comment line\n%s\n",line);
6292: printf("Comment line\n%s\n",line);
6293: continue;
6294: }
6295: trimbb(linetmp,line); /* Trims multiple blanks in line */
6296: strcpy(line, linetmp);
6297:
6298:
6299: for (j=maxwav;j>=1;j--){
6300: cutv(stra, strb, line, ' ');
6301: if(strb[0]=='.') { /* Missing status */
6302: lval=-1;
6303: }else{
6304: errno=0;
6305: lval=strtol(strb,&endptr,10);
6306: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
6307: if( strb[0]=='\0' || (*endptr != '\0')){
6308: 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);
6309: 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);
6310: return 1;
6311: }
6312: }
6313: s[j][i]=lval;
6314:
6315: strcpy(line,stra);
6316: cutv(stra, strb,line,' ');
6317: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6318: }
6319: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6320: month=99;
6321: year=9999;
6322: }else{
6323: 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);
6324: 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);
6325: return 1;
6326: }
6327: anint[j][i]= (double) year;
6328: mint[j][i]= (double)month;
6329: strcpy(line,stra);
6330: } /* ENd Waves */
6331:
6332: cutv(stra, strb,line,' ');
6333: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6334: }
6335: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6336: month=99;
6337: year=9999;
6338: }else{
6339: 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);
6340: 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);
6341: return 1;
6342: }
6343: andc[i]=(double) year;
6344: moisdc[i]=(double) month;
6345: strcpy(line,stra);
6346:
6347: cutv(stra, strb,line,' ');
6348: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6349: }
6350: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
6351: month=99;
6352: year=9999;
6353: }else{
6354: 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);
6355: 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);
6356: return 1;
6357: }
6358: if (year==9999) {
6359: 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);
6360: 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);
6361: return 1;
6362:
6363: }
6364: annais[i]=(double)(year);
6365: moisnais[i]=(double)(month);
6366: strcpy(line,stra);
6367:
6368: cutv(stra, strb,line,' ');
6369: errno=0;
6370: dval=strtod(strb,&endptr);
6371: if( strb[0]=='\0' || (*endptr != '\0')){
6372: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6373: 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);
6374: fflush(ficlog);
6375: return 1;
6376: }
6377: weight[i]=dval;
6378: strcpy(line,stra);
6379:
6380: for (j=ncovcol;j>=1;j--){
6381: cutv(stra, strb,line,' ');
6382: if(strb[0]=='.') { /* Missing status */
6383: lval=-1;
6384: }else{
6385: errno=0;
6386: lval=strtol(strb,&endptr,10);
6387: if( strb[0]=='\0' || (*endptr != '\0')){
6388: 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);
6389: 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);
6390: return 1;
6391: }
6392: }
6393: if(lval <-1 || lval >1){
6394: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6395: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6396: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6397: For example, for multinomial values like 1, 2 and 3,\n \
6398: build V1=0 V2=0 for the reference value (1),\n \
6399: V1=1 V2=0 for (2) \n \
6400: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6401: output of IMaCh is often meaningless.\n \
6402: Exiting.\n",lval,linei, i,line,j);
6403: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6404: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6405: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6406: For example, for multinomial values like 1, 2 and 3,\n \
6407: build V1=0 V2=0 for the reference value (1),\n \
6408: V1=1 V2=0 for (2) \n \
6409: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6410: output of IMaCh is often meaningless.\n \
6411: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6412: return 1;
6413: }
6414: covar[j][i]=(double)(lval);
6415: strcpy(line,stra);
6416: }
6417: lstra=strlen(stra);
6418:
6419: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6420: stratrunc = &(stra[lstra-9]);
6421: num[i]=atol(stratrunc);
6422: }
6423: else
6424: num[i]=atol(stra);
6425: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6426: 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;}*/
6427:
6428: i=i+1;
6429: } /* End loop reading data */
6430:
6431: *imax=i-1; /* Number of individuals */
6432: fclose(fic);
6433:
6434: return (0);
6435: /* endread: */
6436: printf("Exiting readdata: ");
6437: fclose(fic);
6438: return (1);
6439:
6440:
6441:
6442: }
6443: void removespace(char *str) {
6444: char *p1 = str, *p2 = str;
6445: do
6446: while (*p2 == ' ')
6447: p2++;
6448: while (*p1++ == *p2++);
6449: }
6450:
6451: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
6452: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6453: * - nagesqr = 1 if age*age in the model, otherwise 0.
6454: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6455: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6456: * - cptcovage number of covariates with age*products =2
6457: * - cptcovs number of simple covariates
6458: * - 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
6459: * which is a new column after the 9 (ncovcol) variables.
6460: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6461: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6462: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6463: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6464: */
6465: {
6466: int i, j, k, ks;
6467: int j1, k1, k2;
6468: char modelsav[80];
6469: char stra[80], strb[80], strc[80], strd[80],stre[80];
6470: char *strpt;
6471:
6472: /*removespace(model);*/
6473: if (strlen(model) >1){ /* If there is at least 1 covariate */
6474: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6475: if (strstr(model,"AGE") !=0){
6476: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6477: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6478: return 1;
6479: }
6480: if (strstr(model,"v") !=0){
6481: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6482: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6483: return 1;
6484: }
6485: strcpy(modelsav,model);
6486: if ((strpt=strstr(model,"age*age")) !=0){
6487: printf(" strpt=%s, model=%s\n",strpt, model);
6488: if(strpt != model){
6489: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6490: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6491: corresponding column of parameters.\n",model);
6492: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6493: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6494: corresponding column of parameters.\n",model); fflush(ficlog);
6495: return 1;
6496: }
6497:
6498: nagesqr=1;
6499: if (strstr(model,"+age*age") !=0)
6500: substrchaine(modelsav, model, "+age*age");
6501: else if (strstr(model,"age*age+") !=0)
6502: substrchaine(modelsav, model, "age*age+");
6503: else
6504: substrchaine(modelsav, model, "age*age");
6505: }else
6506: nagesqr=0;
6507: if (strlen(modelsav) >1){
6508: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6509: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6510: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6511: cptcovt= j+1; /* Number of total covariates in the model, not including
6512: * cst, age and age*age
6513: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6514: /* including age products which are counted in cptcovage.
6515: * but the covariates which are products must be treated
6516: * separately: ncovn=4- 2=2 (V1+V3). */
6517: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6518: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6519:
6520:
6521: /* Design
6522: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6523: * < ncovcol=8 >
6524: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6525: * k= 1 2 3 4 5 6 7 8
6526: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6527: * covar[k,i], value of kth covariate if not including age for individual i:
6528: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6529: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6530: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6531: * Tage[++cptcovage]=k
6532: * if products, new covar are created after ncovcol with k1
6533: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6534: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6535: * 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
6536: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6537: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6538: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6539: * < ncovcol=8 >
6540: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6541: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6542: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6543: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6544: * p Tprod[1]@2={ 6, 5}
6545: *p Tvard[1][1]@4= {7, 8, 5, 6}
6546: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6547: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6548: *How to reorganize?
6549: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6550: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6551: * {2, 1, 4, 8, 5, 6, 3, 7}
6552: * Struct []
6553: */
6554:
6555: /* This loop fills the array Tvar from the string 'model'.*/
6556: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6557: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6558: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6559: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6560: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6561: /* k=1 Tvar[1]=2 (from V2) */
6562: /* k=5 Tvar[5] */
6563: /* for (k=1; k<=cptcovn;k++) { */
6564: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6565: /* } */
6566: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6567: /*
6568: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6569: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6570: Tvar[k]=0;
6571: cptcovage=0;
6572: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6573: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6574: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6575: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6576: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6577: /*scanf("%d",i);*/
6578: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6579: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6580: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6581: /* covar is not filled and then is empty */
6582: cptcovprod--;
6583: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6584: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6585: cptcovage++; /* Sums the number of covariates which include age as a product */
6586: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6587: /*printf("stre=%s ", stre);*/
6588: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6589: cptcovprod--;
6590: cutl(stre,strb,strc,'V');
6591: Tvar[k]=atoi(stre);
6592: cptcovage++;
6593: Tage[cptcovage]=k;
6594: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6595: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6596: cptcovn++;
6597: cptcovprodnoage++;k1++;
6598: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6599: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6600: because this model-covariate is a construction we invent a new column
6601: ncovcol + k1
6602: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6603: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6604: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6605: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6606: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6607: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6608: k2=k2+2;
6609: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6610: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6611: for (i=1; i<=lastobs;i++){
6612: /* Computes the new covariate which is a product of
6613: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6614: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6615: }
6616: } /* End age is not in the model */
6617: } /* End if model includes a product */
6618: else { /* no more sum */
6619: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6620: /* scanf("%d",i);*/
6621: cutl(strd,strc,strb,'V');
6622: ks++; /**< Number of simple covariates */
6623: cptcovn++;
6624: Tvar[k]=atoi(strd);
6625: }
6626: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6627: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6628: scanf("%d",i);*/
6629: } /* end of loop + on total covariates */
6630: } /* end if strlen(modelsave == 0) age*age might exist */
6631: } /* end if strlen(model == 0) */
6632:
6633: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6634: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6635:
6636: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6637: printf("cptcovprod=%d ", cptcovprod);
6638: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6639:
6640: scanf("%d ",i);*/
6641:
6642:
6643: return (0); /* with covar[new additional covariate if product] and Tage if age */
6644: /*endread:*/
6645: printf("Exiting decodemodel: ");
6646: return (1);
6647: }
6648:
6649: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6650: {
6651: int i, m;
6652:
6653: for (i=1; i<=imx; i++) {
6654: for(m=2; (m<= maxwav); m++) {
6655: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6656: anint[m][i]=9999;
6657: if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
6658: s[m][i]=-1;
6659: }
6660: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6661: *nberr = *nberr + 1;
6662: 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);
6663: 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);
6664: s[m][i]=-1;
6665: }
6666: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6667: (*nberr)++;
6668: 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]);
6669: 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]);
6670: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6671: }
6672: }
6673: }
6674:
6675: for (i=1; i<=imx; i++) {
6676: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6677: for(m=firstpass; (m<= lastpass); m++){
6678: if(s[m][i] >0 || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
6679: if (s[m][i] >= nlstate+1) {
6680: if(agedc[i]>0){
6681: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6682: agev[m][i]=agedc[i];
6683: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6684: }else {
6685: if ((int)andc[i]!=9999){
6686: nbwarn++;
6687: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6688: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6689: agev[m][i]=-1;
6690: }
6691: }
6692: } /* agedc > 0 */
6693: } /* end if */
6694: else if(s[m][i] !=9){ /* Standard case, age in fractional
6695: years but with the precision of a month */
6696: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6697: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6698: agev[m][i]=1;
6699: else if(agev[m][i] < *agemin){
6700: *agemin=agev[m][i];
6701: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6702: }
6703: else if(agev[m][i] >*agemax){
6704: *agemax=agev[m][i];
6705: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6706: }
6707: /*agev[m][i]=anint[m][i]-annais[i];*/
6708: /* agev[m][i] = age[i]+2*m;*/
6709: } /* en if 9*/
6710: else { /* =9 */
6711: /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
6712: agev[m][i]=1;
6713: s[m][i]=-1;
6714: }
6715: }
6716: else if(s[m][i]==0) /*= 0 Unknown */
6717: agev[m][i]=1;
6718: else{
6719: printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
6720: fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
6721: agev[m][i]=0;
6722: }
6723: } /* End for lastpass */
6724: }
6725:
6726: for (i=1; i<=imx; i++) {
6727: for(m=firstpass; (m<=lastpass); m++){
6728: if (s[m][i] > (nlstate+ndeath)) {
6729: (*nberr)++;
6730: 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);
6731: 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);
6732: return 1;
6733: }
6734: }
6735: }
6736:
6737: /*for (i=1; i<=imx; i++){
6738: for (m=firstpass; (m<lastpass); m++){
6739: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6740: }
6741:
6742: }*/
6743:
6744:
6745: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6746: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6747:
6748: return (0);
6749: /* endread:*/
6750: printf("Exiting calandcheckages: ");
6751: return (1);
6752: }
6753:
6754: #if defined(_MSC_VER)
6755: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6756: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6757: //#include "stdafx.h"
6758: //#include <stdio.h>
6759: //#include <tchar.h>
6760: //#include <windows.h>
6761: //#include <iostream>
6762: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6763:
6764: LPFN_ISWOW64PROCESS fnIsWow64Process;
6765:
6766: BOOL IsWow64()
6767: {
6768: BOOL bIsWow64 = FALSE;
6769:
6770: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6771: // (HANDLE, PBOOL);
6772:
6773: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6774:
6775: HMODULE module = GetModuleHandle(_T("kernel32"));
6776: const char funcName[] = "IsWow64Process";
6777: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6778: GetProcAddress(module, funcName);
6779:
6780: if (NULL != fnIsWow64Process)
6781: {
6782: if (!fnIsWow64Process(GetCurrentProcess(),
6783: &bIsWow64))
6784: //throw std::exception("Unknown error");
6785: printf("Unknown error\n");
6786: }
6787: return bIsWow64 != FALSE;
6788: }
6789: #endif
6790:
6791: void syscompilerinfo(int logged)
6792: {
6793: /* #include "syscompilerinfo.h"*/
6794: /* command line Intel compiler 32bit windows, XP compatible:*/
6795: /* /GS /W3 /Gy
6796: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6797: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6798: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6799: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6800: */
6801: /* 64 bits */
6802: /*
6803: /GS /W3 /Gy
6804: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6805: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6806: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6807: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6808: /* Optimization are useless and O3 is slower than O2 */
6809: /*
6810: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6811: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6812: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6813: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6814: */
6815: /* Link is */ /* /OUT:"visual studio
6816: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6817: /PDB:"visual studio
6818: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6819: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6820: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6821: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6822: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6823: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6824: uiAccess='false'"
6825: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6826: /NOLOGO /TLBID:1
6827: */
6828: #if defined __INTEL_COMPILER
6829: #if defined(__GNUC__)
6830: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6831: #endif
6832: #elif defined(__GNUC__)
6833: #ifndef __APPLE__
6834: #include <gnu/libc-version.h> /* Only on gnu */
6835: #endif
6836: struct utsname sysInfo;
6837: int cross = CROSS;
6838: if (cross){
6839: printf("Cross-");
6840: if(logged) fprintf(ficlog, "Cross-");
6841: }
6842: #endif
6843:
6844: #include <stdint.h>
6845:
6846: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6847: #if defined(__clang__)
6848: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6849: #endif
6850: #if defined(__ICC) || defined(__INTEL_COMPILER)
6851: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6852: #endif
6853: #if defined(__GNUC__) || defined(__GNUG__)
6854: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6855: #endif
6856: #if defined(__HP_cc) || defined(__HP_aCC)
6857: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6858: #endif
6859: #if defined(__IBMC__) || defined(__IBMCPP__)
6860: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6861: #endif
6862: #if defined(_MSC_VER)
6863: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6864: #endif
6865: #if defined(__PGI)
6866: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6867: #endif
6868: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6869: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6870: #endif
6871: printf(" for "); if (logged) fprintf(ficlog, " for ");
6872:
6873: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6874: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6875: // Windows (x64 and x86)
6876: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6877: #elif __unix__ // all unices, not all compilers
6878: // Unix
6879: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6880: #elif __linux__
6881: // linux
6882: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6883: #elif __APPLE__
6884: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6885: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6886: #endif
6887:
6888: /* __MINGW32__ */
6889: /* __CYGWIN__ */
6890: /* __MINGW64__ */
6891: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6892: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6893: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6894: /* _WIN64 // Defined for applications for Win64. */
6895: /* _M_X64 // Defined for compilations that target x64 processors. */
6896: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6897:
6898: #if UINTPTR_MAX == 0xffffffff
6899: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6900: #elif UINTPTR_MAX == 0xffffffffffffffff
6901: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6902: #else
6903: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6904: #endif
6905:
6906: #if defined(__GNUC__)
6907: # if defined(__GNUC_PATCHLEVEL__)
6908: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6909: + __GNUC_MINOR__ * 100 \
6910: + __GNUC_PATCHLEVEL__)
6911: # else
6912: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6913: + __GNUC_MINOR__ * 100)
6914: # endif
6915: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6916: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6917:
6918: if (uname(&sysInfo) != -1) {
6919: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6920: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6921: }
6922: else
6923: perror("uname() error");
6924: //#ifndef __INTEL_COMPILER
6925: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6926: printf("GNU libc version: %s\n", gnu_get_libc_version());
6927: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6928: #endif
6929: #endif
6930:
6931: // void main()
6932: // {
6933: #if defined(_MSC_VER)
6934: if (IsWow64()){
6935: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6936: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6937: }
6938: else{
6939: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6940: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6941: }
6942: // printf("\nPress Enter to continue...");
6943: // getchar();
6944: // }
6945:
6946: #endif
6947:
6948:
6949: }
6950:
6951: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
6952: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6953: int i, j, k, i1 ;
6954: /* double ftolpl = 1.e-10; */
6955: double age, agebase, agelim;
6956: double tot;
6957:
6958: strcpy(filerespl,"PL_");
6959: strcat(filerespl,fileresu);
6960: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6961: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6962: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6963: }
6964: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6965: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6966: pstamp(ficrespl);
6967: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6968: fprintf(ficrespl,"#Age ");
6969: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6970: fprintf(ficrespl,"\n");
6971:
6972: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6973:
6974: agebase=ageminpar;
6975: agelim=agemaxpar;
6976:
6977: i1=pow(2,cptcoveff);
6978: if (cptcovn < 1){i1=1;}
6979:
6980: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6981: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6982: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6983: k=k+1;
6984: /* to clean */
6985: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6986: fprintf(ficrespl,"#******");
6987: printf("#******");
6988: fprintf(ficlog,"#******");
6989: for(j=1;j<=cptcoveff;j++) {
6990: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6991: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6992: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6993: }
6994: fprintf(ficrespl,"******\n");
6995: printf("******\n");
6996: fprintf(ficlog,"******\n");
6997:
6998: fprintf(ficrespl,"#Age ");
6999: for(j=1;j<=cptcoveff;j++) {
7000: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7001: }
7002: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
7003: fprintf(ficrespl,"Total Years_to_converge\n");
7004:
7005: for (age=agebase; age<=agelim; age++){
7006: /* for (age=agebase; age<=agebase; age++){ */
7007: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
7008: fprintf(ficrespl,"%.0f ",age );
7009: for(j=1;j<=cptcoveff;j++)
7010: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7011: tot=0.;
7012: for(i=1; i<=nlstate;i++){
7013: tot += prlim[i][i];
7014: fprintf(ficrespl," %.5f", prlim[i][i]);
7015: }
7016: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
7017: } /* Age */
7018: /* was end of cptcod */
7019: } /* cptcov */
7020: return 0;
7021: }
7022:
7023: int hPijx(double *p, int bage, int fage){
7024: /*------------- h Pij x at various ages ------------*/
7025:
7026: int stepsize;
7027: int agelim;
7028: int hstepm;
7029: int nhstepm;
7030: int h, i, i1, j, k;
7031:
7032: double agedeb;
7033: double ***p3mat;
7034:
7035: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
7036: if((ficrespij=fopen(filerespij,"w"))==NULL) {
7037: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
7038: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
7039: }
7040: printf("Computing pij: result on file '%s' \n", filerespij);
7041: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
7042:
7043: stepsize=(int) (stepm+YEARM-1)/YEARM;
7044: /*if (stepm<=24) stepsize=2;*/
7045:
7046: agelim=AGESUP;
7047: hstepm=stepsize*YEARM; /* Every year of age */
7048: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
7049:
7050: /* hstepm=1; aff par mois*/
7051: pstamp(ficrespij);
7052: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
7053: i1= pow(2,cptcoveff);
7054: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
7055: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
7056: /* k=k+1; */
7057: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7058: fprintf(ficrespij,"\n#****** ");
7059: for(j=1;j<=cptcoveff;j++)
7060: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7061: fprintf(ficrespij,"******\n");
7062:
7063: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
7064: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
7065: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
7066:
7067: /* nhstepm=nhstepm*YEARM; aff par mois*/
7068:
7069: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7070: oldm=oldms;savm=savms;
7071: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
7072: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
7073: for(i=1; i<=nlstate;i++)
7074: for(j=1; j<=nlstate+ndeath;j++)
7075: fprintf(ficrespij," %1d-%1d",i,j);
7076: fprintf(ficrespij,"\n");
7077: for (h=0; h<=nhstepm; h++){
7078: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
7079: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
7080: for(i=1; i<=nlstate;i++)
7081: for(j=1; j<=nlstate+ndeath;j++)
7082: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
7083: fprintf(ficrespij,"\n");
7084: }
7085: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7086: fprintf(ficrespij,"\n");
7087: }
7088: /*}*/
7089: }
7090: return 0;
7091: }
7092:
7093:
7094: /***********************************************/
7095: /**************** Main Program *****************/
7096: /***********************************************/
7097:
7098: int main(int argc, char *argv[])
7099: {
7100: #ifdef GSL
7101: const gsl_multimin_fminimizer_type *T;
7102: size_t iteri = 0, it;
7103: int rval = GSL_CONTINUE;
7104: int status = GSL_SUCCESS;
7105: double ssval;
7106: #endif
7107: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
7108: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
7109: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
7110: int jj, ll, li, lj, lk;
7111: int numlinepar=0; /* Current linenumber of parameter file */
7112: int num_filled;
7113: int itimes;
7114: int NDIM=2;
7115: int vpopbased=0;
7116:
7117: char ca[32], cb[32];
7118: /* FILE *fichtm; *//* Html File */
7119: /* FILE *ficgp;*/ /*Gnuplot File */
7120: struct stat info;
7121: double agedeb=0.;
7122:
7123: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
7124:
7125: double fret;
7126: double dum=0.; /* Dummy variable */
7127: double ***p3mat;
7128: double ***mobaverage;
7129:
7130: char line[MAXLINE];
7131: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
7132:
7133: char model[MAXLINE], modeltemp[MAXLINE];
7134: char pathr[MAXLINE], pathimach[MAXLINE];
7135: char *tok, *val; /* pathtot */
7136: int firstobs=1, lastobs=10;
7137: int c, h , cpt, c2;
7138: int jl=0;
7139: int i1, j1, jk, stepsize=0;
7140: int count=0;
7141:
7142: int *tab;
7143: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
7144: int mobilav=0,popforecast=0;
7145: int hstepm=0, nhstepm=0;
7146: int agemortsup;
7147: float sumlpop=0.;
7148: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
7149: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
7150:
7151: double bage=0, fage=110., age, agelim=0., agebase=0.;
7152: double ftolpl=FTOL;
7153: double **prlim;
7154: double ***param; /* Matrix of parameters */
7155: double *p;
7156: double **matcov; /* Matrix of covariance */
7157: double **hess; /* Hessian matrix */
7158: double ***delti3; /* Scale */
7159: double *delti; /* Scale */
7160: double ***eij, ***vareij;
7161: double **varpl; /* Variances of prevalence limits by age */
7162: double *epj, vepp;
7163:
7164: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
7165: double **ximort;
7166: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
7167: int *dcwave;
7168:
7169: char z[1]="c";
7170:
7171: /*char *strt;*/
7172: char strtend[80];
7173:
7174:
7175: /* setlocale (LC_ALL, ""); */
7176: /* bindtextdomain (PACKAGE, LOCALEDIR); */
7177: /* textdomain (PACKAGE); */
7178: /* setlocale (LC_CTYPE, ""); */
7179: /* setlocale (LC_MESSAGES, ""); */
7180:
7181: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
7182: rstart_time = time(NULL);
7183: /* (void) gettimeofday(&start_time,&tzp);*/
7184: start_time = *localtime(&rstart_time);
7185: curr_time=start_time;
7186: /*tml = *localtime(&start_time.tm_sec);*/
7187: /* strcpy(strstart,asctime(&tml)); */
7188: strcpy(strstart,asctime(&start_time));
7189:
7190: /* printf("Localtime (at start)=%s",strstart); */
7191: /* tp.tm_sec = tp.tm_sec +86400; */
7192: /* tm = *localtime(&start_time.tm_sec); */
7193: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
7194: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
7195: /* tmg.tm_hour=tmg.tm_hour + 1; */
7196: /* tp.tm_sec = mktime(&tmg); */
7197: /* strt=asctime(&tmg); */
7198: /* printf("Time(after) =%s",strstart); */
7199: /* (void) time (&time_value);
7200: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
7201: * tm = *localtime(&time_value);
7202: * strstart=asctime(&tm);
7203: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
7204: */
7205:
7206: nberr=0; /* Number of errors and warnings */
7207: nbwarn=0;
7208: #ifdef WIN32
7209: _getcwd(pathcd, size);
7210: #else
7211: getcwd(pathcd, size);
7212: #endif
7213: syscompilerinfo(0);
7214: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
7215: if(argc <=1){
7216: printf("\nEnter the parameter file name: ");
7217: if(!fgets(pathr,FILENAMELENGTH,stdin)){
7218: printf("ERROR Empty parameter file name\n");
7219: goto end;
7220: }
7221: i=strlen(pathr);
7222: if(pathr[i-1]=='\n')
7223: pathr[i-1]='\0';
7224: i=strlen(pathr);
7225: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
7226: pathr[i-1]='\0';
7227: }
7228: i=strlen(pathr);
7229: if( i==0 ){
7230: printf("ERROR Empty parameter file name\n");
7231: goto end;
7232: }
7233: for (tok = pathr; tok != NULL; ){
7234: printf("Pathr |%s|\n",pathr);
7235: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
7236: printf("val= |%s| pathr=%s\n",val,pathr);
7237: strcpy (pathtot, val);
7238: if(pathr[0] == '\0') break; /* Dirty */
7239: }
7240: }
7241: else{
7242: strcpy(pathtot,argv[1]);
7243: }
7244: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
7245: /*cygwin_split_path(pathtot,path,optionfile);
7246: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
7247: /* cutv(path,optionfile,pathtot,'\\');*/
7248:
7249: /* Split argv[0], imach program to get pathimach */
7250: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
7251: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7252: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7253: /* strcpy(pathimach,argv[0]); */
7254: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
7255: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
7256: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
7257: #ifdef WIN32
7258: _chdir(path); /* Can be a relative path */
7259: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
7260: #else
7261: chdir(path); /* Can be a relative path */
7262: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
7263: #endif
7264: printf("Current directory %s!\n",pathcd);
7265: strcpy(command,"mkdir ");
7266: strcat(command,optionfilefiname);
7267: if((outcmd=system(command)) != 0){
7268: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
7269: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
7270: /* fclose(ficlog); */
7271: /* exit(1); */
7272: }
7273: /* if((imk=mkdir(optionfilefiname))<0){ */
7274: /* perror("mkdir"); */
7275: /* } */
7276:
7277: /*-------- arguments in the command line --------*/
7278:
7279: /* Main Log file */
7280: strcat(filelog, optionfilefiname);
7281: strcat(filelog,".log"); /* */
7282: if((ficlog=fopen(filelog,"w"))==NULL) {
7283: printf("Problem with logfile %s\n",filelog);
7284: goto end;
7285: }
7286: fprintf(ficlog,"Log filename:%s\n",filelog);
7287: fprintf(ficlog,"Version %s %s",version,fullversion);
7288: fprintf(ficlog,"\nEnter the parameter file name: \n");
7289: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
7290: path=%s \n\
7291: optionfile=%s\n\
7292: optionfilext=%s\n\
7293: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
7294:
7295: syscompilerinfo(1);
7296:
7297: printf("Local time (at start):%s",strstart);
7298: fprintf(ficlog,"Local time (at start): %s",strstart);
7299: fflush(ficlog);
7300: /* (void) gettimeofday(&curr_time,&tzp); */
7301: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
7302:
7303: /* */
7304: strcpy(fileres,"r");
7305: strcat(fileres, optionfilefiname);
7306: strcat(fileresu, optionfilefiname); /* Without r in front */
7307: strcat(fileres,".txt"); /* Other files have txt extension */
7308: strcat(fileresu,".txt"); /* Other files have txt extension */
7309:
7310: /* Main ---------arguments file --------*/
7311:
7312: if((ficpar=fopen(optionfile,"r"))==NULL) {
7313: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7314: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7315: fflush(ficlog);
7316: /* goto end; */
7317: exit(70);
7318: }
7319:
7320:
7321:
7322: strcpy(filereso,"o");
7323: strcat(filereso,fileresu);
7324: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
7325: printf("Problem with Output resultfile: %s\n", filereso);
7326: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
7327: fflush(ficlog);
7328: goto end;
7329: }
7330:
7331: /* Reads comments: lines beginning with '#' */
7332: numlinepar=0;
7333:
7334: /* First parameter line */
7335: while(fgets(line, MAXLINE, ficpar)) {
7336: /* If line starts with a # it is a comment */
7337: if (line[0] == '#') {
7338: numlinepar++;
7339: fputs(line,stdout);
7340: fputs(line,ficparo);
7341: fputs(line,ficlog);
7342: continue;
7343: }else
7344: break;
7345: }
7346: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
7347: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
7348: if (num_filled != 5) {
7349: printf("Should be 5 parameters\n");
7350: }
7351: numlinepar++;
7352: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
7353: }
7354: /* Second parameter line */
7355: while(fgets(line, MAXLINE, ficpar)) {
7356: /* If line starts with a # it is a comment */
7357: if (line[0] == '#') {
7358: numlinepar++;
7359: fputs(line,stdout);
7360: fputs(line,ficparo);
7361: fputs(line,ficlog);
7362: continue;
7363: }else
7364: break;
7365: }
7366: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
7367: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7368: if (num_filled != 8) {
7369: 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");
7370: printf("but line=%s\n",line);
7371: }
7372: 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);
7373: }
7374: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
7375: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
7376: /* Third parameter line */
7377: while(fgets(line, MAXLINE, ficpar)) {
7378: /* If line starts with a # it is a comment */
7379: if (line[0] == '#') {
7380: numlinepar++;
7381: fputs(line,stdout);
7382: fputs(line,ficparo);
7383: fputs(line,ficlog);
7384: continue;
7385: }else
7386: break;
7387: }
7388: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7389: if (num_filled == 0)
7390: model[0]='\0';
7391: else if (num_filled != 1){
7392: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7393: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7394: model[0]='\0';
7395: goto end;
7396: }
7397: else{
7398: if (model[0]=='+'){
7399: for(i=1; i<=strlen(model);i++)
7400: modeltemp[i-1]=model[i];
7401: strcpy(model,modeltemp);
7402: }
7403: }
7404: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
7405: printf("model=1+age+%s\n",model);fflush(stdout);
7406: }
7407: /* 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); */
7408: /* numlinepar=numlinepar+3; /\* In general *\/ */
7409: /* 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); */
7410: 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);
7411: 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);
7412: fflush(ficlog);
7413: /* if(model[0]=='#'|| model[0]== '\0'){ */
7414: if(model[0]=='#'){
7415: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7416: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7417: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7418: if(mle != -1){
7419: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7420: exit(1);
7421: }
7422: }
7423: while((c=getc(ficpar))=='#' && c!= EOF){
7424: ungetc(c,ficpar);
7425: fgets(line, MAXLINE, ficpar);
7426: numlinepar++;
7427: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7428: z[0]=line[1];
7429: }
7430: /* printf("****line [1] = %c \n",line[1]); */
7431: fputs(line, stdout);
7432: //puts(line);
7433: fputs(line,ficparo);
7434: fputs(line,ficlog);
7435: }
7436: ungetc(c,ficpar);
7437:
7438:
7439: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
7440: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7441: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7442: v1+v2*age+v2*v3 makes cptcovn = 3
7443: */
7444: if (strlen(model)>1)
7445: 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*/
7446: else
7447: ncovmodel=2; /* Constant and age */
7448: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7449: npar= nforce*ncovmodel; /* Number of parameters like aij*/
7450: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7451: 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);
7452: 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);
7453: fflush(stdout);
7454: fclose (ficlog);
7455: goto end;
7456: }
7457: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7458: delti=delti3[1][1];
7459: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7460: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7461: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7462: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7463: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7464: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7465: fclose (ficparo);
7466: fclose (ficlog);
7467: goto end;
7468: exit(0);
7469: }
7470: else if(mle==-3) { /* Main Wizard */
7471: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7472: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7473: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7474: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7475: matcov=matrix(1,npar,1,npar);
7476: hess=matrix(1,npar,1,npar);
7477: }
7478: else{
7479: /* Read guessed parameters */
7480: /* Reads comments: lines beginning with '#' */
7481: while((c=getc(ficpar))=='#' && c!= EOF){
7482: ungetc(c,ficpar);
7483: fgets(line, MAXLINE, ficpar);
7484: numlinepar++;
7485: fputs(line,stdout);
7486: fputs(line,ficparo);
7487: fputs(line,ficlog);
7488: }
7489: ungetc(c,ficpar);
7490:
7491: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7492: for(i=1; i <=nlstate; i++){
7493: j=0;
7494: for(jj=1; jj <=nlstate+ndeath; jj++){
7495: if(jj==i) continue;
7496: j++;
7497: fscanf(ficpar,"%1d%1d",&i1,&j1);
7498: if ((i1 != i) || (j1 != jj)){
7499: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7500: It might be a problem of design; if ncovcol and the model are correct\n \
7501: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7502: exit(1);
7503: }
7504: fprintf(ficparo,"%1d%1d",i1,j1);
7505: if(mle==1)
7506: printf("%1d%1d",i,jj);
7507: fprintf(ficlog,"%1d%1d",i,jj);
7508: for(k=1; k<=ncovmodel;k++){
7509: fscanf(ficpar," %lf",¶m[i][j][k]);
7510: if(mle==1){
7511: printf(" %lf",param[i][j][k]);
7512: fprintf(ficlog," %lf",param[i][j][k]);
7513: }
7514: else
7515: fprintf(ficlog," %lf",param[i][j][k]);
7516: fprintf(ficparo," %lf",param[i][j][k]);
7517: }
7518: fscanf(ficpar,"\n");
7519: numlinepar++;
7520: if(mle==1)
7521: printf("\n");
7522: fprintf(ficlog,"\n");
7523: fprintf(ficparo,"\n");
7524: }
7525: }
7526: fflush(ficlog);
7527:
7528: /* Reads scales values */
7529: p=param[1][1];
7530:
7531: /* Reads comments: lines beginning with '#' */
7532: while((c=getc(ficpar))=='#' && c!= EOF){
7533: ungetc(c,ficpar);
7534: fgets(line, MAXLINE, ficpar);
7535: numlinepar++;
7536: fputs(line,stdout);
7537: fputs(line,ficparo);
7538: fputs(line,ficlog);
7539: }
7540: ungetc(c,ficpar);
7541:
7542: for(i=1; i <=nlstate; i++){
7543: for(j=1; j <=nlstate+ndeath-1; j++){
7544: fscanf(ficpar,"%1d%1d",&i1,&j1);
7545: if ( (i1-i) * (j1-j) != 0){
7546: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7547: exit(1);
7548: }
7549: printf("%1d%1d",i,j);
7550: fprintf(ficparo,"%1d%1d",i1,j1);
7551: fprintf(ficlog,"%1d%1d",i1,j1);
7552: for(k=1; k<=ncovmodel;k++){
7553: fscanf(ficpar,"%le",&delti3[i][j][k]);
7554: printf(" %le",delti3[i][j][k]);
7555: fprintf(ficparo," %le",delti3[i][j][k]);
7556: fprintf(ficlog," %le",delti3[i][j][k]);
7557: }
7558: fscanf(ficpar,"\n");
7559: numlinepar++;
7560: printf("\n");
7561: fprintf(ficparo,"\n");
7562: fprintf(ficlog,"\n");
7563: }
7564: }
7565: fflush(ficlog);
7566:
7567: /* Reads covariance matrix */
7568: delti=delti3[1][1];
7569:
7570:
7571: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7572:
7573: /* Reads comments: lines beginning with '#' */
7574: while((c=getc(ficpar))=='#' && c!= EOF){
7575: ungetc(c,ficpar);
7576: fgets(line, MAXLINE, ficpar);
7577: numlinepar++;
7578: fputs(line,stdout);
7579: fputs(line,ficparo);
7580: fputs(line,ficlog);
7581: }
7582: ungetc(c,ficpar);
7583:
7584: matcov=matrix(1,npar,1,npar);
7585: hess=matrix(1,npar,1,npar);
7586: for(i=1; i <=npar; i++)
7587: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7588:
7589: /* Scans npar lines */
7590: for(i=1; i <=npar; i++){
7591: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7592: if(count != 3){
7593: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7594: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7595: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7596: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7597: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7598: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7599: exit(1);
7600: }else
7601: if(mle==1)
7602: printf("%1d%1d%1d",i1,j1,jk);
7603: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7604: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7605: for(j=1; j <=i; j++){
7606: fscanf(ficpar," %le",&matcov[i][j]);
7607: if(mle==1){
7608: printf(" %.5le",matcov[i][j]);
7609: }
7610: fprintf(ficlog," %.5le",matcov[i][j]);
7611: fprintf(ficparo," %.5le",matcov[i][j]);
7612: }
7613: fscanf(ficpar,"\n");
7614: numlinepar++;
7615: if(mle==1)
7616: printf("\n");
7617: fprintf(ficlog,"\n");
7618: fprintf(ficparo,"\n");
7619: }
7620: /* End of read covariance matrix npar lines */
7621: for(i=1; i <=npar; i++)
7622: for(j=i+1;j<=npar;j++)
7623: matcov[i][j]=matcov[j][i];
7624:
7625: if(mle==1)
7626: printf("\n");
7627: fprintf(ficlog,"\n");
7628:
7629: fflush(ficlog);
7630:
7631: /*-------- Rewriting parameter file ----------*/
7632: strcpy(rfileres,"r"); /* "Rparameterfile */
7633: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7634: strcat(rfileres,"."); /* */
7635: strcat(rfileres,optionfilext); /* Other files have txt extension */
7636: if((ficres =fopen(rfileres,"w"))==NULL) {
7637: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7638: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7639: }
7640: fprintf(ficres,"#%s\n",version);
7641: } /* End of mle != -3 */
7642:
7643: /* Main data
7644: */
7645: n= lastobs;
7646: num=lvector(1,n);
7647: moisnais=vector(1,n);
7648: annais=vector(1,n);
7649: moisdc=vector(1,n);
7650: andc=vector(1,n);
7651: agedc=vector(1,n);
7652: cod=ivector(1,n);
7653: weight=vector(1,n);
7654: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7655: mint=matrix(1,maxwav,1,n);
7656: anint=matrix(1,maxwav,1,n);
7657: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7658: tab=ivector(1,NCOVMAX);
7659: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7660: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7661:
7662: /* Reads data from file datafile */
7663: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7664: goto end;
7665:
7666: /* Calculation of the number of parameters from char model */
7667: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7668: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7669: k=3 V4 Tvar[k=3]= 4 (from V4)
7670: k=2 V1 Tvar[k=2]= 1 (from V1)
7671: k=1 Tvar[1]=2 (from V2)
7672: */
7673: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7674: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7675: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7676: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7677: */
7678: /* For model-covariate k tells which data-covariate to use but
7679: because this model-covariate is a construction we invent a new column
7680: ncovcol + k1
7681: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7682: Tvar[3=V1*V4]=4+1 etc */
7683: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7684: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7685: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7686: */
7687: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7688: 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
7689: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7690: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7691: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7692: 4 covariates (3 plus signs)
7693: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7694: */
7695:
7696: /* Main decodemodel */
7697:
7698:
7699: if(decodemodel(model, lastobs) == 1)
7700: goto end;
7701:
7702: if((double)(lastobs-imx)/(double)imx > 1.10){
7703: nbwarn++;
7704: 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);
7705: 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);
7706: }
7707: /* if(mle==1){*/
7708: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7709: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7710: }
7711:
7712: /*-calculation of age at interview from date of interview and age at death -*/
7713: agev=matrix(1,maxwav,1,imx);
7714:
7715: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7716: goto end;
7717:
7718:
7719: agegomp=(int)agemin;
7720: free_vector(moisnais,1,n);
7721: free_vector(annais,1,n);
7722: /* free_matrix(mint,1,maxwav,1,n);
7723: free_matrix(anint,1,maxwav,1,n);*/
7724: /* free_vector(moisdc,1,n); */
7725: /* free_vector(andc,1,n); */
7726: /* */
7727:
7728: wav=ivector(1,imx);
7729: /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
7730: /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
7731: /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
7732: dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
7733: bh=imatrix(1,lastpass-firstpass+2,1,imx);
7734: mw=imatrix(1,lastpass-firstpass+2,1,imx);
7735:
7736: /* Concatenates waves */
7737: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
7738: Death is a valid wave (if date is known).
7739: mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
7740: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
7741: and mw[mi+1][i]. dh depends on stepm.
7742: */
7743:
7744: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7745: /* */
7746:
7747: free_vector(moisdc,1,n);
7748: free_vector(andc,1,n);
7749:
7750: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7751:
7752: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7753: ncodemax[1]=1;
7754: Ndum =ivector(-1,NCOVMAX);
7755: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7756: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7757: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
7758: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7759: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
7760:
7761: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7762: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7763: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7764: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
7765: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
7766: * (currently 0 or 1) in the data.
7767: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
7768: * corresponding modality (h,j).
7769: */
7770:
7771: h=0;
7772:
7773:
7774: /*if (cptcovn > 0) */
7775:
7776:
7777: m=pow(2,cptcoveff);
7778:
7779: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7780: * For k=4 covariates, h goes from 1 to m=2**k
7781: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
7782: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7783: * h\k 1 2 3 4
7784: *______________________________
7785: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7786: * 2 2 1 1 1
7787: * 3 i=2 1 2 1 1
7788: * 4 2 2 1 1
7789: * 5 i=3 1 i=2 1 2 1
7790: * 6 2 1 2 1
7791: * 7 i=4 1 2 2 1
7792: * 8 2 2 2 1
7793: * 9 i=5 1 i=3 1 i=2 1 2
7794: * 10 2 1 1 2
7795: * 11 i=6 1 2 1 2
7796: * 12 2 2 1 2
7797: * 13 i=7 1 i=4 1 2 2
7798: * 14 2 1 2 2
7799: * 15 i=8 1 2 2 2
7800: * 16 2 2 2 2
7801: */
7802: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
7803: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
7804: * and the value of each covariate?
7805: * V1=1, V2=1, V3=2, V4=1 ?
7806: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
7807: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
7808: * In order to get the real value in the data, we use nbcode
7809: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
7810: * We are keeping this crazy system in order to be able (in the future?)
7811: * to have more than 2 values (0 or 1) for a covariate.
7812: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7813: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
7814: * bbbbbbbb
7815: * 76543210
7816: * h-1 00000101 (6-1=5)
7817: *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
7818: * &
7819: * 1 00000001 (1)
7820: * 00000001 = 1 & ((h-1) >> (k-1))
7821: * +1= 00000010 =2
7822: *
7823: * h=14, k=3 => h'=h-1=13, k'=k-1=2
7824: * h' 1101 =2^3+2^2+0x2^1+2^0
7825: * >>k' 11
7826: * & 00000001
7827: * = 00000001
7828: * +1 = 00000010=2 = codtabm(14,3)
7829: * Reverse h=6 and m=16?
7830: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
7831: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
7832: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
7833: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
7834: * V3=decodtabm(14,3,2**4)=2
7835: * h'=13 1101 =2^3+2^2+0x2^1+2^0
7836: *(h-1) >> (j-1) 0011 =13 >> 2
7837: * &1 000000001
7838: * = 000000001
7839: * +1= 000000010 =2
7840: * 2211
7841: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
7842: * V3=2
7843: */
7844:
7845: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7846: /* /\* printf("h=%2d ", h); *\/ */
7847: /* /\* for(k=1; k <=10; k++){ *\/ */
7848: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7849: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7850: /* /\* } *\/ */
7851: /* /\* printf("\n"); *\/ */
7852: /* } */
7853: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7854: /* 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 *\/ */
7855: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7856: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7857: /* h++; */
7858: /* if (h>m) */
7859: /* h=1; */
7860: /* codtab[h][k]=j; */
7861: /* /\* codtab[12][3]=1; *\/ */
7862: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7863: /* /\* 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]]); *\/ */
7864: /* } */
7865: /* } */
7866: /* } */
7867: /* } */
7868: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7869: codtab[1][2]=1;codtab[2][2]=2; */
7870: /* for(i=1; i <=m ;i++){ */
7871: /* for(k=1; k <=cptcovn; k++){ */
7872: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7873: /* } */
7874: /* printf("\n"); */
7875: /* } */
7876: /* scanf("%d",i);*/
7877:
7878: free_ivector(Ndum,-1,NCOVMAX);
7879:
7880:
7881:
7882: /* Initialisation of ----------- gnuplot -------------*/
7883: strcpy(optionfilegnuplot,optionfilefiname);
7884: if(mle==-3)
7885: strcat(optionfilegnuplot,"-MORT_");
7886: strcat(optionfilegnuplot,".gp");
7887:
7888: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7889: printf("Problem with file %s",optionfilegnuplot);
7890: }
7891: else{
7892: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7893: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7894: //fprintf(ficgp,"set missing 'NaNq'\n");
7895: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7896: }
7897: /* fclose(ficgp);*/
7898:
7899:
7900: /* Initialisation of --------- index.htm --------*/
7901:
7902: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7903: if(mle==-3)
7904: strcat(optionfilehtm,"-MORT_");
7905: strcat(optionfilehtm,".htm");
7906: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7907: printf("Problem with %s \n",optionfilehtm);
7908: exit(0);
7909: }
7910:
7911: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7912: strcat(optionfilehtmcov,"-cov.htm");
7913: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7914: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7915: }
7916: else{
7917: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7918: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7919: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7920: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7921: }
7922:
7923: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \
7924: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7925: <font size=\"2\">IMaCh-%s <br> %s</font> \
7926: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7927: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7928: \n\
7929: <hr size=\"2\" color=\"#EC5E5E\">\
7930: <ul><li><h4>Parameter files</h4>\n\
7931: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7932: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7933: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7934: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7935: - Date and time at start: %s</ul>\n",\
7936: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7937: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7938: fileres,fileres,\
7939: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7940: fflush(fichtm);
7941:
7942: strcpy(pathr,path);
7943: strcat(pathr,optionfilefiname);
7944: #ifdef WIN32
7945: _chdir(optionfilefiname); /* Move to directory named optionfile */
7946: #else
7947: chdir(optionfilefiname); /* Move to directory named optionfile */
7948: #endif
7949:
7950:
7951: /* Calculates basic frequencies. Computes observed prevalence at single age
7952: and prints on file fileres'p'. */
7953: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
7954: firstpass, lastpass, stepm, weightopt, model);
7955:
7956: fprintf(fichtm,"\n");
7957: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7958: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7959: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7960: imx,agemin,agemax,jmin,jmax,jmean);
7961: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7962: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7963: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7964: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7965: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7966:
7967:
7968: /* For Powell, parameters are in a vector p[] starting at p[1]
7969: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7970: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7971:
7972: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7973: /* For mortality only */
7974: if (mle==-3){
7975: ximort=matrix(1,NDIM,1,NDIM);
7976: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7977: cens=ivector(1,n);
7978: ageexmed=vector(1,n);
7979: agecens=vector(1,n);
7980: dcwave=ivector(1,n);
7981:
7982: for (i=1; i<=imx; i++){
7983: dcwave[i]=-1;
7984: for (m=firstpass; m<=lastpass; m++)
7985: if (s[m][i]>nlstate) {
7986: dcwave[i]=m;
7987: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7988: break;
7989: }
7990: }
7991:
7992: for (i=1; i<=imx; i++) {
7993: if (wav[i]>0){
7994: ageexmed[i]=agev[mw[1][i]][i];
7995: j=wav[i];
7996: agecens[i]=1.;
7997:
7998: if (ageexmed[i]> 1 && wav[i] > 0){
7999: agecens[i]=agev[mw[j][i]][i];
8000: cens[i]= 1;
8001: }else if (ageexmed[i]< 1)
8002: cens[i]= -1;
8003: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
8004: cens[i]=0 ;
8005: }
8006: else cens[i]=-1;
8007: }
8008:
8009: for (i=1;i<=NDIM;i++) {
8010: for (j=1;j<=NDIM;j++)
8011: ximort[i][j]=(i == j ? 1.0 : 0.0);
8012: }
8013:
8014: /*p[1]=0.0268; p[NDIM]=0.083;*/
8015: /*printf("%lf %lf", p[1], p[2]);*/
8016:
8017:
8018: #ifdef GSL
8019: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
8020: #else
8021: printf("Powell\n"); fprintf(ficlog,"Powell\n");
8022: #endif
8023: strcpy(filerespow,"POW-MORT_");
8024: strcat(filerespow,fileresu);
8025: if((ficrespow=fopen(filerespow,"w"))==NULL) {
8026: printf("Problem with resultfile: %s\n", filerespow);
8027: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
8028: }
8029: #ifdef GSL
8030: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
8031: #else
8032: fprintf(ficrespow,"# Powell\n# iter -2*LL");
8033: #endif
8034: /* for (i=1;i<=nlstate;i++)
8035: for(j=1;j<=nlstate+ndeath;j++)
8036: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
8037: */
8038: fprintf(ficrespow,"\n");
8039: #ifdef GSL
8040: /* gsl starts here */
8041: T = gsl_multimin_fminimizer_nmsimplex;
8042: gsl_multimin_fminimizer *sfm = NULL;
8043: gsl_vector *ss, *x;
8044: gsl_multimin_function minex_func;
8045:
8046: /* Initial vertex size vector */
8047: ss = gsl_vector_alloc (NDIM);
8048:
8049: if (ss == NULL){
8050: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
8051: }
8052: /* Set all step sizes to 1 */
8053: gsl_vector_set_all (ss, 0.001);
8054:
8055: /* Starting point */
8056:
8057: x = gsl_vector_alloc (NDIM);
8058:
8059: if (x == NULL){
8060: gsl_vector_free(ss);
8061: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
8062: }
8063:
8064: /* Initialize method and iterate */
8065: /* p[1]=0.0268; p[NDIM]=0.083; */
8066: /* gsl_vector_set(x, 0, 0.0268); */
8067: /* gsl_vector_set(x, 1, 0.083); */
8068: gsl_vector_set(x, 0, p[1]);
8069: gsl_vector_set(x, 1, p[2]);
8070:
8071: minex_func.f = &gompertz_f;
8072: minex_func.n = NDIM;
8073: minex_func.params = (void *)&p; /* ??? */
8074:
8075: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
8076: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
8077:
8078: printf("Iterations beginning .....\n\n");
8079: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
8080:
8081: iteri=0;
8082: while (rval == GSL_CONTINUE){
8083: iteri++;
8084: status = gsl_multimin_fminimizer_iterate(sfm);
8085:
8086: if (status) printf("error: %s\n", gsl_strerror (status));
8087: fflush(0);
8088:
8089: if (status)
8090: break;
8091:
8092: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
8093: ssval = gsl_multimin_fminimizer_size (sfm);
8094:
8095: if (rval == GSL_SUCCESS)
8096: printf ("converged to a local maximum at\n");
8097:
8098: printf("%5d ", iteri);
8099: for (it = 0; it < NDIM; it++){
8100: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
8101: }
8102: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
8103: }
8104:
8105: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
8106:
8107: gsl_vector_free(x); /* initial values */
8108: gsl_vector_free(ss); /* inital step size */
8109: for (it=0; it<NDIM; it++){
8110: p[it+1]=gsl_vector_get(sfm->x,it);
8111: fprintf(ficrespow," %.12lf", p[it]);
8112: }
8113: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
8114: #endif
8115: #ifdef POWELL
8116: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
8117: #endif
8118: fclose(ficrespow);
8119:
8120: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
8121:
8122: for(i=1; i <=NDIM; i++)
8123: for(j=i+1;j<=NDIM;j++)
8124: matcov[i][j]=matcov[j][i];
8125:
8126: printf("\nCovariance matrix\n ");
8127: fprintf(ficlog,"\nCovariance matrix\n ");
8128: for(i=1; i <=NDIM; i++) {
8129: for(j=1;j<=NDIM;j++){
8130: printf("%f ",matcov[i][j]);
8131: fprintf(ficlog,"%f ",matcov[i][j]);
8132: }
8133: printf("\n "); fprintf(ficlog,"\n ");
8134: }
8135:
8136: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
8137: for (i=1;i<=NDIM;i++) {
8138: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
8139: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
8140: }
8141: lsurv=vector(1,AGESUP);
8142: lpop=vector(1,AGESUP);
8143: tpop=vector(1,AGESUP);
8144: lsurv[agegomp]=100000;
8145:
8146: for (k=agegomp;k<=AGESUP;k++) {
8147: agemortsup=k;
8148: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
8149: }
8150:
8151: for (k=agegomp;k<agemortsup;k++)
8152: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
8153:
8154: for (k=agegomp;k<agemortsup;k++){
8155: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
8156: sumlpop=sumlpop+lpop[k];
8157: }
8158:
8159: tpop[agegomp]=sumlpop;
8160: for (k=agegomp;k<(agemortsup-3);k++){
8161: /* tpop[k+1]=2;*/
8162: tpop[k+1]=tpop[k]-lpop[k];
8163: }
8164:
8165:
8166: printf("\nAge lx qx dx Lx Tx e(x)\n");
8167: for (k=agegomp;k<(agemortsup-2);k++)
8168: 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]);
8169:
8170:
8171: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8172: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
8173: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8174: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8175: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8176: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8177: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8178: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8179: }else
8180: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8181: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
8182: stepm, weightopt,\
8183: model,imx,p,matcov,agemortsup);
8184:
8185: free_vector(lsurv,1,AGESUP);
8186: free_vector(lpop,1,AGESUP);
8187: free_vector(tpop,1,AGESUP);
8188: #ifdef GSL
8189: free_ivector(cens,1,n);
8190: free_vector(agecens,1,n);
8191: free_ivector(dcwave,1,n);
8192: free_matrix(ximort,1,NDIM,1,NDIM);
8193: #endif
8194: } /* Endof if mle==-3 mortality only */
8195: /* Standard */
8196: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
8197: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8198: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8199: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8200: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8201: for (k=1; k<=npar;k++)
8202: printf(" %d %8.5f",k,p[k]);
8203: printf("\n");
8204: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
8205: /* mlikeli uses func not funcone */
8206: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
8207: }
8208: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
8209: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8210: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8211: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8212: }
8213: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
8214: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8215: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8216: for (k=1; k<=npar;k++)
8217: printf(" %d %8.5f",k,p[k]);
8218: printf("\n");
8219:
8220: /*--------- results files --------------*/
8221: 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);
8222:
8223:
8224: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8225: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8226: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8227: for(i=1,jk=1; i <=nlstate; i++){
8228: for(k=1; k <=(nlstate+ndeath); k++){
8229: if (k != i) {
8230: printf("%d%d ",i,k);
8231: fprintf(ficlog,"%d%d ",i,k);
8232: fprintf(ficres,"%1d%1d ",i,k);
8233: for(j=1; j <=ncovmodel; j++){
8234: printf("%12.7f ",p[jk]);
8235: fprintf(ficlog,"%12.7f ",p[jk]);
8236: fprintf(ficres,"%12.7f ",p[jk]);
8237: jk++;
8238: }
8239: printf("\n");
8240: fprintf(ficlog,"\n");
8241: fprintf(ficres,"\n");
8242: }
8243: }
8244: }
8245: if(mle != 0){
8246: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
8247: ftolhess=ftol; /* Usually correct */
8248: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
8249: 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");
8250: 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");
8251: for(i=1,jk=1; i <=nlstate; i++){
8252: for(k=1; k <=(nlstate+ndeath); k++){
8253: if (k != i) {
8254: printf("%d%d ",i,k);
8255: fprintf(ficlog,"%d%d ",i,k);
8256: for(j=1; j <=ncovmodel; j++){
8257: 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]));
8258: 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]));
8259: jk++;
8260: }
8261: printf("\n");
8262: fprintf(ficlog,"\n");
8263: }
8264: }
8265: }
8266: } /* end of hesscov and Wald tests */
8267:
8268: /* */
8269: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
8270: printf("# Scales (for hessian or gradient estimation)\n");
8271: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
8272: for(i=1,jk=1; i <=nlstate; i++){
8273: for(j=1; j <=nlstate+ndeath; j++){
8274: if (j!=i) {
8275: fprintf(ficres,"%1d%1d",i,j);
8276: printf("%1d%1d",i,j);
8277: fprintf(ficlog,"%1d%1d",i,j);
8278: for(k=1; k<=ncovmodel;k++){
8279: printf(" %.5e",delti[jk]);
8280: fprintf(ficlog," %.5e",delti[jk]);
8281: fprintf(ficres," %.5e",delti[jk]);
8282: jk++;
8283: }
8284: printf("\n");
8285: fprintf(ficlog,"\n");
8286: fprintf(ficres,"\n");
8287: }
8288: }
8289: }
8290:
8291: 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");
8292: if(mle >= 1) /* To big for the screen */
8293: 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");
8294: 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");
8295: /* # 121 Var(a12)\n\ */
8296: /* # 122 Cov(b12,a12) Var(b12)\n\ */
8297: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
8298: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
8299: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
8300: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
8301: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
8302: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
8303:
8304:
8305: /* Just to have a covariance matrix which will be more understandable
8306: even is we still don't want to manage dictionary of variables
8307: */
8308: for(itimes=1;itimes<=2;itimes++){
8309: jj=0;
8310: for(i=1; i <=nlstate; i++){
8311: for(j=1; j <=nlstate+ndeath; j++){
8312: if(j==i) continue;
8313: for(k=1; k<=ncovmodel;k++){
8314: jj++;
8315: ca[0]= k+'a'-1;ca[1]='\0';
8316: if(itimes==1){
8317: if(mle>=1)
8318: printf("#%1d%1d%d",i,j,k);
8319: fprintf(ficlog,"#%1d%1d%d",i,j,k);
8320: fprintf(ficres,"#%1d%1d%d",i,j,k);
8321: }else{
8322: if(mle>=1)
8323: printf("%1d%1d%d",i,j,k);
8324: fprintf(ficlog,"%1d%1d%d",i,j,k);
8325: fprintf(ficres,"%1d%1d%d",i,j,k);
8326: }
8327: ll=0;
8328: for(li=1;li <=nlstate; li++){
8329: for(lj=1;lj <=nlstate+ndeath; lj++){
8330: if(lj==li) continue;
8331: for(lk=1;lk<=ncovmodel;lk++){
8332: ll++;
8333: if(ll<=jj){
8334: cb[0]= lk +'a'-1;cb[1]='\0';
8335: if(ll<jj){
8336: if(itimes==1){
8337: if(mle>=1)
8338: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8339: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8340: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8341: }else{
8342: if(mle>=1)
8343: printf(" %.5e",matcov[jj][ll]);
8344: fprintf(ficlog," %.5e",matcov[jj][ll]);
8345: fprintf(ficres," %.5e",matcov[jj][ll]);
8346: }
8347: }else{
8348: if(itimes==1){
8349: if(mle>=1)
8350: printf(" Var(%s%1d%1d)",ca,i,j);
8351: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
8352: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
8353: }else{
8354: if(mle>=1)
8355: printf(" %.7e",matcov[jj][ll]);
8356: fprintf(ficlog," %.7e",matcov[jj][ll]);
8357: fprintf(ficres," %.7e",matcov[jj][ll]);
8358: }
8359: }
8360: }
8361: } /* end lk */
8362: } /* end lj */
8363: } /* end li */
8364: if(mle>=1)
8365: printf("\n");
8366: fprintf(ficlog,"\n");
8367: fprintf(ficres,"\n");
8368: numlinepar++;
8369: } /* end k*/
8370: } /*end j */
8371: } /* end i */
8372: } /* end itimes */
8373:
8374: fflush(ficlog);
8375: fflush(ficres);
8376: while(fgets(line, MAXLINE, ficpar)) {
8377: /* If line starts with a # it is a comment */
8378: if (line[0] == '#') {
8379: numlinepar++;
8380: fputs(line,stdout);
8381: fputs(line,ficparo);
8382: fputs(line,ficlog);
8383: continue;
8384: }else
8385: break;
8386: }
8387:
8388: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
8389: /* ungetc(c,ficpar); */
8390: /* fgets(line, MAXLINE, ficpar); */
8391: /* fputs(line,stdout); */
8392: /* fputs(line,ficparo); */
8393: /* } */
8394: /* ungetc(c,ficpar); */
8395:
8396: estepm=0;
8397: 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){
8398:
8399: if (num_filled != 6) {
8400: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
8401: printf("but line=%s\n",line);
8402: goto end;
8403: }
8404: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
8405: }
8406: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8407: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8408:
8409: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
8410: if (estepm==0 || estepm < stepm) estepm=stepm;
8411: if (fage <= 2) {
8412: bage = ageminpar;
8413: fage = agemaxpar;
8414: }
8415:
8416: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
8417: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8418: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8419:
8420: /* Other stuffs, more or less useful */
8421: while((c=getc(ficpar))=='#' && c!= EOF){
8422: ungetc(c,ficpar);
8423: fgets(line, MAXLINE, ficpar);
8424: fputs(line,stdout);
8425: fputs(line,ficparo);
8426: }
8427: ungetc(c,ficpar);
8428:
8429: 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);
8430: 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);
8431: 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);
8432: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8433: 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);
8434:
8435: while((c=getc(ficpar))=='#' && c!= EOF){
8436: ungetc(c,ficpar);
8437: fgets(line, MAXLINE, ficpar);
8438: fputs(line,stdout);
8439: fputs(line,ficparo);
8440: }
8441: ungetc(c,ficpar);
8442:
8443:
8444: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8445: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8446:
8447: fscanf(ficpar,"pop_based=%d\n",&popbased);
8448: fprintf(ficlog,"pop_based=%d\n",popbased);
8449: fprintf(ficparo,"pop_based=%d\n",popbased);
8450: fprintf(ficres,"pop_based=%d\n",popbased);
8451:
8452: while((c=getc(ficpar))=='#' && c!= EOF){
8453: ungetc(c,ficpar);
8454: fgets(line, MAXLINE, ficpar);
8455: fputs(line,stdout);
8456: fputs(line,ficparo);
8457: }
8458: ungetc(c,ficpar);
8459:
8460: 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);
8461: 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);
8462: 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);
8463: 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);
8464: 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);
8465: /* day and month of proj2 are not used but only year anproj2.*/
8466:
8467:
8468:
8469: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8470: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
8471:
8472: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8473: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8474: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8475: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8476: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8477: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8478: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8479: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8480: }else
8481: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
8482:
8483: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
8484: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
8485: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
8486:
8487: /*------------ free_vector -------------*/
8488: /* chdir(path); */
8489:
8490: /* free_ivector(wav,1,imx); */ /* Moved after last prevalence call */
8491: /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
8492: /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
8493: /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx); */
8494: free_lvector(num,1,n);
8495: free_vector(agedc,1,n);
8496: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8497: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8498: fclose(ficparo);
8499: fclose(ficres);
8500:
8501:
8502: /* Other results (useful)*/
8503:
8504:
8505: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
8506: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8507: prlim=matrix(1,nlstate,1,nlstate);
8508: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
8509: fclose(ficrespl);
8510:
8511: #ifdef FREEEXIT2
8512: #include "freeexit2.h"
8513: #endif
8514:
8515: /*------------- h Pij x at various ages ------------*/
8516: /*#include "hpijx.h"*/
8517: hPijx(p, bage, fage);
8518: fclose(ficrespij);
8519:
8520: /*-------------- Variance of one-step probabilities---*/
8521: k=1;
8522: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8523:
8524:
8525: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8526: for(i=1;i<=AGESUP;i++)
8527: for(j=1;j<=NCOVMAX;j++)
8528: for(k=1;k<=NCOVMAX;k++)
8529: probs[i][j][k]=0.;
8530:
8531: /*---------- Forecasting ------------------*/
8532: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8533: if(prevfcast==1){
8534: /* if(stepm ==1){*/
8535: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
8536: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8537: /* } */
8538: /* else{ */
8539: /* erreur=108; */
8540: /* 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); */
8541: /* 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); */
8542: /* } */
8543: }
8544:
8545: /* ------ Other prevalence ratios------------ */
8546:
8547: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8548:
8549: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8550: /* 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",\
8551: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8552: */
8553: free_ivector(wav,1,imx);
8554: free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
8555: free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
8556: free_imatrix(mw,1,lastpass-firstpass+2,1,imx);
8557:
8558:
8559: if (mobilav!=0) {
8560: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8561: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8562: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8563: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8564: }
8565: }
8566:
8567:
8568: /*---------- Health expectancies, no variances ------------*/
8569:
8570: strcpy(filerese,"E_");
8571: strcat(filerese,fileresu);
8572: if((ficreseij=fopen(filerese,"w"))==NULL) {
8573: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8574: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8575: }
8576: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8577: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
8578: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8579: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8580:
8581: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8582: fprintf(ficreseij,"\n#****** ");
8583: for(j=1;j<=cptcoveff;j++) {
8584: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8585: }
8586: fprintf(ficreseij,"******\n");
8587:
8588: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8589: oldm=oldms;savm=savms;
8590: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8591:
8592: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8593: /*}*/
8594: }
8595: fclose(ficreseij);
8596: printf("done evsij\n");fflush(stdout);
8597: fprintf(ficlog,"done evsij\n");fflush(ficlog);
8598:
8599: /*---------- Health expectancies and variances ------------*/
8600:
8601:
8602: strcpy(filerest,"T_");
8603: strcat(filerest,fileresu);
8604: if((ficrest=fopen(filerest,"w"))==NULL) {
8605: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8606: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8607: }
8608: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8609: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
8610:
8611:
8612: strcpy(fileresstde,"STDE_");
8613: strcat(fileresstde,fileresu);
8614: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8615: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8616: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8617: }
8618: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8619: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8620:
8621: strcpy(filerescve,"CVE_");
8622: strcat(filerescve,fileresu);
8623: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8624: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8625: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8626: }
8627: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8628: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8629:
8630: strcpy(fileresv,"V_");
8631: strcat(fileresv,fileresu);
8632: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8633: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8634: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8635: }
8636: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8637: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
8638:
8639: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8640: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8641:
8642: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8643: fprintf(ficrest,"\n#****** ");
8644: for(j=1;j<=cptcoveff;j++)
8645: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8646: fprintf(ficrest,"******\n");
8647:
8648: fprintf(ficresstdeij,"\n#****** ");
8649: fprintf(ficrescveij,"\n#****** ");
8650: for(j=1;j<=cptcoveff;j++) {
8651: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8652: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8653: }
8654: fprintf(ficresstdeij,"******\n");
8655: fprintf(ficrescveij,"******\n");
8656:
8657: fprintf(ficresvij,"\n#****** ");
8658: for(j=1;j<=cptcoveff;j++)
8659: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8660: fprintf(ficresvij,"******\n");
8661:
8662: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8663: oldm=oldms;savm=savms;
8664: printf(" cvevsij %d, ",k);
8665: fprintf(ficlog, " cvevsij %d, ",k);
8666: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8667: printf(" end cvevsij \n ");
8668: fprintf(ficlog, " end cvevsij \n ");
8669:
8670: /*
8671: */
8672: /* goto endfree; */
8673:
8674: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8675: pstamp(ficrest);
8676:
8677:
8678: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8679: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8680: cptcod= 0; /* To be deleted */
8681: printf("varevsij %d \n",vpopbased);
8682: fprintf(ficlog, "varevsij %d \n",vpopbased);
8683: 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 */
8684: 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 ");
8685: if(vpopbased==1)
8686: 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);
8687: else
8688: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8689: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8690: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8691: fprintf(ficrest,"\n");
8692: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8693: epj=vector(1,nlstate+1);
8694: printf("Computing age specific period (stable) prevalences in each health state \n");
8695: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8696: for(age=bage; age <=fage ;age++){
8697: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
8698: if (vpopbased==1) {
8699: if(mobilav ==0){
8700: for(i=1; i<=nlstate;i++)
8701: prlim[i][i]=probs[(int)age][i][k];
8702: }else{ /* mobilav */
8703: for(i=1; i<=nlstate;i++)
8704: prlim[i][i]=mobaverage[(int)age][i][k];
8705: }
8706: }
8707:
8708: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8709: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8710: /* printf(" age %4.0f ",age); */
8711: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8712: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8713: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8714: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8715: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8716: }
8717: epj[nlstate+1] +=epj[j];
8718: }
8719: /* printf(" age %4.0f \n",age); */
8720:
8721: for(i=1, vepp=0.;i <=nlstate;i++)
8722: for(j=1;j <=nlstate;j++)
8723: vepp += vareij[i][j][(int)age];
8724: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8725: for(j=1;j <=nlstate;j++){
8726: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8727: }
8728: fprintf(ficrest,"\n");
8729: }
8730: } /* End vpopbased */
8731: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8732: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8733: free_vector(epj,1,nlstate+1);
8734: printf("done \n");fflush(stdout);
8735: fprintf(ficlog,"done\n");fflush(ficlog);
8736:
8737: /*}*/
8738: } /* End k */
8739: free_vector(weight,1,n);
8740: free_imatrix(Tvard,1,NCOVMAX,1,2);
8741: free_imatrix(s,1,maxwav+1,1,n);
8742: free_matrix(anint,1,maxwav,1,n);
8743: free_matrix(mint,1,maxwav,1,n);
8744: free_ivector(cod,1,n);
8745: free_ivector(tab,1,NCOVMAX);
8746: fclose(ficresstdeij);
8747: fclose(ficrescveij);
8748: fclose(ficresvij);
8749: fclose(ficrest);
8750: printf("done Health expectancies\n");fflush(stdout);
8751: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
8752: fclose(ficpar);
8753:
8754: /*------- Variance of period (stable) prevalence------*/
8755:
8756: strcpy(fileresvpl,"VPL_");
8757: strcat(fileresvpl,fileresu);
8758: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8759: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8760: exit(0);
8761: }
8762: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8763: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
8764:
8765: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8766: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8767:
8768: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8769: fprintf(ficresvpl,"\n#****** ");
8770: for(j=1;j<=cptcoveff;j++)
8771: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8772: fprintf(ficresvpl,"******\n");
8773:
8774: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8775: oldm=oldms;savm=savms;
8776: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
8777: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8778: /*}*/
8779: }
8780:
8781: fclose(ficresvpl);
8782: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8783: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
8784:
8785: /*---------- End : free ----------------*/
8786: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8787: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8788: } /* mle==-3 arrives here for freeing */
8789: /* endfree:*/
8790: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8791: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8792: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8793: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8794: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8795: free_matrix(covar,0,NCOVMAX,1,n);
8796: free_matrix(matcov,1,npar,1,npar);
8797: free_matrix(hess,1,npar,1,npar);
8798: /*free_vector(delti,1,npar);*/
8799: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8800: free_matrix(agev,1,maxwav,1,imx);
8801: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8802:
8803: free_ivector(ncodemax,1,NCOVMAX);
8804: free_ivector(ncodemaxwundef,1,NCOVMAX);
8805: free_ivector(Tvar,1,NCOVMAX);
8806: free_ivector(Tprod,1,NCOVMAX);
8807: free_ivector(Tvaraff,1,NCOVMAX);
8808: free_ivector(Tage,1,NCOVMAX);
8809:
8810: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8811: /* free_imatrix(codtab,1,100,1,10); */
8812: fflush(fichtm);
8813: fflush(ficgp);
8814:
8815:
8816: if((nberr >0) || (nbwarn>0)){
8817: printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
8818: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
8819: }else{
8820: printf("End of Imach\n");
8821: fprintf(ficlog,"End of Imach\n");
8822: }
8823: printf("See log file on %s\n",filelog);
8824: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8825: /*(void) gettimeofday(&end_time,&tzp);*/
8826: rend_time = time(NULL);
8827: end_time = *localtime(&rend_time);
8828: /* tml = *localtime(&end_time.tm_sec); */
8829: strcpy(strtend,asctime(&end_time));
8830: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8831: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8832: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8833:
8834: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8835: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8836: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8837: /* printf("Total time was %d uSec.\n", total_usecs);*/
8838: /* if(fileappend(fichtm,optionfilehtm)){ */
8839: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8840: fclose(fichtm);
8841: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8842: fclose(fichtmcov);
8843: fclose(ficgp);
8844: fclose(ficlog);
8845: /*------ End -----------*/
8846:
8847:
8848: printf("Before Current directory %s!\n",pathcd);
8849: #ifdef WIN32
8850: if (_chdir(pathcd) != 0)
8851: printf("Can't move to directory %s!\n",path);
8852: if(_getcwd(pathcd,MAXLINE) > 0)
8853: #else
8854: if(chdir(pathcd) != 0)
8855: printf("Can't move to directory %s!\n", path);
8856: if (getcwd(pathcd, MAXLINE) > 0)
8857: #endif
8858: printf("Current directory %s!\n",pathcd);
8859: /*strcat(plotcmd,CHARSEPARATOR);*/
8860: sprintf(plotcmd,"gnuplot");
8861: #ifdef _WIN32
8862: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8863: #endif
8864: if(!stat(plotcmd,&info)){
8865: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8866: if(!stat(getenv("GNUPLOTBIN"),&info)){
8867: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8868: }else
8869: strcpy(pplotcmd,plotcmd);
8870: #ifdef __unix
8871: strcpy(plotcmd,GNUPLOTPROGRAM);
8872: if(!stat(plotcmd,&info)){
8873: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8874: }else
8875: strcpy(pplotcmd,plotcmd);
8876: #endif
8877: }else
8878: strcpy(pplotcmd,plotcmd);
8879:
8880: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8881: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8882:
8883: if((outcmd=system(plotcmd)) != 0){
8884: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8885: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8886: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8887: if((outcmd=system(plotcmd)) != 0)
8888: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8889: }
8890: printf(" Successful, please wait...");
8891: while (z[0] != 'q') {
8892: /* chdir(path); */
8893: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8894: scanf("%s",z);
8895: /* if (z[0] == 'c') system("./imach"); */
8896: if (z[0] == 'e') {
8897: #ifdef __APPLE__
8898: sprintf(pplotcmd, "open %s", optionfilehtm);
8899: #elif __linux
8900: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8901: #else
8902: sprintf(pplotcmd, "%s", optionfilehtm);
8903: #endif
8904: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8905: system(pplotcmd);
8906: }
8907: else if (z[0] == 'g') system(plotcmd);
8908: else if (z[0] == 'q') exit(0);
8909: }
8910: end:
8911: while (z[0] != 'q') {
8912: printf("\nType q for exiting: "); fflush(stdout);
8913: scanf("%s",z);
8914: }
8915: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>