File:
[Local Repository] /
imach /
src /
imach.c
Revision
1.209:
download - view:
text,
annotated -
select for diffs
Tue Nov 17 22:12:03 2015 UTC (8 years, 9 months ago) by
brouard
Branches:
MAIN
CVS tags:
HEAD
Summary: Adding ftolpl parameter
Author: N Brouard
We had difficulties to get smoothed confidence intervals. It was due
to the period prevalence which wasn't computed accurately. The inner
parameter ftolpl is now an outer parameter of the .imach parameter
file after estepm. If ftolpl is small 1.e-4 and estepm too,
computation are long.
1: /* $Id: imach.c,v 1.209 2015/11/17 22:12:03 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.209 2015/11/17 22:12:03 brouard
5: Summary: Adding ftolpl parameter
6: Author: N Brouard
7:
8: We had difficulties to get smoothed confidence intervals. It was due
9: to the period prevalence which wasn't computed accurately. The inner
10: parameter ftolpl is now an outer parameter of the .imach parameter
11: file after estepm. If ftolpl is small 1.e-4 and estepm too,
12: computation are long.
13:
14: Revision 1.208 2015/11/17 14:31:57 brouard
15: Summary: temporary
16:
17: Revision 1.207 2015/10/27 17:36:57 brouard
18: *** empty log message ***
19:
20: Revision 1.206 2015/10/24 07:14:11 brouard
21: *** empty log message ***
22:
23: Revision 1.205 2015/10/23 15:50:53 brouard
24: Summary: 0.98r3 some clarification for graphs on likelihood contributions
25:
26: Revision 1.204 2015/10/01 16:20:26 brouard
27: Summary: Some new graphs of contribution to likelihood
28:
29: Revision 1.203 2015/09/30 17:45:14 brouard
30: Summary: looking at better estimation of the hessian
31:
32: Also a better criteria for convergence to the period prevalence And
33: therefore adding the number of years needed to converge. (The
34: prevalence in any alive state shold sum to one
35:
36: Revision 1.202 2015/09/22 19:45:16 brouard
37: Summary: Adding some overall graph on contribution to likelihood. Might change
38:
39: Revision 1.201 2015/09/15 17:34:58 brouard
40: Summary: 0.98r0
41:
42: - Some new graphs like suvival functions
43: - Some bugs fixed like model=1+age+V2.
44:
45: Revision 1.200 2015/09/09 16:53:55 brouard
46: Summary: Big bug thanks to Flavia
47:
48: Even model=1+age+V2. did not work anymore
49:
50: Revision 1.199 2015/09/07 14:09:23 brouard
51: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
52:
53: Revision 1.198 2015/09/03 07:14:39 brouard
54: Summary: 0.98q5 Flavia
55:
56: Revision 1.197 2015/09/01 18:24:39 brouard
57: *** empty log message ***
58:
59: Revision 1.196 2015/08/18 23:17:52 brouard
60: Summary: 0.98q5
61:
62: Revision 1.195 2015/08/18 16:28:39 brouard
63: Summary: Adding a hack for testing purpose
64:
65: After reading the title, ftol and model lines, if the comment line has
66: a q, starting with #q, the answer at the end of the run is quit. It
67: permits to run test files in batch with ctest. The former workaround was
68: $ echo q | imach foo.imach
69:
70: Revision 1.194 2015/08/18 13:32:00 brouard
71: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
72:
73: Revision 1.193 2015/08/04 07:17:42 brouard
74: Summary: 0.98q4
75:
76: Revision 1.192 2015/07/16 16:49:02 brouard
77: Summary: Fixing some outputs
78:
79: Revision 1.191 2015/07/14 10:00:33 brouard
80: Summary: Some fixes
81:
82: Revision 1.190 2015/05/05 08:51:13 brouard
83: Summary: Adding digits in output parameters (7 digits instead of 6)
84:
85: Fix 1+age+.
86:
87: Revision 1.189 2015/04/30 14:45:16 brouard
88: Summary: 0.98q2
89:
90: Revision 1.188 2015/04/30 08:27:53 brouard
91: *** empty log message ***
92:
93: Revision 1.187 2015/04/29 09:11:15 brouard
94: *** empty log message ***
95:
96: Revision 1.186 2015/04/23 12:01:52 brouard
97: Summary: V1*age is working now, version 0.98q1
98:
99: Some codes had been disabled in order to simplify and Vn*age was
100: working in the optimization phase, ie, giving correct MLE parameters,
101: but, as usual, outputs were not correct and program core dumped.
102:
103: Revision 1.185 2015/03/11 13:26:42 brouard
104: Summary: Inclusion of compile and links command line for Intel Compiler
105:
106: Revision 1.184 2015/03/11 11:52:39 brouard
107: Summary: Back from Windows 8. Intel Compiler
108:
109: Revision 1.183 2015/03/10 20:34:32 brouard
110: Summary: 0.98q0, trying with directest, mnbrak fixed
111:
112: We use directest instead of original Powell test; probably no
113: incidence on the results, but better justifications;
114: We fixed Numerical Recipes mnbrak routine which was wrong and gave
115: wrong results.
116:
117: Revision 1.182 2015/02/12 08:19:57 brouard
118: Summary: Trying to keep directest which seems simpler and more general
119: Author: Nicolas Brouard
120:
121: Revision 1.181 2015/02/11 23:22:24 brouard
122: Summary: Comments on Powell added
123:
124: Author:
125:
126: Revision 1.180 2015/02/11 17:33:45 brouard
127: Summary: Finishing move from main to function (hpijx and prevalence_limit)
128:
129: Revision 1.179 2015/01/04 09:57:06 brouard
130: Summary: back to OS/X
131:
132: Revision 1.178 2015/01/04 09:35:48 brouard
133: *** empty log message ***
134:
135: Revision 1.177 2015/01/03 18:40:56 brouard
136: Summary: Still testing ilc32 on OSX
137:
138: Revision 1.176 2015/01/03 16:45:04 brouard
139: *** empty log message ***
140:
141: Revision 1.175 2015/01/03 16:33:42 brouard
142: *** empty log message ***
143:
144: Revision 1.174 2015/01/03 16:15:49 brouard
145: Summary: Still in cross-compilation
146:
147: Revision 1.173 2015/01/03 12:06:26 brouard
148: Summary: trying to detect cross-compilation
149:
150: Revision 1.172 2014/12/27 12:07:47 brouard
151: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
152:
153: Revision 1.171 2014/12/23 13:26:59 brouard
154: Summary: Back from Visual C
155:
156: Still problem with utsname.h on Windows
157:
158: Revision 1.170 2014/12/23 11:17:12 brouard
159: Summary: Cleaning some \%% back to %%
160:
161: The escape was mandatory for a specific compiler (which one?), but too many warnings.
162:
163: Revision 1.169 2014/12/22 23:08:31 brouard
164: Summary: 0.98p
165:
166: Outputs some informations on compiler used, OS etc. Testing on different platforms.
167:
168: Revision 1.168 2014/12/22 15:17:42 brouard
169: Summary: update
170:
171: Revision 1.167 2014/12/22 13:50:56 brouard
172: Summary: Testing uname and compiler version and if compiled 32 or 64
173:
174: Testing on Linux 64
175:
176: Revision 1.166 2014/12/22 11:40:47 brouard
177: *** empty log message ***
178:
179: Revision 1.165 2014/12/16 11:20:36 brouard
180: Summary: After compiling on Visual C
181:
182: * imach.c (Module): Merging 1.61 to 1.162
183:
184: Revision 1.164 2014/12/16 10:52:11 brouard
185: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
186:
187: * imach.c (Module): Merging 1.61 to 1.162
188:
189: Revision 1.163 2014/12/16 10:30:11 brouard
190: * imach.c (Module): Merging 1.61 to 1.162
191:
192: Revision 1.162 2014/09/25 11:43:39 brouard
193: Summary: temporary backup 0.99!
194:
195: Revision 1.1 2014/09/16 11:06:58 brouard
196: Summary: With some code (wrong) for nlopt
197:
198: Author:
199:
200: Revision 1.161 2014/09/15 20:41:41 brouard
201: Summary: Problem with macro SQR on Intel compiler
202:
203: Revision 1.160 2014/09/02 09:24:05 brouard
204: *** empty log message ***
205:
206: Revision 1.159 2014/09/01 10:34:10 brouard
207: Summary: WIN32
208: Author: Brouard
209:
210: Revision 1.158 2014/08/27 17:11:51 brouard
211: *** empty log message ***
212:
213: Revision 1.157 2014/08/27 16:26:55 brouard
214: Summary: Preparing windows Visual studio version
215: Author: Brouard
216:
217: In order to compile on Visual studio, time.h is now correct and time_t
218: and tm struct should be used. difftime should be used but sometimes I
219: just make the differences in raw time format (time(&now).
220: Trying to suppress #ifdef LINUX
221: Add xdg-open for __linux in order to open default browser.
222:
223: Revision 1.156 2014/08/25 20:10:10 brouard
224: *** empty log message ***
225:
226: Revision 1.155 2014/08/25 18:32:34 brouard
227: Summary: New compile, minor changes
228: Author: Brouard
229:
230: Revision 1.154 2014/06/20 17:32:08 brouard
231: Summary: Outputs now all graphs of convergence to period prevalence
232:
233: Revision 1.153 2014/06/20 16:45:46 brouard
234: Summary: If 3 live state, convergence to period prevalence on same graph
235: Author: Brouard
236:
237: Revision 1.152 2014/06/18 17:54:09 brouard
238: Summary: open browser, use gnuplot on same dir than imach if not found in the path
239:
240: Revision 1.151 2014/06/18 16:43:30 brouard
241: *** empty log message ***
242:
243: Revision 1.150 2014/06/18 16:42:35 brouard
244: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
245: Author: brouard
246:
247: Revision 1.149 2014/06/18 15:51:14 brouard
248: Summary: Some fixes in parameter files errors
249: Author: Nicolas Brouard
250:
251: Revision 1.148 2014/06/17 17:38:48 brouard
252: Summary: Nothing new
253: Author: Brouard
254:
255: Just a new packaging for OS/X version 0.98nS
256:
257: Revision 1.147 2014/06/16 10:33:11 brouard
258: *** empty log message ***
259:
260: Revision 1.146 2014/06/16 10:20:28 brouard
261: Summary: Merge
262: Author: Brouard
263:
264: Merge, before building revised version.
265:
266: Revision 1.145 2014/06/10 21:23:15 brouard
267: Summary: Debugging with valgrind
268: Author: Nicolas Brouard
269:
270: Lot of changes in order to output the results with some covariates
271: After the Edimburgh REVES conference 2014, it seems mandatory to
272: improve the code.
273: No more memory valgrind error but a lot has to be done in order to
274: continue the work of splitting the code into subroutines.
275: Also, decodemodel has been improved. Tricode is still not
276: optimal. nbcode should be improved. Documentation has been added in
277: the source code.
278:
279: Revision 1.143 2014/01/26 09:45:38 brouard
280: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
281:
282: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
283: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
284:
285: Revision 1.142 2014/01/26 03:57:36 brouard
286: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
287:
288: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
289:
290: Revision 1.141 2014/01/26 02:42:01 brouard
291: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
292:
293: Revision 1.140 2011/09/02 10:37:54 brouard
294: Summary: times.h is ok with mingw32 now.
295:
296: Revision 1.139 2010/06/14 07:50:17 brouard
297: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
298: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
299:
300: Revision 1.138 2010/04/30 18:19:40 brouard
301: *** empty log message ***
302:
303: Revision 1.137 2010/04/29 18:11:38 brouard
304: (Module): Checking covariates for more complex models
305: than V1+V2. A lot of change to be done. Unstable.
306:
307: Revision 1.136 2010/04/26 20:30:53 brouard
308: (Module): merging some libgsl code. Fixing computation
309: of likelione (using inter/intrapolation if mle = 0) in order to
310: get same likelihood as if mle=1.
311: Some cleaning of code and comments added.
312:
313: Revision 1.135 2009/10/29 15:33:14 brouard
314: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
315:
316: Revision 1.134 2009/10/29 13:18:53 brouard
317: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
318:
319: Revision 1.133 2009/07/06 10:21:25 brouard
320: just nforces
321:
322: Revision 1.132 2009/07/06 08:22:05 brouard
323: Many tings
324:
325: Revision 1.131 2009/06/20 16:22:47 brouard
326: Some dimensions resccaled
327:
328: Revision 1.130 2009/05/26 06:44:34 brouard
329: (Module): Max Covariate is now set to 20 instead of 8. A
330: lot of cleaning with variables initialized to 0. Trying to make
331: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
332:
333: Revision 1.129 2007/08/31 13:49:27 lievre
334: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
335:
336: Revision 1.128 2006/06/30 13:02:05 brouard
337: (Module): Clarifications on computing e.j
338:
339: Revision 1.127 2006/04/28 18:11:50 brouard
340: (Module): Yes the sum of survivors was wrong since
341: imach-114 because nhstepm was no more computed in the age
342: loop. Now we define nhstepma in the age loop.
343: (Module): In order to speed up (in case of numerous covariates) we
344: compute health expectancies (without variances) in a first step
345: and then all the health expectancies with variances or standard
346: deviation (needs data from the Hessian matrices) which slows the
347: computation.
348: In the future we should be able to stop the program is only health
349: expectancies and graph are needed without standard deviations.
350:
351: Revision 1.126 2006/04/28 17:23:28 brouard
352: (Module): Yes the sum of survivors was wrong since
353: imach-114 because nhstepm was no more computed in the age
354: loop. Now we define nhstepma in the age loop.
355: Version 0.98h
356:
357: Revision 1.125 2006/04/04 15:20:31 lievre
358: Errors in calculation of health expectancies. Age was not initialized.
359: Forecasting file added.
360:
361: Revision 1.124 2006/03/22 17:13:53 lievre
362: Parameters are printed with %lf instead of %f (more numbers after the comma).
363: The log-likelihood is printed in the log file
364:
365: Revision 1.123 2006/03/20 10:52:43 brouard
366: * imach.c (Module): <title> changed, corresponds to .htm file
367: name. <head> headers where missing.
368:
369: * imach.c (Module): Weights can have a decimal point as for
370: English (a comma might work with a correct LC_NUMERIC environment,
371: otherwise the weight is truncated).
372: Modification of warning when the covariates values are not 0 or
373: 1.
374: Version 0.98g
375:
376: Revision 1.122 2006/03/20 09:45:41 brouard
377: (Module): Weights can have a decimal point as for
378: English (a comma might work with a correct LC_NUMERIC environment,
379: otherwise the weight is truncated).
380: Modification of warning when the covariates values are not 0 or
381: 1.
382: Version 0.98g
383:
384: Revision 1.121 2006/03/16 17:45:01 lievre
385: * imach.c (Module): Comments concerning covariates added
386:
387: * imach.c (Module): refinements in the computation of lli if
388: status=-2 in order to have more reliable computation if stepm is
389: not 1 month. Version 0.98f
390:
391: Revision 1.120 2006/03/16 15:10:38 lievre
392: (Module): refinements in the computation of lli if
393: status=-2 in order to have more reliable computation if stepm is
394: not 1 month. Version 0.98f
395:
396: Revision 1.119 2006/03/15 17:42:26 brouard
397: (Module): Bug if status = -2, the loglikelihood was
398: computed as likelihood omitting the logarithm. Version O.98e
399:
400: Revision 1.118 2006/03/14 18:20:07 brouard
401: (Module): varevsij Comments added explaining the second
402: table of variances if popbased=1 .
403: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
404: (Module): Function pstamp added
405: (Module): Version 0.98d
406:
407: Revision 1.117 2006/03/14 17:16:22 brouard
408: (Module): varevsij Comments added explaining the second
409: table of variances if popbased=1 .
410: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
411: (Module): Function pstamp added
412: (Module): Version 0.98d
413:
414: Revision 1.116 2006/03/06 10:29:27 brouard
415: (Module): Variance-covariance wrong links and
416: varian-covariance of ej. is needed (Saito).
417:
418: Revision 1.115 2006/02/27 12:17:45 brouard
419: (Module): One freematrix added in mlikeli! 0.98c
420:
421: Revision 1.114 2006/02/26 12:57:58 brouard
422: (Module): Some improvements in processing parameter
423: filename with strsep.
424:
425: Revision 1.113 2006/02/24 14:20:24 brouard
426: (Module): Memory leaks checks with valgrind and:
427: datafile was not closed, some imatrix were not freed and on matrix
428: allocation too.
429:
430: Revision 1.112 2006/01/30 09:55:26 brouard
431: (Module): Back to gnuplot.exe instead of wgnuplot.exe
432:
433: Revision 1.111 2006/01/25 20:38:18 brouard
434: (Module): Lots of cleaning and bugs added (Gompertz)
435: (Module): Comments can be added in data file. Missing date values
436: can be a simple dot '.'.
437:
438: Revision 1.110 2006/01/25 00:51:50 brouard
439: (Module): Lots of cleaning and bugs added (Gompertz)
440:
441: Revision 1.109 2006/01/24 19:37:15 brouard
442: (Module): Comments (lines starting with a #) are allowed in data.
443:
444: Revision 1.108 2006/01/19 18:05:42 lievre
445: Gnuplot problem appeared...
446: To be fixed
447:
448: Revision 1.107 2006/01/19 16:20:37 brouard
449: Test existence of gnuplot in imach path
450:
451: Revision 1.106 2006/01/19 13:24:36 brouard
452: Some cleaning and links added in html output
453:
454: Revision 1.105 2006/01/05 20:23:19 lievre
455: *** empty log message ***
456:
457: Revision 1.104 2005/09/30 16:11:43 lievre
458: (Module): sump fixed, loop imx fixed, and simplifications.
459: (Module): If the status is missing at the last wave but we know
460: that the person is alive, then we can code his/her status as -2
461: (instead of missing=-1 in earlier versions) and his/her
462: contributions to the likelihood is 1 - Prob of dying from last
463: health status (= 1-p13= p11+p12 in the easiest case of somebody in
464: the healthy state at last known wave). Version is 0.98
465:
466: Revision 1.103 2005/09/30 15:54:49 lievre
467: (Module): sump fixed, loop imx fixed, and simplifications.
468:
469: Revision 1.102 2004/09/15 17:31:30 brouard
470: Add the possibility to read data file including tab characters.
471:
472: Revision 1.101 2004/09/15 10:38:38 brouard
473: Fix on curr_time
474:
475: Revision 1.100 2004/07/12 18:29:06 brouard
476: Add version for Mac OS X. Just define UNIX in Makefile
477:
478: Revision 1.99 2004/06/05 08:57:40 brouard
479: *** empty log message ***
480:
481: Revision 1.98 2004/05/16 15:05:56 brouard
482: New version 0.97 . First attempt to estimate force of mortality
483: directly from the data i.e. without the need of knowing the health
484: state at each age, but using a Gompertz model: log u =a + b*age .
485: This is the basic analysis of mortality and should be done before any
486: other analysis, in order to test if the mortality estimated from the
487: cross-longitudinal survey is different from the mortality estimated
488: from other sources like vital statistic data.
489:
490: The same imach parameter file can be used but the option for mle should be -3.
491:
492: Agnès, who wrote this part of the code, tried to keep most of the
493: former routines in order to include the new code within the former code.
494:
495: The output is very simple: only an estimate of the intercept and of
496: the slope with 95% confident intervals.
497:
498: Current limitations:
499: A) Even if you enter covariates, i.e. with the
500: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
501: B) There is no computation of Life Expectancy nor Life Table.
502:
503: Revision 1.97 2004/02/20 13:25:42 lievre
504: Version 0.96d. Population forecasting command line is (temporarily)
505: suppressed.
506:
507: Revision 1.96 2003/07/15 15:38:55 brouard
508: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
509: rewritten within the same printf. Workaround: many printfs.
510:
511: Revision 1.95 2003/07/08 07:54:34 brouard
512: * imach.c (Repository):
513: (Repository): Using imachwizard code to output a more meaningful covariance
514: matrix (cov(a12,c31) instead of numbers.
515:
516: Revision 1.94 2003/06/27 13:00:02 brouard
517: Just cleaning
518:
519: Revision 1.93 2003/06/25 16:33:55 brouard
520: (Module): On windows (cygwin) function asctime_r doesn't
521: exist so I changed back to asctime which exists.
522: (Module): Version 0.96b
523:
524: Revision 1.92 2003/06/25 16:30:45 brouard
525: (Module): On windows (cygwin) function asctime_r doesn't
526: exist so I changed back to asctime which exists.
527:
528: Revision 1.91 2003/06/25 15:30:29 brouard
529: * imach.c (Repository): Duplicated warning errors corrected.
530: (Repository): Elapsed time after each iteration is now output. It
531: helps to forecast when convergence will be reached. Elapsed time
532: is stamped in powell. We created a new html file for the graphs
533: concerning matrix of covariance. It has extension -cov.htm.
534:
535: Revision 1.90 2003/06/24 12:34:15 brouard
536: (Module): Some bugs corrected for windows. Also, when
537: mle=-1 a template is output in file "or"mypar.txt with the design
538: of the covariance matrix to be input.
539:
540: Revision 1.89 2003/06/24 12:30:52 brouard
541: (Module): Some bugs corrected for windows. Also, when
542: mle=-1 a template is output in file "or"mypar.txt with the design
543: of the covariance matrix to be input.
544:
545: Revision 1.88 2003/06/23 17:54:56 brouard
546: * 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.
547:
548: Revision 1.87 2003/06/18 12:26:01 brouard
549: Version 0.96
550:
551: Revision 1.86 2003/06/17 20:04:08 brouard
552: (Module): Change position of html and gnuplot routines and added
553: routine fileappend.
554:
555: Revision 1.85 2003/06/17 13:12:43 brouard
556: * imach.c (Repository): Check when date of death was earlier that
557: current date of interview. It may happen when the death was just
558: prior to the death. In this case, dh was negative and likelihood
559: was wrong (infinity). We still send an "Error" but patch by
560: assuming that the date of death was just one stepm after the
561: interview.
562: (Repository): Because some people have very long ID (first column)
563: we changed int to long in num[] and we added a new lvector for
564: memory allocation. But we also truncated to 8 characters (left
565: truncation)
566: (Repository): No more line truncation errors.
567:
568: Revision 1.84 2003/06/13 21:44:43 brouard
569: * imach.c (Repository): Replace "freqsummary" at a correct
570: place. It differs from routine "prevalence" which may be called
571: many times. Probs is memory consuming and must be used with
572: parcimony.
573: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
574:
575: Revision 1.83 2003/06/10 13:39:11 lievre
576: *** empty log message ***
577:
578: Revision 1.82 2003/06/05 15:57:20 brouard
579: Add log in imach.c and fullversion number is now printed.
580:
581: */
582: /*
583: Interpolated Markov Chain
584:
585: Short summary of the programme:
586:
587: This program computes Healthy Life Expectancies from
588: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
589: first survey ("cross") where individuals from different ages are
590: interviewed on their health status or degree of disability (in the
591: case of a health survey which is our main interest) -2- at least a
592: second wave of interviews ("longitudinal") which measure each change
593: (if any) in individual health status. Health expectancies are
594: computed from the time spent in each health state according to a
595: model. More health states you consider, more time is necessary to reach the
596: Maximum Likelihood of the parameters involved in the model. The
597: simplest model is the multinomial logistic model where pij is the
598: probability to be observed in state j at the second wave
599: conditional to be observed in state i at the first wave. Therefore
600: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
601: 'age' is age and 'sex' is a covariate. If you want to have a more
602: complex model than "constant and age", you should modify the program
603: where the markup *Covariates have to be included here again* invites
604: you to do it. More covariates you add, slower the
605: convergence.
606:
607: The advantage of this computer programme, compared to a simple
608: multinomial logistic model, is clear when the delay between waves is not
609: identical for each individual. Also, if a individual missed an
610: intermediate interview, the information is lost, but taken into
611: account using an interpolation or extrapolation.
612:
613: hPijx is the probability to be observed in state i at age x+h
614: conditional to the observed state i at age x. The delay 'h' can be
615: split into an exact number (nh*stepm) of unobserved intermediate
616: states. This elementary transition (by month, quarter,
617: semester or year) is modelled as a multinomial logistic. The hPx
618: matrix is simply the matrix product of nh*stepm elementary matrices
619: and the contribution of each individual to the likelihood is simply
620: hPijx.
621:
622: Also this programme outputs the covariance matrix of the parameters but also
623: of the life expectancies. It also computes the period (stable) prevalence.
624:
625: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
626: Institut national d'études démographiques, Paris.
627: This software have been partly granted by Euro-REVES, a concerted action
628: from the European Union.
629: It is copyrighted identically to a GNU software product, ie programme and
630: software can be distributed freely for non commercial use. Latest version
631: can be accessed at http://euroreves.ined.fr/imach .
632:
633: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
634: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
635:
636: **********************************************************************/
637: /*
638: main
639: read parameterfile
640: read datafile
641: concatwav
642: freqsummary
643: if (mle >= 1)
644: mlikeli
645: print results files
646: if mle==1
647: computes hessian
648: read end of parameter file: agemin, agemax, bage, fage, estepm
649: begin-prev-date,...
650: open gnuplot file
651: open html file
652: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
653: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
654: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
655: freexexit2 possible for memory heap.
656:
657: h Pij x | pij_nom ficrestpij
658: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
659: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
660: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
661:
662: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
663: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
664: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
665: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
666: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
667:
668: forecasting if prevfcast==1 prevforecast call prevalence()
669: health expectancies
670: Variance-covariance of DFLE
671: prevalence()
672: movingaverage()
673: varevsij()
674: if popbased==1 varevsij(,popbased)
675: total life expectancies
676: Variance of period (stable) prevalence
677: end
678: */
679:
680: /* #define DEBUG */
681: /* #define DEBUGBRENT */
682: /* #define DEBUGLINMIN */
683: /* #define DEBUGHESS */
684: #define DEBUGHESSIJ
685: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
686: #define POWELL /* Instead of NLOPT */
687: #define POWELLF1F3 /* Skip test */
688: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
689: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
690:
691: #include <math.h>
692: #include <stdio.h>
693: #include <stdlib.h>
694: #include <string.h>
695:
696: #ifdef _WIN32
697: #include <io.h>
698: #include <windows.h>
699: #include <tchar.h>
700: #else
701: #include <unistd.h>
702: #endif
703:
704: #include <limits.h>
705: #include <sys/types.h>
706:
707: #if defined(__GNUC__)
708: #include <sys/utsname.h> /* Doesn't work on Windows */
709: #endif
710:
711: #include <sys/stat.h>
712: #include <errno.h>
713: /* extern int errno; */
714:
715: /* #ifdef LINUX */
716: /* #include <time.h> */
717: /* #include "timeval.h" */
718: /* #else */
719: /* #include <sys/time.h> */
720: /* #endif */
721:
722: #include <time.h>
723:
724: #ifdef GSL
725: #include <gsl/gsl_errno.h>
726: #include <gsl/gsl_multimin.h>
727: #endif
728:
729:
730: #ifdef NLOPT
731: #include <nlopt.h>
732: typedef struct {
733: double (* function)(double [] );
734: } myfunc_data ;
735: #endif
736:
737: /* #include <libintl.h> */
738: /* #define _(String) gettext (String) */
739:
740: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
741:
742: #define GNUPLOTPROGRAM "gnuplot"
743: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
744: #define FILENAMELENGTH 132
745:
746: #define GLOCK_ERROR_NOPATH -1 /* empty path */
747: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
748:
749: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
750: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
751:
752: #define NINTERVMAX 8
753: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
754: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
755: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
756: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
757: #define MAXN 20000
758: #define YEARM 12. /**< Number of months per year */
759: #define AGESUP 130
760: #define AGEBASE 40
761: #define AGEOVERFLOW 1.e20
762: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
763: #ifdef _WIN32
764: #define DIRSEPARATOR '\\'
765: #define CHARSEPARATOR "\\"
766: #define ODIRSEPARATOR '/'
767: #else
768: #define DIRSEPARATOR '/'
769: #define CHARSEPARATOR "/"
770: #define ODIRSEPARATOR '\\'
771: #endif
772:
773: /* $Id: imach.c,v 1.209 2015/11/17 22:12:03 brouard Exp $ */
774: /* $State: Exp $ */
775: #include "version.h"
776: char version[]=__IMACH_VERSION__;
777: 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";
778: char fullversion[]="$Revision: 1.209 $ $Date: 2015/11/17 22:12:03 $";
779: char strstart[80];
780: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
781: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
782: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
783: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
784: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
785: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
786: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
787: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
788: int cptcovprodnoage=0; /**< Number of covariate products without age */
789: int cptcoveff=0; /* Total number of covariates to vary for printing results */
790: int cptcov=0; /* Working variable */
791: int npar=NPARMAX;
792: int nlstate=2; /* Number of live states */
793: int ndeath=1; /* Number of dead states */
794: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
795: int popbased=0;
796:
797: int *wav; /* Number of waves for this individuual 0 is possible */
798: int maxwav=0; /* Maxim number of waves */
799: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
800: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
801: int gipmx=0, gsw=0; /* Global variables on the number of contributions
802: to the likelihood and the sum of weights (done by funcone)*/
803: int mle=1, weightopt=0;
804: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
805: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
806: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
807: * wave mi and wave mi+1 is not an exact multiple of stepm. */
808: int countcallfunc=0; /* Count the number of calls to func */
809: double jmean=1; /* Mean space between 2 waves */
810: double **matprod2(); /* test */
811: double **oldm, **newm, **savm; /* Working pointers to matrices */
812: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
813: /*FILE *fic ; */ /* Used in readdata only */
814: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
815: FILE *ficlog, *ficrespow;
816: int globpr=0; /* Global variable for printing or not */
817: double fretone; /* Only one call to likelihood */
818: long ipmx=0; /* Number of contributions */
819: double sw; /* Sum of weights */
820: char filerespow[FILENAMELENGTH];
821: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
822: FILE *ficresilk;
823: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
824: FILE *ficresprobmorprev;
825: FILE *fichtm, *fichtmcov; /* Html File */
826: FILE *ficreseij;
827: char filerese[FILENAMELENGTH];
828: FILE *ficresstdeij;
829: char fileresstde[FILENAMELENGTH];
830: FILE *ficrescveij;
831: char filerescve[FILENAMELENGTH];
832: FILE *ficresvij;
833: char fileresv[FILENAMELENGTH];
834: FILE *ficresvpl;
835: char fileresvpl[FILENAMELENGTH];
836: char title[MAXLINE];
837: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
838: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
839: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
840: char command[FILENAMELENGTH];
841: int outcmd=0;
842:
843: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
844: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
845: char filelog[FILENAMELENGTH]; /* Log file */
846: char filerest[FILENAMELENGTH];
847: char fileregp[FILENAMELENGTH];
848: char popfile[FILENAMELENGTH];
849:
850: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
851:
852: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
853: /* struct timezone tzp; */
854: /* extern int gettimeofday(); */
855: struct tm tml, *gmtime(), *localtime();
856:
857: extern time_t time();
858:
859: struct tm start_time, end_time, curr_time, last_time, forecast_time;
860: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
861: struct tm tm;
862:
863: char strcurr[80], strfor[80];
864:
865: char *endptr;
866: long lval;
867: double dval;
868:
869: #define NR_END 1
870: #define FREE_ARG char*
871: #define FTOL 1.0e-10
872:
873: #define NRANSI
874: #define ITMAX 200
875:
876: #define TOL 2.0e-4
877:
878: #define CGOLD 0.3819660
879: #define ZEPS 1.0e-10
880: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
881:
882: #define GOLD 1.618034
883: #define GLIMIT 100.0
884: #define TINY 1.0e-20
885:
886: static double maxarg1,maxarg2;
887: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
888: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
889:
890: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
891: #define rint(a) floor(a+0.5)
892: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
893: #define mytinydouble 1.0e-16
894: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
895: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
896: /* static double dsqrarg; */
897: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
898: static double sqrarg;
899: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
900: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
901: int agegomp= AGEGOMP;
902:
903: int imx;
904: int stepm=1;
905: /* Stepm, step in month: minimum step interpolation*/
906:
907: int estepm;
908: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
909:
910: int m,nb;
911: long *num;
912: int firstpass=0, lastpass=4,*cod, *cens;
913: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
914: covariate for which somebody answered excluding
915: undefined. Usually 2: 0 and 1. */
916: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
917: covariate for which somebody answered including
918: undefined. Usually 3: -1, 0 and 1. */
919: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
920: double **pmmij, ***probs;
921: double *ageexmed,*agecens;
922: double dateintmean=0;
923:
924: double *weight;
925: int **s; /* Status */
926: double *agedc;
927: double **covar; /**< covar[j,i], value of jth covariate for individual i,
928: * covar=matrix(0,NCOVMAX,1,n);
929: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
930: double idx;
931: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
932: int *Tage;
933: int *Ndum; /** Freq of modality (tricode */
934: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
935: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
936: double *lsurv, *lpop, *tpop;
937:
938: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
939: double ftolhess; /**< Tolerance for computing hessian */
940:
941: /**************** split *************************/
942: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
943: {
944: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
945: the name of the file (name), its extension only (ext) and its first part of the name (finame)
946: */
947: char *ss; /* pointer */
948: int l1=0, l2=0; /* length counters */
949:
950: l1 = strlen(path ); /* length of path */
951: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
952: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
953: if ( ss == NULL ) { /* no directory, so determine current directory */
954: strcpy( name, path ); /* we got the fullname name because no directory */
955: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
956: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
957: /* get current working directory */
958: /* extern char* getcwd ( char *buf , int len);*/
959: #ifdef WIN32
960: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
961: #else
962: if (getcwd(dirc, FILENAME_MAX) == NULL) {
963: #endif
964: return( GLOCK_ERROR_GETCWD );
965: }
966: /* got dirc from getcwd*/
967: printf(" DIRC = %s \n",dirc);
968: } else { /* strip directory from path */
969: ss++; /* after this, the filename */
970: l2 = strlen( ss ); /* length of filename */
971: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
972: strcpy( name, ss ); /* save file name */
973: strncpy( dirc, path, l1 - l2 ); /* now the directory */
974: dirc[l1-l2] = '\0'; /* add zero */
975: printf(" DIRC2 = %s \n",dirc);
976: }
977: /* We add a separator at the end of dirc if not exists */
978: l1 = strlen( dirc ); /* length of directory */
979: if( dirc[l1-1] != DIRSEPARATOR ){
980: dirc[l1] = DIRSEPARATOR;
981: dirc[l1+1] = 0;
982: printf(" DIRC3 = %s \n",dirc);
983: }
984: ss = strrchr( name, '.' ); /* find last / */
985: if (ss >0){
986: ss++;
987: strcpy(ext,ss); /* save extension */
988: l1= strlen( name);
989: l2= strlen(ss)+1;
990: strncpy( finame, name, l1-l2);
991: finame[l1-l2]= 0;
992: }
993:
994: return( 0 ); /* we're done */
995: }
996:
997:
998: /******************************************/
999:
1000: void replace_back_to_slash(char *s, char*t)
1001: {
1002: int i;
1003: int lg=0;
1004: i=0;
1005: lg=strlen(t);
1006: for(i=0; i<= lg; i++) {
1007: (s[i] = t[i]);
1008: if (t[i]== '\\') s[i]='/';
1009: }
1010: }
1011:
1012: char *trimbb(char *out, char *in)
1013: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1014: char *s;
1015: s=out;
1016: while (*in != '\0'){
1017: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1018: in++;
1019: }
1020: *out++ = *in++;
1021: }
1022: *out='\0';
1023: return s;
1024: }
1025:
1026: /* char *substrchaine(char *out, char *in, char *chain) */
1027: /* { */
1028: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1029: /* char *s, *t; */
1030: /* t=in;s=out; */
1031: /* while ((*in != *chain) && (*in != '\0')){ */
1032: /* *out++ = *in++; */
1033: /* } */
1034:
1035: /* /\* *in matches *chain *\/ */
1036: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1037: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1038: /* } */
1039: /* in--; chain--; */
1040: /* while ( (*in != '\0')){ */
1041: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1042: /* *out++ = *in++; */
1043: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1044: /* } */
1045: /* *out='\0'; */
1046: /* out=s; */
1047: /* return out; */
1048: /* } */
1049: char *substrchaine(char *out, char *in, char *chain)
1050: {
1051: /* Substract chain 'chain' from 'in', return and output 'out' */
1052: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1053:
1054: char *strloc;
1055:
1056: strcpy (out, in);
1057: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1058: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1059: if(strloc != NULL){
1060: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1061: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1062: /* strcpy (strloc, strloc +strlen(chain));*/
1063: }
1064: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1065: return out;
1066: }
1067:
1068:
1069: char *cutl(char *blocc, char *alocc, char *in, char occ)
1070: {
1071: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1072: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1073: gives blocc="abcdef" and alocc="ghi2j".
1074: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1075: */
1076: char *s, *t;
1077: t=in;s=in;
1078: while ((*in != occ) && (*in != '\0')){
1079: *alocc++ = *in++;
1080: }
1081: if( *in == occ){
1082: *(alocc)='\0';
1083: s=++in;
1084: }
1085:
1086: if (s == t) {/* occ not found */
1087: *(alocc-(in-s))='\0';
1088: in=s;
1089: }
1090: while ( *in != '\0'){
1091: *blocc++ = *in++;
1092: }
1093:
1094: *blocc='\0';
1095: return t;
1096: }
1097: char *cutv(char *blocc, char *alocc, char *in, char occ)
1098: {
1099: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1100: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1101: gives blocc="abcdef2ghi" and alocc="j".
1102: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1103: */
1104: char *s, *t;
1105: t=in;s=in;
1106: while (*in != '\0'){
1107: while( *in == occ){
1108: *blocc++ = *in++;
1109: s=in;
1110: }
1111: *blocc++ = *in++;
1112: }
1113: if (s == t) /* occ not found */
1114: *(blocc-(in-s))='\0';
1115: else
1116: *(blocc-(in-s)-1)='\0';
1117: in=s;
1118: while ( *in != '\0'){
1119: *alocc++ = *in++;
1120: }
1121:
1122: *alocc='\0';
1123: return s;
1124: }
1125:
1126: int nbocc(char *s, char occ)
1127: {
1128: int i,j=0;
1129: int lg=20;
1130: i=0;
1131: lg=strlen(s);
1132: for(i=0; i<= lg; i++) {
1133: if (s[i] == occ ) j++;
1134: }
1135: return j;
1136: }
1137:
1138: /* void cutv(char *u,char *v, char*t, char occ) */
1139: /* { */
1140: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1141: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1142: /* gives u="abcdef2ghi" and v="j" *\/ */
1143: /* int i,lg,j,p=0; */
1144: /* i=0; */
1145: /* lg=strlen(t); */
1146: /* for(j=0; j<=lg-1; j++) { */
1147: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1148: /* } */
1149:
1150: /* for(j=0; j<p; j++) { */
1151: /* (u[j] = t[j]); */
1152: /* } */
1153: /* u[p]='\0'; */
1154:
1155: /* for(j=0; j<= lg; j++) { */
1156: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1157: /* } */
1158: /* } */
1159:
1160: #ifdef _WIN32
1161: char * strsep(char **pp, const char *delim)
1162: {
1163: char *p, *q;
1164:
1165: if ((p = *pp) == NULL)
1166: return 0;
1167: if ((q = strpbrk (p, delim)) != NULL)
1168: {
1169: *pp = q + 1;
1170: *q = '\0';
1171: }
1172: else
1173: *pp = 0;
1174: return p;
1175: }
1176: #endif
1177:
1178: /********************** nrerror ********************/
1179:
1180: void nrerror(char error_text[])
1181: {
1182: fprintf(stderr,"ERREUR ...\n");
1183: fprintf(stderr,"%s\n",error_text);
1184: exit(EXIT_FAILURE);
1185: }
1186: /*********************** vector *******************/
1187: double *vector(int nl, int nh)
1188: {
1189: double *v;
1190: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1191: if (!v) nrerror("allocation failure in vector");
1192: return v-nl+NR_END;
1193: }
1194:
1195: /************************ free vector ******************/
1196: void free_vector(double*v, int nl, int nh)
1197: {
1198: free((FREE_ARG)(v+nl-NR_END));
1199: }
1200:
1201: /************************ivector *******************************/
1202: int *ivector(long nl,long nh)
1203: {
1204: int *v;
1205: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1206: if (!v) nrerror("allocation failure in ivector");
1207: return v-nl+NR_END;
1208: }
1209:
1210: /******************free ivector **************************/
1211: void free_ivector(int *v, long nl, long nh)
1212: {
1213: free((FREE_ARG)(v+nl-NR_END));
1214: }
1215:
1216: /************************lvector *******************************/
1217: long *lvector(long nl,long nh)
1218: {
1219: long *v;
1220: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1221: if (!v) nrerror("allocation failure in ivector");
1222: return v-nl+NR_END;
1223: }
1224:
1225: /******************free lvector **************************/
1226: void free_lvector(long *v, long nl, long nh)
1227: {
1228: free((FREE_ARG)(v+nl-NR_END));
1229: }
1230:
1231: /******************* imatrix *******************************/
1232: int **imatrix(long nrl, long nrh, long ncl, long nch)
1233: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1234: {
1235: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1236: int **m;
1237:
1238: /* allocate pointers to rows */
1239: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1240: if (!m) nrerror("allocation failure 1 in matrix()");
1241: m += NR_END;
1242: m -= nrl;
1243:
1244:
1245: /* allocate rows and set pointers to them */
1246: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1247: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1248: m[nrl] += NR_END;
1249: m[nrl] -= ncl;
1250:
1251: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1252:
1253: /* return pointer to array of pointers to rows */
1254: return m;
1255: }
1256:
1257: /****************** free_imatrix *************************/
1258: void free_imatrix(m,nrl,nrh,ncl,nch)
1259: int **m;
1260: long nch,ncl,nrh,nrl;
1261: /* free an int matrix allocated by imatrix() */
1262: {
1263: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1264: free((FREE_ARG) (m+nrl-NR_END));
1265: }
1266:
1267: /******************* matrix *******************************/
1268: double **matrix(long nrl, long nrh, long ncl, long nch)
1269: {
1270: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1271: double **m;
1272:
1273: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1274: if (!m) nrerror("allocation failure 1 in matrix()");
1275: m += NR_END;
1276: m -= nrl;
1277:
1278: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1279: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1280: m[nrl] += NR_END;
1281: m[nrl] -= ncl;
1282:
1283: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1284: return m;
1285: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1286: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1287: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1288: */
1289: }
1290:
1291: /*************************free matrix ************************/
1292: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1293: {
1294: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1295: free((FREE_ARG)(m+nrl-NR_END));
1296: }
1297:
1298: /******************* ma3x *******************************/
1299: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1300: {
1301: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1302: double ***m;
1303:
1304: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1305: if (!m) nrerror("allocation failure 1 in matrix()");
1306: m += NR_END;
1307: m -= nrl;
1308:
1309: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1310: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1311: m[nrl] += NR_END;
1312: m[nrl] -= ncl;
1313:
1314: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1315:
1316: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1317: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1318: m[nrl][ncl] += NR_END;
1319: m[nrl][ncl] -= nll;
1320: for (j=ncl+1; j<=nch; j++)
1321: m[nrl][j]=m[nrl][j-1]+nlay;
1322:
1323: for (i=nrl+1; i<=nrh; i++) {
1324: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1325: for (j=ncl+1; j<=nch; j++)
1326: m[i][j]=m[i][j-1]+nlay;
1327: }
1328: return m;
1329: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1330: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1331: */
1332: }
1333:
1334: /*************************free ma3x ************************/
1335: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1336: {
1337: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1338: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1339: free((FREE_ARG)(m+nrl-NR_END));
1340: }
1341:
1342: /*************** function subdirf ***********/
1343: char *subdirf(char fileres[])
1344: {
1345: /* Caution optionfilefiname is hidden */
1346: strcpy(tmpout,optionfilefiname);
1347: strcat(tmpout,"/"); /* Add to the right */
1348: strcat(tmpout,fileres);
1349: return tmpout;
1350: }
1351:
1352: /*************** function subdirf2 ***********/
1353: char *subdirf2(char fileres[], char *preop)
1354: {
1355:
1356: /* Caution optionfilefiname is hidden */
1357: strcpy(tmpout,optionfilefiname);
1358: strcat(tmpout,"/");
1359: strcat(tmpout,preop);
1360: strcat(tmpout,fileres);
1361: return tmpout;
1362: }
1363:
1364: /*************** function subdirf3 ***********/
1365: char *subdirf3(char fileres[], char *preop, char *preop2)
1366: {
1367:
1368: /* Caution optionfilefiname is hidden */
1369: strcpy(tmpout,optionfilefiname);
1370: strcat(tmpout,"/");
1371: strcat(tmpout,preop);
1372: strcat(tmpout,preop2);
1373: strcat(tmpout,fileres);
1374: return tmpout;
1375: }
1376:
1377: char *asc_diff_time(long time_sec, char ascdiff[])
1378: {
1379: long sec_left, days, hours, minutes;
1380: days = (time_sec) / (60*60*24);
1381: sec_left = (time_sec) % (60*60*24);
1382: hours = (sec_left) / (60*60) ;
1383: sec_left = (sec_left) %(60*60);
1384: minutes = (sec_left) /60;
1385: sec_left = (sec_left) % (60);
1386: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1387: return ascdiff;
1388: }
1389:
1390: /***************** f1dim *************************/
1391: extern int ncom;
1392: extern double *pcom,*xicom;
1393: extern double (*nrfunc)(double []);
1394:
1395: double f1dim(double x)
1396: {
1397: int j;
1398: double f;
1399: double *xt;
1400:
1401: xt=vector(1,ncom);
1402: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1403: f=(*nrfunc)(xt);
1404: free_vector(xt,1,ncom);
1405: return f;
1406: }
1407:
1408: /*****************brent *************************/
1409: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1410: {
1411: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1412: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1413: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1414: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1415: * returned function value.
1416: */
1417: int iter;
1418: double a,b,d,etemp;
1419: double fu=0,fv,fw,fx;
1420: double ftemp=0.;
1421: double p,q,r,tol1,tol2,u,v,w,x,xm;
1422: double e=0.0;
1423:
1424: a=(ax < cx ? ax : cx);
1425: b=(ax > cx ? ax : cx);
1426: x=w=v=bx;
1427: fw=fv=fx=(*f)(x);
1428: for (iter=1;iter<=ITMAX;iter++) {
1429: xm=0.5*(a+b);
1430: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1431: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1432: printf(".");fflush(stdout);
1433: fprintf(ficlog,".");fflush(ficlog);
1434: #ifdef DEBUGBRENT
1435: 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);
1436: 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);
1437: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1438: #endif
1439: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1440: *xmin=x;
1441: return fx;
1442: }
1443: ftemp=fu;
1444: if (fabs(e) > tol1) {
1445: r=(x-w)*(fx-fv);
1446: q=(x-v)*(fx-fw);
1447: p=(x-v)*q-(x-w)*r;
1448: q=2.0*(q-r);
1449: if (q > 0.0) p = -p;
1450: q=fabs(q);
1451: etemp=e;
1452: e=d;
1453: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1454: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1455: else {
1456: d=p/q;
1457: u=x+d;
1458: if (u-a < tol2 || b-u < tol2)
1459: d=SIGN(tol1,xm-x);
1460: }
1461: } else {
1462: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1463: }
1464: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1465: fu=(*f)(u);
1466: if (fu <= fx) {
1467: if (u >= x) a=x; else b=x;
1468: SHFT(v,w,x,u)
1469: SHFT(fv,fw,fx,fu)
1470: } else {
1471: if (u < x) a=u; else b=u;
1472: if (fu <= fw || w == x) {
1473: v=w;
1474: w=u;
1475: fv=fw;
1476: fw=fu;
1477: } else if (fu <= fv || v == x || v == w) {
1478: v=u;
1479: fv=fu;
1480: }
1481: }
1482: }
1483: nrerror("Too many iterations in brent");
1484: *xmin=x;
1485: return fx;
1486: }
1487:
1488: /****************** mnbrak ***********************/
1489:
1490: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1491: double (*func)(double))
1492: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1493: the downhill direction (defined by the function as evaluated at the initial points) and returns
1494: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1495: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1496: */
1497: double ulim,u,r,q, dum;
1498: double fu;
1499:
1500: double scale=10.;
1501: int iterscale=0;
1502:
1503: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1504: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1505:
1506:
1507: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1508: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1509: /* *bx = *ax - (*ax - *bx)/scale; */
1510: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1511: /* } */
1512:
1513: if (*fb > *fa) {
1514: SHFT(dum,*ax,*bx,dum)
1515: SHFT(dum,*fb,*fa,dum)
1516: }
1517: *cx=(*bx)+GOLD*(*bx-*ax);
1518: *fc=(*func)(*cx);
1519: #ifdef DEBUG
1520: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1521: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1522: #endif
1523: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1524: r=(*bx-*ax)*(*fb-*fc);
1525: q=(*bx-*cx)*(*fb-*fa);
1526: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1527: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1528: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1529: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1530: fu=(*func)(u);
1531: #ifdef DEBUG
1532: /* f(x)=A(x-u)**2+f(u) */
1533: double A, fparabu;
1534: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1535: fparabu= *fa - A*(*ax-u)*(*ax-u);
1536: 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);
1537: 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);
1538: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1539: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1540: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1541: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1542: #endif
1543: #ifdef MNBRAKORIGINAL
1544: #else
1545: /* if (fu > *fc) { */
1546: /* #ifdef DEBUG */
1547: /* printf("mnbrak4 fu > fc \n"); */
1548: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1549: /* #endif */
1550: /* /\* 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 *\\/ *\/ */
1551: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1552: /* dum=u; /\* Shifting c and u *\/ */
1553: /* u = *cx; */
1554: /* *cx = dum; */
1555: /* dum = fu; */
1556: /* fu = *fc; */
1557: /* *fc =dum; */
1558: /* } else { /\* end *\/ */
1559: /* #ifdef DEBUG */
1560: /* printf("mnbrak3 fu < fc \n"); */
1561: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1562: /* #endif */
1563: /* dum=u; /\* Shifting c and u *\/ */
1564: /* u = *cx; */
1565: /* *cx = dum; */
1566: /* dum = fu; */
1567: /* fu = *fc; */
1568: /* *fc =dum; */
1569: /* } */
1570: #ifdef DEBUG
1571: printf("mnbrak34 fu < or >= fc \n");
1572: fprintf(ficlog, "mnbrak34 fu < fc\n");
1573: #endif
1574: dum=u; /* Shifting c and u */
1575: u = *cx;
1576: *cx = dum;
1577: dum = fu;
1578: fu = *fc;
1579: *fc =dum;
1580: #endif
1581: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1582: #ifdef DEBUG
1583: printf("mnbrak2 u after c but before ulim\n");
1584: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1585: #endif
1586: fu=(*func)(u);
1587: if (fu < *fc) {
1588: #ifdef DEBUG
1589: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1590: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1591: #endif
1592: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1593: SHFT(*fb,*fc,fu,(*func)(u))
1594: }
1595: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1596: #ifdef DEBUG
1597: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1598: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1599: #endif
1600: u=ulim;
1601: fu=(*func)(u);
1602: } else { /* u could be left to b (if r > q parabola has a maximum) */
1603: #ifdef DEBUG
1604: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1605: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1606: #endif
1607: u=(*cx)+GOLD*(*cx-*bx);
1608: fu=(*func)(u);
1609: } /* end tests */
1610: SHFT(*ax,*bx,*cx,u)
1611: SHFT(*fa,*fb,*fc,fu)
1612: #ifdef DEBUG
1613: 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);
1614: 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);
1615: #endif
1616: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1617: }
1618:
1619: /*************** linmin ************************/
1620: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1621: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1622: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1623: the value of func at the returned location p . This is actually all accomplished by calling the
1624: routines mnbrak and brent .*/
1625: int ncom;
1626: double *pcom,*xicom;
1627: double (*nrfunc)(double []);
1628:
1629: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1630: {
1631: double brent(double ax, double bx, double cx,
1632: double (*f)(double), double tol, double *xmin);
1633: double f1dim(double x);
1634: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1635: double *fc, double (*func)(double));
1636: int j;
1637: double xx,xmin,bx,ax;
1638: double fx,fb,fa;
1639:
1640: #ifdef LINMINORIGINAL
1641: #else
1642: double scale=10., axs, xxs; /* Scale added for infinity */
1643: #endif
1644:
1645: ncom=n;
1646: pcom=vector(1,n);
1647: xicom=vector(1,n);
1648: nrfunc=func;
1649: for (j=1;j<=n;j++) {
1650: pcom[j]=p[j];
1651: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1652: }
1653:
1654: #ifdef LINMINORIGINAL
1655: xx=1.;
1656: #else
1657: axs=0.0;
1658: xxs=1.;
1659: do{
1660: xx= xxs;
1661: #endif
1662: ax=0.;
1663: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1664: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1665: /* 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)) */
1666: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1667: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1668: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1669: /* 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]]*/
1670: #ifdef LINMINORIGINAL
1671: #else
1672: if (fx != fx){
1673: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1674: printf("|");
1675: fprintf(ficlog,"|");
1676: #ifdef DEBUGLINMIN
1677: 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);
1678: #endif
1679: }
1680: }while(fx != fx);
1681: #endif
1682:
1683: #ifdef DEBUGLINMIN
1684: 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);
1685: 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);
1686: #endif
1687: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1688: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1689: /* fmin = f(p[j] + xmin * xi[j]) */
1690: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1691: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1692: #ifdef DEBUG
1693: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1694: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1695: #endif
1696: #ifdef DEBUGLINMIN
1697: printf("linmin end ");
1698: fprintf(ficlog,"linmin end ");
1699: #endif
1700: for (j=1;j<=n;j++) {
1701: #ifdef LINMINORIGINAL
1702: xi[j] *= xmin;
1703: #else
1704: #ifdef DEBUGLINMIN
1705: if(xxs <1.0)
1706: printf(" before xi[%d]=%12.8f", j,xi[j]);
1707: #endif
1708: 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) */
1709: #ifdef DEBUGLINMIN
1710: if(xxs <1.0)
1711: 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 );
1712: #endif
1713: #endif
1714: p[j] += xi[j]; /* Parameters values are updated accordingly */
1715: }
1716: #ifdef DEBUGLINMIN
1717: printf("\n");
1718: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1719: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1720: for (j=1;j<=n;j++) {
1721: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1722: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1723: if(j % ncovmodel == 0){
1724: printf("\n");
1725: fprintf(ficlog,"\n");
1726: }
1727: }
1728: #else
1729: #endif
1730: free_vector(xicom,1,n);
1731: free_vector(pcom,1,n);
1732: }
1733:
1734:
1735: /*************** powell ************************/
1736: /*
1737: Minimization of a function func of n variables. Input consists of an initial starting point
1738: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1739: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1740: such that failure to decrease by more than this amount on one iteration signals doneness. On
1741: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1742: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1743: */
1744: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1745: double (*func)(double []))
1746: {
1747: void linmin(double p[], double xi[], int n, double *fret,
1748: double (*func)(double []));
1749: int i,ibig,j;
1750: double del,t,*pt,*ptt,*xit;
1751: double directest;
1752: double fp,fptt;
1753: double *xits;
1754: int niterf, itmp;
1755:
1756: pt=vector(1,n);
1757: ptt=vector(1,n);
1758: xit=vector(1,n);
1759: xits=vector(1,n);
1760: *fret=(*func)(p);
1761: for (j=1;j<=n;j++) pt[j]=p[j];
1762: rcurr_time = time(NULL);
1763: for (*iter=1;;++(*iter)) {
1764: fp=(*fret); /* From former iteration or initial value */
1765: ibig=0;
1766: del=0.0;
1767: rlast_time=rcurr_time;
1768: /* (void) gettimeofday(&curr_time,&tzp); */
1769: rcurr_time = time(NULL);
1770: curr_time = *localtime(&rcurr_time);
1771: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1772: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1773: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1774: for (i=1;i<=n;i++) {
1775: printf(" %d %.12f",i, p[i]);
1776: fprintf(ficlog," %d %.12lf",i, p[i]);
1777: fprintf(ficrespow," %.12lf", p[i]);
1778: }
1779: printf("\n");
1780: fprintf(ficlog,"\n");
1781: fprintf(ficrespow,"\n");fflush(ficrespow);
1782: if(*iter <=3){
1783: tml = *localtime(&rcurr_time);
1784: strcpy(strcurr,asctime(&tml));
1785: rforecast_time=rcurr_time;
1786: itmp = strlen(strcurr);
1787: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1788: strcurr[itmp-1]='\0';
1789: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1790: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1791: for(niterf=10;niterf<=30;niterf+=10){
1792: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1793: forecast_time = *localtime(&rforecast_time);
1794: strcpy(strfor,asctime(&forecast_time));
1795: itmp = strlen(strfor);
1796: if(strfor[itmp-1]=='\n')
1797: strfor[itmp-1]='\0';
1798: 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);
1799: 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);
1800: }
1801: }
1802: for (i=1;i<=n;i++) { /* For each direction i */
1803: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1804: fptt=(*fret);
1805: #ifdef DEBUG
1806: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1807: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1808: #endif
1809: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1810: fprintf(ficlog,"%d",i);fflush(ficlog);
1811: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1812: /* Outputs are fret(new point p) p is updated and xit rescaled */
1813: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1814: /* because that direction will be replaced unless the gain del is small */
1815: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1816: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1817: /* with the new direction. */
1818: del=fabs(fptt-(*fret));
1819: ibig=i;
1820: }
1821: #ifdef DEBUG
1822: printf("%d %.12e",i,(*fret));
1823: fprintf(ficlog,"%d %.12e",i,(*fret));
1824: for (j=1;j<=n;j++) {
1825: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1826: printf(" x(%d)=%.12e",j,xit[j]);
1827: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1828: }
1829: for(j=1;j<=n;j++) {
1830: printf(" p(%d)=%.12e",j,p[j]);
1831: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1832: }
1833: printf("\n");
1834: fprintf(ficlog,"\n");
1835: #endif
1836: } /* end loop on each direction i */
1837: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1838: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1839: /* New value of last point Pn is not computed, P(n-1) */
1840: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1841: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1842: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1843: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1844: /* decreased of more than 3.84 */
1845: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1846: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1847: /* By adding 10 parameters more the gain should be 18.31 */
1848:
1849: /* Starting the program with initial values given by a former maximization will simply change */
1850: /* the scales of the directions and the directions, because the are reset to canonical directions */
1851: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1852: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1853: #ifdef DEBUG
1854: int k[2],l;
1855: k[0]=1;
1856: k[1]=-1;
1857: printf("Max: %.12e",(*func)(p));
1858: fprintf(ficlog,"Max: %.12e",(*func)(p));
1859: for (j=1;j<=n;j++) {
1860: printf(" %.12e",p[j]);
1861: fprintf(ficlog," %.12e",p[j]);
1862: }
1863: printf("\n");
1864: fprintf(ficlog,"\n");
1865: for(l=0;l<=1;l++) {
1866: for (j=1;j<=n;j++) {
1867: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1868: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1869: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1870: }
1871: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1872: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1873: }
1874: #endif
1875:
1876:
1877: free_vector(xit,1,n);
1878: free_vector(xits,1,n);
1879: free_vector(ptt,1,n);
1880: free_vector(pt,1,n);
1881: return;
1882: } /* enough precision */
1883: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1884: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1885: ptt[j]=2.0*p[j]-pt[j];
1886: xit[j]=p[j]-pt[j];
1887: pt[j]=p[j];
1888: }
1889: fptt=(*func)(ptt); /* f_3 */
1890: #ifdef POWELLF1F3
1891: #else
1892: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1893: #endif
1894: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1895: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1896: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1897: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1898: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1899: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1900: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1901: #ifdef NRCORIGINAL
1902: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1903: #else
1904: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1905: t= t- del*SQR(fp-fptt);
1906: #endif
1907: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1908: #ifdef DEBUG
1909: 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);
1910: 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);
1911: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1912: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1913: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1914: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1915: 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);
1916: 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);
1917: #endif
1918: #ifdef POWELLORIGINAL
1919: if (t < 0.0) { /* Then we use it for new direction */
1920: #else
1921: if (directest*t < 0.0) { /* Contradiction between both tests */
1922: 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);
1923: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1924: 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);
1925: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1926: }
1927: if (directest < 0.0) { /* Then we use it for new direction */
1928: #endif
1929: #ifdef DEBUGLINMIN
1930: printf("Before linmin in direction P%d-P0\n",n);
1931: for (j=1;j<=n;j++) {
1932: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1933: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1934: if(j % ncovmodel == 0){
1935: printf("\n");
1936: fprintf(ficlog,"\n");
1937: }
1938: }
1939: #endif
1940: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1941: #ifdef DEBUGLINMIN
1942: for (j=1;j<=n;j++) {
1943: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1944: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1945: if(j % ncovmodel == 0){
1946: printf("\n");
1947: fprintf(ficlog,"\n");
1948: }
1949: }
1950: #endif
1951: for (j=1;j<=n;j++) {
1952: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1953: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1954: }
1955: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1956: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1957:
1958: #ifdef DEBUG
1959: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1960: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1961: for(j=1;j<=n;j++){
1962: printf(" %.12e",xit[j]);
1963: fprintf(ficlog," %.12e",xit[j]);
1964: }
1965: printf("\n");
1966: fprintf(ficlog,"\n");
1967: #endif
1968: } /* end of t or directest negative */
1969: #ifdef POWELLF1F3
1970: #else
1971: } /* end if (fptt < fp) */
1972: #endif
1973: } /* loop iteration */
1974: }
1975:
1976: /**** Prevalence limit (stable or period prevalence) ****************/
1977:
1978: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1979: {
1980: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1981: matrix by transitions matrix until convergence is reached with precision ftolpl */
1982: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
1983: /* Wx is row vector: population in state 1, population in state 2, population dead */
1984: /* or prevalence in state 1, prevalence in state 2, 0 */
1985: /* newm is the matrix after multiplications, its rows are identical at a factor */
1986: /* Initial matrix pimij */
1987: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
1988: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
1989: /* 0, 0 , 1} */
1990: /*
1991: * and after some iteration: */
1992: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
1993: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
1994: /* 0, 0 , 1} */
1995: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
1996: /* {0.51571254859325999, 0.4842874514067399, */
1997: /* 0.51326036147820708, 0.48673963852179264} */
1998: /* If we start from prlim again, prlim tends to a constant matrix */
1999:
2000: int i, ii,j,k;
2001: double *min, *max, *meandiff, maxmax,sumnew=0.;
2002: /* double **matprod2(); */ /* test */
2003: double **out, cov[NCOVMAX+1], **pmij();
2004: double **newm;
2005: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2006: int ncvloop=0;
2007:
2008: min=vector(1,nlstate);
2009: max=vector(1,nlstate);
2010: meandiff=vector(1,nlstate);
2011:
2012: for (ii=1;ii<=nlstate+ndeath;ii++)
2013: for (j=1;j<=nlstate+ndeath;j++){
2014: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2015: }
2016:
2017: cov[1]=1.;
2018:
2019: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2020: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2021: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2022: ncvloop++;
2023: newm=savm;
2024: /* Covariates have to be included here again */
2025: cov[2]=agefin;
2026: if(nagesqr==1)
2027: cov[3]= agefin*agefin;;
2028: for (k=1; k<=cptcovn;k++) {
2029: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2030: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2031: /* 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])]); */
2032: }
2033: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2034: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2035: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2036: for (k=1; k<=cptcovprod;k++) /* Useless */
2037: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2038: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2039:
2040: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2041: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2042: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2043: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2044: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2045: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2046:
2047: savm=oldm;
2048: oldm=newm;
2049:
2050: for(j=1; j<=nlstate; j++){
2051: max[j]=0.;
2052: min[j]=1.;
2053: }
2054: for(i=1;i<=nlstate;i++){
2055: sumnew=0;
2056: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2057: for(j=1; j<=nlstate; j++){
2058: prlim[i][j]= newm[i][j]/(1-sumnew);
2059: max[j]=FMAX(max[j],prlim[i][j]);
2060: min[j]=FMIN(min[j],prlim[i][j]);
2061: }
2062: }
2063:
2064: maxmax=0.;
2065: for(j=1; j<=nlstate; j++){
2066: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2067: maxmax=FMAX(maxmax,meandiff[j]);
2068: /* 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); */
2069: } /* j loop */
2070: *ncvyear= (int)age- (int)agefin;
2071: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2072: if(maxmax < ftolpl){
2073: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2074: free_vector(min,1,nlstate);
2075: free_vector(max,1,nlstate);
2076: free_vector(meandiff,1,nlstate);
2077: return prlim;
2078: }
2079: } /* age loop */
2080: /* After some age loop it doesn't converge */
2081: 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\
2082: 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);
2083: /* 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); */
2084: free_vector(min,1,nlstate);
2085: free_vector(max,1,nlstate);
2086: free_vector(meandiff,1,nlstate);
2087:
2088: return prlim; /* should not reach here */
2089: }
2090:
2091: /*************** transition probabilities ***************/
2092:
2093: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2094: {
2095: /* According to parameters values stored in x and the covariate's values stored in cov,
2096: computes the probability to be observed in state j being in state i by appying the
2097: model to the ncovmodel covariates (including constant and age).
2098: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2099: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2100: ncth covariate in the global vector x is given by the formula:
2101: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2102: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2103: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2104: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2105: Outputs ps[i][j] the probability to be observed in j being in j according to
2106: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2107: */
2108: double s1, lnpijopii;
2109: /*double t34;*/
2110: int i,j, nc, ii, jj;
2111:
2112: for(i=1; i<= nlstate; i++){
2113: for(j=1; j<i;j++){
2114: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2115: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2116: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2117: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2118: }
2119: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2120: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2121: }
2122: for(j=i+1; j<=nlstate+ndeath;j++){
2123: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2124: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2125: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2126: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2127: }
2128: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2129: }
2130: }
2131:
2132: for(i=1; i<= nlstate; i++){
2133: s1=0;
2134: for(j=1; j<i; j++){
2135: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2136: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2137: }
2138: for(j=i+1; j<=nlstate+ndeath; j++){
2139: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2140: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2141: }
2142: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2143: ps[i][i]=1./(s1+1.);
2144: /* Computing other pijs */
2145: for(j=1; j<i; j++)
2146: ps[i][j]= exp(ps[i][j])*ps[i][i];
2147: for(j=i+1; j<=nlstate+ndeath; j++)
2148: ps[i][j]= exp(ps[i][j])*ps[i][i];
2149: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2150: } /* end i */
2151:
2152: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2153: for(jj=1; jj<= nlstate+ndeath; jj++){
2154: ps[ii][jj]=0;
2155: ps[ii][ii]=1;
2156: }
2157: }
2158:
2159:
2160: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2161: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2162: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2163: /* } */
2164: /* printf("\n "); */
2165: /* } */
2166: /* printf("\n ");printf("%lf ",cov[2]);*/
2167: /*
2168: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2169: goto end;*/
2170: return ps;
2171: }
2172:
2173: /**************** Product of 2 matrices ******************/
2174:
2175: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2176: {
2177: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2178: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2179: /* in, b, out are matrice of pointers which should have been initialized
2180: before: only the contents of out is modified. The function returns
2181: a pointer to pointers identical to out */
2182: int i, j, k;
2183: for(i=nrl; i<= nrh; i++)
2184: for(k=ncolol; k<=ncoloh; k++){
2185: out[i][k]=0.;
2186: for(j=ncl; j<=nch; j++)
2187: out[i][k] +=in[i][j]*b[j][k];
2188: }
2189: return out;
2190: }
2191:
2192:
2193: /************* Higher Matrix Product ***************/
2194:
2195: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2196: {
2197: /* Computes the transition matrix starting at age 'age' over
2198: 'nhstepm*hstepm*stepm' months (i.e. until
2199: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2200: nhstepm*hstepm matrices.
2201: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2202: (typically every 2 years instead of every month which is too big
2203: for the memory).
2204: Model is determined by parameters x and covariates have to be
2205: included manually here.
2206:
2207: */
2208:
2209: int i, j, d, h, k;
2210: double **out, cov[NCOVMAX+1];
2211: double **newm;
2212: double agexact;
2213:
2214: /* Hstepm could be zero and should return the unit matrix */
2215: for (i=1;i<=nlstate+ndeath;i++)
2216: for (j=1;j<=nlstate+ndeath;j++){
2217: oldm[i][j]=(i==j ? 1.0 : 0.0);
2218: po[i][j][0]=(i==j ? 1.0 : 0.0);
2219: }
2220: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2221: for(h=1; h <=nhstepm; h++){
2222: for(d=1; d <=hstepm; d++){
2223: newm=savm;
2224: /* Covariates have to be included here again */
2225: cov[1]=1.;
2226: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
2227: cov[2]=agexact;
2228: if(nagesqr==1)
2229: cov[3]= agexact*agexact;
2230: for (k=1; k<=cptcovn;k++)
2231: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2232: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2233: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2234: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2235: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2236: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2237: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2238: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2239: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2240:
2241:
2242: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2243: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2244: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2245: pmij(pmmij,cov,ncovmodel,x,nlstate));
2246: savm=oldm;
2247: oldm=newm;
2248: }
2249: for(i=1; i<=nlstate+ndeath; i++)
2250: for(j=1;j<=nlstate+ndeath;j++) {
2251: po[i][j][h]=newm[i][j];
2252: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2253: }
2254: /*printf("h=%d ",h);*/
2255: } /* end h */
2256: /* printf("\n H=%d \n",h); */
2257: return po;
2258: }
2259:
2260: #ifdef NLOPT
2261: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2262: double fret;
2263: double *xt;
2264: int j;
2265: myfunc_data *d2 = (myfunc_data *) pd;
2266: /* xt = (p1-1); */
2267: xt=vector(1,n);
2268: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2269:
2270: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2271: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2272: printf("Function = %.12lf ",fret);
2273: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2274: printf("\n");
2275: free_vector(xt,1,n);
2276: return fret;
2277: }
2278: #endif
2279:
2280: /*************** log-likelihood *************/
2281: double func( double *x)
2282: {
2283: int i, ii, j, k, mi, d, kk;
2284: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2285: double **out;
2286: double sw; /* Sum of weights */
2287: double lli; /* Individual log likelihood */
2288: int s1, s2;
2289: double bbh, survp;
2290: long ipmx;
2291: double agexact;
2292: /*extern weight */
2293: /* We are differentiating ll according to initial status */
2294: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2295: /*for(i=1;i<imx;i++)
2296: printf(" %d\n",s[4][i]);
2297: */
2298:
2299: ++countcallfunc;
2300:
2301: cov[1]=1.;
2302:
2303: for(k=1; k<=nlstate; k++) ll[k]=0.;
2304:
2305: if(mle==1){
2306: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2307: /* Computes the values of the ncovmodel covariates of the model
2308: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2309: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2310: to be observed in j being in i according to the model.
2311: */
2312: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2313: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2314: }
2315: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2316: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2317: has been calculated etc */
2318: for(mi=1; mi<= wav[i]-1; mi++){
2319: for (ii=1;ii<=nlstate+ndeath;ii++)
2320: for (j=1;j<=nlstate+ndeath;j++){
2321: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2322: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2323: }
2324: for(d=0; d<dh[mi][i]; d++){
2325: newm=savm;
2326: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2327: cov[2]=agexact;
2328: if(nagesqr==1)
2329: cov[3]= agexact*agexact;
2330: for (kk=1; kk<=cptcovage;kk++) {
2331: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2332: }
2333: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2334: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2335: savm=oldm;
2336: oldm=newm;
2337: } /* end mult */
2338:
2339: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2340: /* But now since version 0.9 we anticipate for bias at large stepm.
2341: * If stepm is larger than one month (smallest stepm) and if the exact delay
2342: * (in months) between two waves is not a multiple of stepm, we rounded to
2343: * the nearest (and in case of equal distance, to the lowest) interval but now
2344: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2345: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2346: * probability in order to take into account the bias as a fraction of the way
2347: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2348: * -stepm/2 to stepm/2 .
2349: * For stepm=1 the results are the same as for previous versions of Imach.
2350: * For stepm > 1 the results are less biased than in previous versions.
2351: */
2352: s1=s[mw[mi][i]][i];
2353: s2=s[mw[mi+1][i]][i];
2354: bbh=(double)bh[mi][i]/(double)stepm;
2355: /* bias bh is positive if real duration
2356: * is higher than the multiple of stepm and negative otherwise.
2357: */
2358: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2359: if( s2 > nlstate){
2360: /* i.e. if s2 is a death state and if the date of death is known
2361: then the contribution to the likelihood is the probability to
2362: die between last step unit time and current step unit time,
2363: which is also equal to probability to die before dh
2364: minus probability to die before dh-stepm .
2365: In version up to 0.92 likelihood was computed
2366: as if date of death was unknown. Death was treated as any other
2367: health state: the date of the interview describes the actual state
2368: and not the date of a change in health state. The former idea was
2369: to consider that at each interview the state was recorded
2370: (healthy, disable or death) and IMaCh was corrected; but when we
2371: introduced the exact date of death then we should have modified
2372: the contribution of an exact death to the likelihood. This new
2373: contribution is smaller and very dependent of the step unit
2374: stepm. It is no more the probability to die between last interview
2375: and month of death but the probability to survive from last
2376: interview up to one month before death multiplied by the
2377: probability to die within a month. Thanks to Chris
2378: Jackson for correcting this bug. Former versions increased
2379: mortality artificially. The bad side is that we add another loop
2380: which slows down the processing. The difference can be up to 10%
2381: lower mortality.
2382: */
2383: /* If, at the beginning of the maximization mostly, the
2384: cumulative probability or probability to be dead is
2385: constant (ie = 1) over time d, the difference is equal to
2386: 0. out[s1][3] = savm[s1][3]: probability, being at state
2387: s1 at precedent wave, to be dead a month before current
2388: wave is equal to probability, being at state s1 at
2389: precedent wave, to be dead at mont of the current
2390: wave. Then the observed probability (that this person died)
2391: is null according to current estimated parameter. In fact,
2392: it should be very low but not zero otherwise the log go to
2393: infinity.
2394: */
2395: /* #ifdef INFINITYORIGINAL */
2396: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2397: /* #else */
2398: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2399: /* lli=log(mytinydouble); */
2400: /* else */
2401: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2402: /* #endif */
2403: lli=log(out[s1][s2] - savm[s1][s2]);
2404:
2405: } else if (s2==-2) {
2406: for (j=1,survp=0. ; j<=nlstate; j++)
2407: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2408: /*survp += out[s1][j]; */
2409: lli= log(survp);
2410: }
2411:
2412: else if (s2==-4) {
2413: for (j=3,survp=0. ; j<=nlstate; j++)
2414: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2415: lli= log(survp);
2416: }
2417:
2418: else if (s2==-5) {
2419: for (j=1,survp=0. ; j<=2; j++)
2420: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2421: lli= log(survp);
2422: }
2423:
2424: else{
2425: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2426: /* 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 */
2427: }
2428: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2429: /*if(lli ==000.0)*/
2430: /*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); */
2431: ipmx +=1;
2432: sw += weight[i];
2433: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2434: /* if (lli < log(mytinydouble)){ */
2435: /* 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); */
2436: /* 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]); */
2437: /* } */
2438: } /* end of wave */
2439: } /* end of individual */
2440: } else if(mle==2){
2441: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2442: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2443: for(mi=1; mi<= wav[i]-1; mi++){
2444: for (ii=1;ii<=nlstate+ndeath;ii++)
2445: for (j=1;j<=nlstate+ndeath;j++){
2446: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2447: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2448: }
2449: for(d=0; d<=dh[mi][i]; d++){
2450: newm=savm;
2451: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2452: cov[2]=agexact;
2453: if(nagesqr==1)
2454: cov[3]= agexact*agexact;
2455: for (kk=1; kk<=cptcovage;kk++) {
2456: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2457: }
2458: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2459: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2460: savm=oldm;
2461: oldm=newm;
2462: } /* end mult */
2463:
2464: s1=s[mw[mi][i]][i];
2465: s2=s[mw[mi+1][i]][i];
2466: bbh=(double)bh[mi][i]/(double)stepm;
2467: 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 */
2468: ipmx +=1;
2469: sw += weight[i];
2470: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2471: } /* end of wave */
2472: } /* end of individual */
2473: } else if(mle==3){ /* exponential inter-extrapolation */
2474: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2475: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2476: for(mi=1; mi<= wav[i]-1; mi++){
2477: for (ii=1;ii<=nlstate+ndeath;ii++)
2478: for (j=1;j<=nlstate+ndeath;j++){
2479: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2480: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2481: }
2482: for(d=0; d<dh[mi][i]; d++){
2483: newm=savm;
2484: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2485: cov[2]=agexact;
2486: if(nagesqr==1)
2487: cov[3]= agexact*agexact;
2488: for (kk=1; kk<=cptcovage;kk++) {
2489: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2490: }
2491: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2492: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2493: savm=oldm;
2494: oldm=newm;
2495: } /* end mult */
2496:
2497: s1=s[mw[mi][i]][i];
2498: s2=s[mw[mi+1][i]][i];
2499: bbh=(double)bh[mi][i]/(double)stepm;
2500: 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 */
2501: ipmx +=1;
2502: sw += weight[i];
2503: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2504: } /* end of wave */
2505: } /* end of individual */
2506: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2507: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2508: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2509: for(mi=1; mi<= wav[i]-1; mi++){
2510: for (ii=1;ii<=nlstate+ndeath;ii++)
2511: for (j=1;j<=nlstate+ndeath;j++){
2512: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2513: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2514: }
2515: for(d=0; d<dh[mi][i]; d++){
2516: newm=savm;
2517: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2518: cov[2]=agexact;
2519: if(nagesqr==1)
2520: cov[3]= agexact*agexact;
2521: for (kk=1; kk<=cptcovage;kk++) {
2522: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2523: }
2524:
2525: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2526: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2527: savm=oldm;
2528: oldm=newm;
2529: } /* end mult */
2530:
2531: s1=s[mw[mi][i]][i];
2532: s2=s[mw[mi+1][i]][i];
2533: if( s2 > nlstate){
2534: lli=log(out[s1][s2] - savm[s1][s2]);
2535: }else{
2536: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2537: }
2538: ipmx +=1;
2539: sw += weight[i];
2540: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2541: /* 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]); */
2542: } /* end of wave */
2543: } /* end of individual */
2544: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2545: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2546: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2547: for(mi=1; mi<= wav[i]-1; mi++){
2548: for (ii=1;ii<=nlstate+ndeath;ii++)
2549: for (j=1;j<=nlstate+ndeath;j++){
2550: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2551: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2552: }
2553: for(d=0; d<dh[mi][i]; d++){
2554: newm=savm;
2555: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2556: cov[2]=agexact;
2557: if(nagesqr==1)
2558: cov[3]= agexact*agexact;
2559: for (kk=1; kk<=cptcovage;kk++) {
2560: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2561: }
2562:
2563: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2564: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2565: savm=oldm;
2566: oldm=newm;
2567: } /* end mult */
2568:
2569: s1=s[mw[mi][i]][i];
2570: s2=s[mw[mi+1][i]][i];
2571: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2572: ipmx +=1;
2573: sw += weight[i];
2574: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2575: /*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]);*/
2576: } /* end of wave */
2577: } /* end of individual */
2578: } /* End of if */
2579: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2580: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2581: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2582: return -l;
2583: }
2584:
2585: /*************** log-likelihood *************/
2586: double funcone( double *x)
2587: {
2588: /* Same as likeli but slower because of a lot of printf and if */
2589: int i, ii, j, k, mi, d, kk;
2590: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2591: double **out;
2592: double lli; /* Individual log likelihood */
2593: double llt;
2594: int s1, s2;
2595: double bbh, survp;
2596: double agexact;
2597: /*extern weight */
2598: /* We are differentiating ll according to initial status */
2599: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2600: /*for(i=1;i<imx;i++)
2601: printf(" %d\n",s[4][i]);
2602: */
2603: cov[1]=1.;
2604:
2605: for(k=1; k<=nlstate; k++) ll[k]=0.;
2606:
2607: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2608: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2609: for(mi=1; mi<= wav[i]-1; mi++){
2610: for (ii=1;ii<=nlstate+ndeath;ii++)
2611: for (j=1;j<=nlstate+ndeath;j++){
2612: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2613: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2614: }
2615: for(d=0; d<dh[mi][i]; d++){
2616: newm=savm;
2617: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2618: cov[2]=agexact;
2619: if(nagesqr==1)
2620: cov[3]= agexact*agexact;
2621: for (kk=1; kk<=cptcovage;kk++) {
2622: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2623: }
2624:
2625: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2626: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2627: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2628: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2629: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2630: savm=oldm;
2631: oldm=newm;
2632: } /* end mult */
2633:
2634: s1=s[mw[mi][i]][i];
2635: s2=s[mw[mi+1][i]][i];
2636: bbh=(double)bh[mi][i]/(double)stepm;
2637: /* bias is positive if real duration
2638: * is higher than the multiple of stepm and negative otherwise.
2639: */
2640: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2641: lli=log(out[s1][s2] - savm[s1][s2]);
2642: } else if (s2==-2) {
2643: for (j=1,survp=0. ; j<=nlstate; j++)
2644: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2645: lli= log(survp);
2646: }else if (mle==1){
2647: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2648: } else if(mle==2){
2649: 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 */
2650: } else if(mle==3){ /* exponential inter-extrapolation */
2651: 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 */
2652: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2653: lli=log(out[s1][s2]); /* Original formula */
2654: } else{ /* mle=0 back to 1 */
2655: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2656: /*lli=log(out[s1][s2]); */ /* Original formula */
2657: } /* End of if */
2658: ipmx +=1;
2659: sw += weight[i];
2660: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2661: /*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]); */
2662: if(globpr){
2663: fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2664: %11.6f %11.6f %11.6f ", \
2665: num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2666: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2667: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2668: llt +=ll[k]*gipmx/gsw;
2669: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2670: }
2671: fprintf(ficresilk," %10.6f\n", -llt);
2672: }
2673: } /* end of wave */
2674: } /* end of individual */
2675: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2676: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2677: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2678: if(globpr==0){ /* First time we count the contributions and weights */
2679: gipmx=ipmx;
2680: gsw=sw;
2681: }
2682: return -l;
2683: }
2684:
2685:
2686: /*************** function likelione ***********/
2687: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2688: {
2689: /* This routine should help understanding what is done with
2690: the selection of individuals/waves and
2691: to check the exact contribution to the likelihood.
2692: Plotting could be done.
2693: */
2694: int k;
2695:
2696: if(*globpri !=0){ /* Just counts and sums, no printings */
2697: strcpy(fileresilk,"ILK_");
2698: strcat(fileresilk,fileresu);
2699: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2700: printf("Problem with resultfile: %s\n", fileresilk);
2701: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2702: }
2703: fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
2704: fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
2705: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2706: for(k=1; k<=nlstate; k++)
2707: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2708: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2709: }
2710:
2711: *fretone=(*funcone)(p);
2712: if(*globpri !=0){
2713: fclose(ficresilk);
2714: if (mle ==0)
2715: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2716: else if(mle >=1)
2717: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2718: 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));
2719:
2720:
2721: for (k=1; k<= nlstate ; k++) {
2722: fprintf(fichtm,"<br>- Probability p%dj by origin %d and destination j <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
2723: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2724: }
2725: 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> \
2726: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2727: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2728: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2729: fflush(fichtm);
2730: }
2731: return;
2732: }
2733:
2734:
2735: /*********** Maximum Likelihood Estimation ***************/
2736:
2737: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2738: {
2739: int i,j, iter=0;
2740: double **xi;
2741: double fret;
2742: double fretone; /* Only one call to likelihood */
2743: /* char filerespow[FILENAMELENGTH];*/
2744:
2745: #ifdef NLOPT
2746: int creturn;
2747: nlopt_opt opt;
2748: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2749: double *lb;
2750: double minf; /* the minimum objective value, upon return */
2751: double * p1; /* Shifted parameters from 0 instead of 1 */
2752: myfunc_data dinst, *d = &dinst;
2753: #endif
2754:
2755:
2756: xi=matrix(1,npar,1,npar);
2757: for (i=1;i<=npar;i++)
2758: for (j=1;j<=npar;j++)
2759: xi[i][j]=(i==j ? 1.0 : 0.0);
2760: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2761: strcpy(filerespow,"POW_");
2762: strcat(filerespow,fileres);
2763: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2764: printf("Problem with resultfile: %s\n", filerespow);
2765: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2766: }
2767: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2768: for (i=1;i<=nlstate;i++)
2769: for(j=1;j<=nlstate+ndeath;j++)
2770: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2771: fprintf(ficrespow,"\n");
2772: #ifdef POWELL
2773: powell(p,xi,npar,ftol,&iter,&fret,func);
2774: #endif
2775:
2776: #ifdef NLOPT
2777: #ifdef NEWUOA
2778: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2779: #else
2780: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2781: #endif
2782: lb=vector(0,npar-1);
2783: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2784: nlopt_set_lower_bounds(opt, lb);
2785: nlopt_set_initial_step1(opt, 0.1);
2786:
2787: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2788: d->function = func;
2789: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2790: nlopt_set_min_objective(opt, myfunc, d);
2791: nlopt_set_xtol_rel(opt, ftol);
2792: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2793: printf("nlopt failed! %d\n",creturn);
2794: }
2795: else {
2796: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2797: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2798: iter=1; /* not equal */
2799: }
2800: nlopt_destroy(opt);
2801: #endif
2802: free_matrix(xi,1,npar,1,npar);
2803: fclose(ficrespow);
2804: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2805: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2806: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2807:
2808: }
2809:
2810: /**** Computes Hessian and covariance matrix ***/
2811: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2812: {
2813: double **a,**y,*x,pd;
2814: /* double **hess; */
2815: int i, j;
2816: int *indx;
2817:
2818: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2819: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2820: void lubksb(double **a, int npar, int *indx, double b[]) ;
2821: void ludcmp(double **a, int npar, int *indx, double *d) ;
2822: double gompertz(double p[]);
2823: /* hess=matrix(1,npar,1,npar); */
2824:
2825: printf("\nCalculation of the hessian matrix. Wait...\n");
2826: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2827: for (i=1;i<=npar;i++){
2828: printf("%d-",i);fflush(stdout);
2829: fprintf(ficlog,"%d-",i);fflush(ficlog);
2830:
2831: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2832:
2833: /* printf(" %f ",p[i]);
2834: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2835: }
2836:
2837: for (i=1;i<=npar;i++) {
2838: for (j=1;j<=npar;j++) {
2839: if (j>i) {
2840: printf(".%d-%d",i,j);fflush(stdout);
2841: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2842: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2843:
2844: hess[j][i]=hess[i][j];
2845: /*printf(" %lf ",hess[i][j]);*/
2846: }
2847: }
2848: }
2849: printf("\n");
2850: fprintf(ficlog,"\n");
2851:
2852: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2853: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2854:
2855: a=matrix(1,npar,1,npar);
2856: y=matrix(1,npar,1,npar);
2857: x=vector(1,npar);
2858: indx=ivector(1,npar);
2859: for (i=1;i<=npar;i++)
2860: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2861: ludcmp(a,npar,indx,&pd);
2862:
2863: for (j=1;j<=npar;j++) {
2864: for (i=1;i<=npar;i++) x[i]=0;
2865: x[j]=1;
2866: lubksb(a,npar,indx,x);
2867: for (i=1;i<=npar;i++){
2868: matcov[i][j]=x[i];
2869: }
2870: }
2871:
2872: printf("\n#Hessian matrix#\n");
2873: fprintf(ficlog,"\n#Hessian matrix#\n");
2874: for (i=1;i<=npar;i++) {
2875: for (j=1;j<=npar;j++) {
2876: printf("%.6e ",hess[i][j]);
2877: fprintf(ficlog,"%.6e ",hess[i][j]);
2878: }
2879: printf("\n");
2880: fprintf(ficlog,"\n");
2881: }
2882:
2883: /* printf("\n#Covariance matrix#\n"); */
2884: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2885: /* for (i=1;i<=npar;i++) { */
2886: /* for (j=1;j<=npar;j++) { */
2887: /* printf("%.6e ",matcov[i][j]); */
2888: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2889: /* } */
2890: /* printf("\n"); */
2891: /* fprintf(ficlog,"\n"); */
2892: /* } */
2893:
2894: /* Recompute Inverse */
2895: /* for (i=1;i<=npar;i++) */
2896: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2897: /* ludcmp(a,npar,indx,&pd); */
2898:
2899: /* printf("\n#Hessian matrix recomputed#\n"); */
2900:
2901: /* for (j=1;j<=npar;j++) { */
2902: /* for (i=1;i<=npar;i++) x[i]=0; */
2903: /* x[j]=1; */
2904: /* lubksb(a,npar,indx,x); */
2905: /* for (i=1;i<=npar;i++){ */
2906: /* y[i][j]=x[i]; */
2907: /* printf("%.3e ",y[i][j]); */
2908: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2909: /* } */
2910: /* printf("\n"); */
2911: /* fprintf(ficlog,"\n"); */
2912: /* } */
2913:
2914: /* Verifying the inverse matrix */
2915: #ifdef DEBUGHESS
2916: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2917:
2918: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2919: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2920:
2921: for (j=1;j<=npar;j++) {
2922: for (i=1;i<=npar;i++){
2923: printf("%.2f ",y[i][j]);
2924: fprintf(ficlog,"%.2f ",y[i][j]);
2925: }
2926: printf("\n");
2927: fprintf(ficlog,"\n");
2928: }
2929: #endif
2930:
2931: free_matrix(a,1,npar,1,npar);
2932: free_matrix(y,1,npar,1,npar);
2933: free_vector(x,1,npar);
2934: free_ivector(indx,1,npar);
2935: /* free_matrix(hess,1,npar,1,npar); */
2936:
2937:
2938: }
2939:
2940: /*************** hessian matrix ****************/
2941: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2942: { /* Around values of x, computes the function func and returns the scales delti and hessian */
2943: int i;
2944: int l=1, lmax=20;
2945: double k1,k2, res, fx;
2946: double p2[MAXPARM+1]; /* identical to x */
2947: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2948: int k=0,kmax=10;
2949: double l1;
2950:
2951: fx=func(x);
2952: for (i=1;i<=npar;i++) p2[i]=x[i];
2953: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2954: l1=pow(10,l);
2955: delts=delt;
2956: for(k=1 ; k <kmax; k=k+1){
2957: delt = delta*(l1*k);
2958: p2[theta]=x[theta] +delt;
2959: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2960: p2[theta]=x[theta]-delt;
2961: k2=func(p2)-fx;
2962: /*res= (k1-2.0*fx+k2)/delt/delt; */
2963: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
2964:
2965: #ifdef DEBUGHESSII
2966: 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);
2967: 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);
2968: #endif
2969: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2970: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2971: k=kmax;
2972: }
2973: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2974: k=kmax; l=lmax*10;
2975: }
2976: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2977: delts=delt;
2978: }
2979: } /* End loop k */
2980: }
2981: delti[theta]=delts;
2982: return res;
2983:
2984: }
2985:
2986: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2987: {
2988: int i;
2989: int l=1, lmax=20;
2990: double k1,k2,k3,k4,res,fx;
2991: double p2[MAXPARM+1];
2992: int k, kmax=1;
2993: double v1, v2, cv12, lc1, lc2;
2994:
2995: int firstime=0;
2996:
2997: fx=func(x);
2998: for (k=1; k<=kmax; k=k+10) {
2999: for (i=1;i<=npar;i++) p2[i]=x[i];
3000: p2[thetai]=x[thetai]+delti[thetai]*k;
3001: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3002: k1=func(p2)-fx;
3003:
3004: p2[thetai]=x[thetai]+delti[thetai]*k;
3005: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3006: k2=func(p2)-fx;
3007:
3008: p2[thetai]=x[thetai]-delti[thetai]*k;
3009: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3010: k3=func(p2)-fx;
3011:
3012: p2[thetai]=x[thetai]-delti[thetai]*k;
3013: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3014: k4=func(p2)-fx;
3015: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3016: if(k1*k2*k3*k4 <0.){
3017: firstime=1;
3018: kmax=kmax+10;
3019: }
3020: if(kmax >=10 || firstime ==1){
3021: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3022: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3023: 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);
3024: 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);
3025: }
3026: #ifdef DEBUGHESSIJ
3027: v1=hess[thetai][thetai];
3028: v2=hess[thetaj][thetaj];
3029: cv12=res;
3030: /* Computing eigen value of Hessian matrix */
3031: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3032: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3033: if ((lc2 <0) || (lc1 <0) ){
3034: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3035: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3036: 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);
3037: 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);
3038: }
3039: #endif
3040: }
3041: return res;
3042: }
3043:
3044: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3045: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3046: /* { */
3047: /* int i; */
3048: /* int l=1, lmax=20; */
3049: /* double k1,k2,k3,k4,res,fx; */
3050: /* double p2[MAXPARM+1]; */
3051: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3052: /* int k=0,kmax=10; */
3053: /* double l1; */
3054:
3055: /* fx=func(x); */
3056: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3057: /* l1=pow(10,l); */
3058: /* delts=delt; */
3059: /* for(k=1 ; k <kmax; k=k+1){ */
3060: /* delt = delti*(l1*k); */
3061: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3062: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3063: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3064: /* k1=func(p2)-fx; */
3065:
3066: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3067: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3068: /* k2=func(p2)-fx; */
3069:
3070: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3071: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3072: /* k3=func(p2)-fx; */
3073:
3074: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3075: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3076: /* k4=func(p2)-fx; */
3077: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3078: /* #ifdef DEBUGHESSIJ */
3079: /* 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); */
3080: /* 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); */
3081: /* #endif */
3082: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3083: /* k=kmax; */
3084: /* } */
3085: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3086: /* k=kmax; l=lmax*10; */
3087: /* } */
3088: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3089: /* delts=delt; */
3090: /* } */
3091: /* } /\* End loop k *\/ */
3092: /* } */
3093: /* delti[theta]=delts; */
3094: /* return res; */
3095: /* } */
3096:
3097:
3098: /************** Inverse of matrix **************/
3099: void ludcmp(double **a, int n, int *indx, double *d)
3100: {
3101: int i,imax,j,k;
3102: double big,dum,sum,temp;
3103: double *vv;
3104:
3105: vv=vector(1,n);
3106: *d=1.0;
3107: for (i=1;i<=n;i++) {
3108: big=0.0;
3109: for (j=1;j<=n;j++)
3110: if ((temp=fabs(a[i][j])) > big) big=temp;
3111: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3112: vv[i]=1.0/big;
3113: }
3114: for (j=1;j<=n;j++) {
3115: for (i=1;i<j;i++) {
3116: sum=a[i][j];
3117: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3118: a[i][j]=sum;
3119: }
3120: big=0.0;
3121: for (i=j;i<=n;i++) {
3122: sum=a[i][j];
3123: for (k=1;k<j;k++)
3124: sum -= a[i][k]*a[k][j];
3125: a[i][j]=sum;
3126: if ( (dum=vv[i]*fabs(sum)) >= big) {
3127: big=dum;
3128: imax=i;
3129: }
3130: }
3131: if (j != imax) {
3132: for (k=1;k<=n;k++) {
3133: dum=a[imax][k];
3134: a[imax][k]=a[j][k];
3135: a[j][k]=dum;
3136: }
3137: *d = -(*d);
3138: vv[imax]=vv[j];
3139: }
3140: indx[j]=imax;
3141: if (a[j][j] == 0.0) a[j][j]=TINY;
3142: if (j != n) {
3143: dum=1.0/(a[j][j]);
3144: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3145: }
3146: }
3147: free_vector(vv,1,n); /* Doesn't work */
3148: ;
3149: }
3150:
3151: void lubksb(double **a, int n, int *indx, double b[])
3152: {
3153: int i,ii=0,ip,j;
3154: double sum;
3155:
3156: for (i=1;i<=n;i++) {
3157: ip=indx[i];
3158: sum=b[ip];
3159: b[ip]=b[i];
3160: if (ii)
3161: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3162: else if (sum) ii=i;
3163: b[i]=sum;
3164: }
3165: for (i=n;i>=1;i--) {
3166: sum=b[i];
3167: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3168: b[i]=sum/a[i][i];
3169: }
3170: }
3171:
3172: void pstamp(FILE *fichier)
3173: {
3174: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3175: }
3176:
3177: /************ Frequencies ********************/
3178: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
3179: { /* Some frequencies */
3180:
3181: int i, m, jk, j1, bool, z1,j;
3182: int first;
3183: double ***freq; /* Frequencies */
3184: double *pp, **prop;
3185: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3186: char fileresp[FILENAMELENGTH];
3187:
3188: pp=vector(1,nlstate);
3189: prop=matrix(1,nlstate,iagemin,iagemax+3);
3190: strcpy(fileresp,"P_");
3191: strcat(fileresp,fileresu);
3192: if((ficresp=fopen(fileresp,"w"))==NULL) {
3193: printf("Problem with prevalence resultfile: %s\n", fileresp);
3194: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3195: exit(0);
3196: }
3197: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3198: j1=0;
3199:
3200: j=cptcoveff;
3201: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3202:
3203: first=1;
3204:
3205: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
3206: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
3207: /* j1++; */
3208: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
3209: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3210: scanf("%d", i);*/
3211: for (i=-5; i<=nlstate+ndeath; i++)
3212: for (jk=-5; jk<=nlstate+ndeath; jk++)
3213: for(m=iagemin; m <= iagemax+3; m++)
3214: freq[i][jk][m]=0;
3215:
3216: for (i=1; i<=nlstate; i++)
3217: for(m=iagemin; m <= iagemax+3; m++)
3218: prop[i][m]=0;
3219:
3220: dateintsum=0;
3221: k2cpt=0;
3222: for (i=1; i<=imx; i++) {
3223: bool=1;
3224: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3225: for (z1=1; z1<=cptcoveff; z1++)
3226: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3227: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3228: bool=0;
3229: /* 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",
3230: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3231: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3232: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3233: }
3234: }
3235:
3236: if (bool==1){
3237: for(m=firstpass; m<=lastpass; m++){
3238: k2=anint[m][i]+(mint[m][i]/12.);
3239: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3240: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3241: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3242: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
3243: if (m<lastpass) {
3244: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
3245: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
3246: }
3247:
3248: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
3249: dateintsum=dateintsum+k2;
3250: k2cpt++;
3251: }
3252: /*}*/
3253: }
3254: }
3255: } /* end i */
3256:
3257: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3258: pstamp(ficresp);
3259: if (cptcovn>0) {
3260: fprintf(ficresp, "\n#********** Variable ");
3261: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3262: fprintf(ficresp, "**********\n#");
3263: fprintf(ficlog, "\n#********** Variable ");
3264: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3265: fprintf(ficlog, "**********\n#");
3266: }
3267: for(i=1; i<=nlstate;i++)
3268: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3269: fprintf(ficresp, "\n");
3270:
3271: for(i=iagemin; i <= iagemax+3; i++){
3272: if(i==iagemax+3){
3273: fprintf(ficlog,"Total");
3274: }else{
3275: if(first==1){
3276: first=0;
3277: printf("See log file for details...\n");
3278: }
3279: fprintf(ficlog,"Age %d", i);
3280: }
3281: for(jk=1; jk <=nlstate ; jk++){
3282: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3283: pp[jk] += freq[jk][m][i];
3284: }
3285: for(jk=1; jk <=nlstate ; jk++){
3286: for(m=-1, pos=0; m <=0 ; m++)
3287: pos += freq[jk][m][i];
3288: if(pp[jk]>=1.e-10){
3289: if(first==1){
3290: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3291: }
3292: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3293: }else{
3294: if(first==1)
3295: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3296: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3297: }
3298: }
3299:
3300: for(jk=1; jk <=nlstate ; jk++){
3301: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3302: pp[jk] += freq[jk][m][i];
3303: }
3304: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3305: pos += pp[jk];
3306: posprop += prop[jk][i];
3307: }
3308: for(jk=1; jk <=nlstate ; jk++){
3309: if(pos>=1.e-5){
3310: if(first==1)
3311: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3312: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3313: }else{
3314: if(first==1)
3315: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3316: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3317: }
3318: if( i <= iagemax){
3319: if(pos>=1.e-5){
3320: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3321: /*probs[i][jk][j1]= pp[jk]/pos;*/
3322: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3323: }
3324: else
3325: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3326: }
3327: }
3328:
3329: for(jk=-1; jk <=nlstate+ndeath; jk++)
3330: for(m=-1; m <=nlstate+ndeath; m++)
3331: if(freq[jk][m][i] !=0 ) {
3332: if(first==1)
3333: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3334: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3335: }
3336: if(i <= iagemax)
3337: fprintf(ficresp,"\n");
3338: if(first==1)
3339: printf("Others in log...\n");
3340: fprintf(ficlog,"\n");
3341: }
3342: /*}*/
3343: }
3344: dateintmean=dateintsum/k2cpt;
3345:
3346: fclose(ficresp);
3347: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3348: free_vector(pp,1,nlstate);
3349: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3350: /* End of Freq */
3351: }
3352:
3353: /************ Prevalence ********************/
3354: 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)
3355: {
3356: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3357: in each health status at the date of interview (if between dateprev1 and dateprev2).
3358: We still use firstpass and lastpass as another selection.
3359: */
3360:
3361: int i, m, jk, j1, bool, z1,j;
3362:
3363: double **prop;
3364: double posprop;
3365: double y2; /* in fractional years */
3366: int iagemin, iagemax;
3367: int first; /** to stop verbosity which is redirected to log file */
3368:
3369: iagemin= (int) agemin;
3370: iagemax= (int) agemax;
3371: /*pp=vector(1,nlstate);*/
3372: prop=matrix(1,nlstate,iagemin,iagemax+3);
3373: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3374: j1=0;
3375:
3376: /*j=cptcoveff;*/
3377: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3378:
3379: first=1;
3380: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3381: /*for(i1=1; i1<=ncodemax[k1];i1++){
3382: j1++;*/
3383:
3384: for (i=1; i<=nlstate; i++)
3385: for(m=iagemin; m <= iagemax+3; m++)
3386: prop[i][m]=0.0;
3387:
3388: for (i=1; i<=imx; i++) { /* Each individual */
3389: bool=1;
3390: if (cptcovn>0) {
3391: for (z1=1; z1<=cptcoveff; z1++)
3392: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3393: bool=0;
3394: }
3395: if (bool==1) {
3396: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
3397: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3398: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3399: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3400: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3401: 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);
3402: if (s[m][i]>0 && s[m][i]<=nlstate) {
3403: /*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]]);*/
3404: prop[s[m][i]][(int)agev[m][i]] += weight[i];
3405: prop[s[m][i]][iagemax+3] += weight[i];
3406: }
3407: }
3408: } /* end selection of waves */
3409: }
3410: }
3411: for(i=iagemin; i <= iagemax+3; i++){
3412: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3413: posprop += prop[jk][i];
3414: }
3415:
3416: for(jk=1; jk <=nlstate ; jk++){
3417: if( i <= iagemax){
3418: if(posprop>=1.e-5){
3419: probs[i][jk][j1]= prop[jk][i]/posprop;
3420: } else{
3421: if(first==1){
3422: first=0;
3423: 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]);
3424: }
3425: }
3426: }
3427: }/* end jk */
3428: }/* end i */
3429: /*} *//* end i1 */
3430: } /* end j1 */
3431:
3432: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3433: /*free_vector(pp,1,nlstate);*/
3434: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3435: } /* End of prevalence */
3436:
3437: /************* Waves Concatenation ***************/
3438:
3439: 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)
3440: {
3441: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3442: Death is a valid wave (if date is known).
3443: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3444: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3445: and mw[mi+1][i]. dh depends on stepm.
3446: */
3447:
3448: int i, mi, m;
3449: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3450: double sum=0., jmean=0.;*/
3451: int first;
3452: int j, k=0,jk, ju, jl;
3453: double sum=0.;
3454: first=0;
3455: jmin=100000;
3456: jmax=-1;
3457: jmean=0.;
3458: for(i=1; i<=imx; i++){
3459: mi=0;
3460: m=firstpass;
3461: while(s[m][i] <= nlstate){
3462: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3463: mw[++mi][i]=m;
3464: if(m >=lastpass)
3465: break;
3466: else
3467: m++;
3468: }/* end while */
3469: if (s[m][i] > nlstate){
3470: mi++; /* Death is another wave */
3471: /* if(mi==0) never been interviewed correctly before death */
3472: /* Only death is a correct wave */
3473: mw[mi][i]=m;
3474: }
3475:
3476: wav[i]=mi;
3477: if(mi==0){
3478: nbwarn++;
3479: if(first==0){
3480: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3481: first=1;
3482: }
3483: if(first==1){
3484: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3485: }
3486: } /* end mi==0 */
3487: } /* End individuals */
3488:
3489: for(i=1; i<=imx; i++){
3490: for(mi=1; mi<wav[i];mi++){
3491: if (stepm <=0)
3492: dh[mi][i]=1;
3493: else{
3494: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3495: if (agedc[i] < 2*AGESUP) {
3496: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3497: if(j==0) j=1; /* Survives at least one month after exam */
3498: else if(j<0){
3499: nberr++;
3500: 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]);
3501: j=1; /* Temporary Dangerous patch */
3502: 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);
3503: 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]);
3504: 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);
3505: }
3506: k=k+1;
3507: if (j >= jmax){
3508: jmax=j;
3509: ijmax=i;
3510: }
3511: if (j <= jmin){
3512: jmin=j;
3513: ijmin=i;
3514: }
3515: sum=sum+j;
3516: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3517: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3518: }
3519: }
3520: else{
3521: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3522: /* 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]); */
3523:
3524: k=k+1;
3525: if (j >= jmax) {
3526: jmax=j;
3527: ijmax=i;
3528: }
3529: else if (j <= jmin){
3530: jmin=j;
3531: ijmin=i;
3532: }
3533: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3534: /*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]);*/
3535: if(j<0){
3536: nberr++;
3537: 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]);
3538: 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]);
3539: }
3540: sum=sum+j;
3541: }
3542: jk= j/stepm;
3543: jl= j -jk*stepm;
3544: ju= j -(jk+1)*stepm;
3545: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3546: if(jl==0){
3547: dh[mi][i]=jk;
3548: bh[mi][i]=0;
3549: }else{ /* We want a negative bias in order to only have interpolation ie
3550: * to avoid the price of an extra matrix product in likelihood */
3551: dh[mi][i]=jk+1;
3552: bh[mi][i]=ju;
3553: }
3554: }else{
3555: if(jl <= -ju){
3556: dh[mi][i]=jk;
3557: bh[mi][i]=jl; /* bias is positive if real duration
3558: * is higher than the multiple of stepm and negative otherwise.
3559: */
3560: }
3561: else{
3562: dh[mi][i]=jk+1;
3563: bh[mi][i]=ju;
3564: }
3565: if(dh[mi][i]==0){
3566: dh[mi][i]=1; /* At least one step */
3567: bh[mi][i]=ju; /* At least one step */
3568: /* 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);*/
3569: }
3570: } /* end if mle */
3571: }
3572: } /* end wave */
3573: }
3574: jmean=sum/k;
3575: 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);
3576: 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);
3577: }
3578:
3579: /*********** Tricode ****************************/
3580: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3581: {
3582: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3583: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3584: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3585: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3586: * nbcode[Tvar[j]][1]=
3587: */
3588:
3589: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3590: int modmaxcovj=0; /* Modality max of covariates j */
3591: int cptcode=0; /* Modality max of covariates j */
3592: int modmincovj=0; /* Modality min of covariates j */
3593:
3594:
3595: cptcoveff=0;
3596:
3597: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3598:
3599: /* Loop on covariates without age and products */
3600: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3601: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3602: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3603: modality of this covariate Vj*/
3604: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3605: * If product of Vn*Vm, still boolean *:
3606: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3607: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3608: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3609: modality of the nth covariate of individual i. */
3610: if (ij > modmaxcovj)
3611: modmaxcovj=ij;
3612: else if (ij < modmincovj)
3613: modmincovj=ij;
3614: if ((ij < -1) && (ij > NCOVMAX)){
3615: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3616: exit(1);
3617: }else
3618: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3619: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3620: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3621: /* getting the maximum value of the modality of the covariate
3622: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3623: female is 1, then modmaxcovj=1.*/
3624: } /* end for loop on individuals i */
3625: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3626: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3627: cptcode=modmaxcovj;
3628: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3629: /*for (i=0; i<=cptcode; i++) {*/
3630: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3631: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3632: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3633: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3634: if( k != -1){
3635: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3636: covariate for which somebody answered excluding
3637: undefined. Usually 2: 0 and 1. */
3638: }
3639: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3640: covariate for which somebody answered including
3641: undefined. Usually 3: -1, 0 and 1. */
3642: }
3643: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3644: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3645: } /* Ndum[-1] number of undefined modalities */
3646:
3647: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3648: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3649: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3650: modmincovj=3; modmaxcovj = 7;
3651: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3652: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3653: defining two dummy variables: variables V1_1 and V1_2.
3654: nbcode[Tvar[j]][ij]=k;
3655: nbcode[Tvar[j]][1]=0;
3656: nbcode[Tvar[j]][2]=1;
3657: nbcode[Tvar[j]][3]=2;
3658: To be continued (not working yet).
3659: */
3660: ij=0; /* ij is similar to i but can jump over null modalities */
3661: 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*/
3662: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3663: break;
3664: }
3665: ij++;
3666: 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.*/
3667: cptcode = ij; /* New max modality for covar j */
3668: } /* end of loop on modality i=-1 to 1 or more */
3669:
3670: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3671: /* /\*recode from 0 *\/ */
3672: /* k is a modality. If we have model=V1+V1*sex */
3673: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3674: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3675: /* } */
3676: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3677: /* if (ij > ncodemax[j]) { */
3678: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3679: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3680: /* break; */
3681: /* } */
3682: /* } /\* end of loop on modality k *\/ */
3683: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3684:
3685: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3686:
3687: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3688: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3689: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3690: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3691: }
3692:
3693: ij=0;
3694: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3695: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3696: if((Ndum[i]!=0) && (i<=ncovcol)){
3697: ij++;
3698: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3699: Tvaraff[ij]=i; /*For printing (unclear) */
3700: }else{
3701: /* Tvaraff[ij]=0; */
3702: }
3703: }
3704: /* ij--; */
3705: cptcoveff=ij; /*Number of total covariates*/
3706:
3707: }
3708:
3709:
3710: /*********** Health Expectancies ****************/
3711:
3712: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3713:
3714: {
3715: /* Health expectancies, no variances */
3716: int i, j, nhstepm, hstepm, h, nstepm;
3717: int nhstepma, nstepma; /* Decreasing with age */
3718: double age, agelim, hf;
3719: double ***p3mat;
3720: double eip;
3721:
3722: pstamp(ficreseij);
3723: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3724: fprintf(ficreseij,"# Age");
3725: for(i=1; i<=nlstate;i++){
3726: for(j=1; j<=nlstate;j++){
3727: fprintf(ficreseij," e%1d%1d ",i,j);
3728: }
3729: fprintf(ficreseij," e%1d. ",i);
3730: }
3731: fprintf(ficreseij,"\n");
3732:
3733:
3734: if(estepm < stepm){
3735: printf ("Problem %d lower than %d\n",estepm, stepm);
3736: }
3737: else hstepm=estepm;
3738: /* We compute the life expectancy from trapezoids spaced every estepm months
3739: * This is mainly to measure the difference between two models: for example
3740: * if stepm=24 months pijx are given only every 2 years and by summing them
3741: * we are calculating an estimate of the Life Expectancy assuming a linear
3742: * progression in between and thus overestimating or underestimating according
3743: * to the curvature of the survival function. If, for the same date, we
3744: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3745: * to compare the new estimate of Life expectancy with the same linear
3746: * hypothesis. A more precise result, taking into account a more precise
3747: * curvature will be obtained if estepm is as small as stepm. */
3748:
3749: /* For example we decided to compute the life expectancy with the smallest unit */
3750: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3751: nhstepm is the number of hstepm from age to agelim
3752: nstepm is the number of stepm from age to agelin.
3753: Look at hpijx to understand the reason of that which relies in memory size
3754: and note for a fixed period like estepm months */
3755: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3756: survival function given by stepm (the optimization length). Unfortunately it
3757: means that if the survival funtion is printed only each two years of age and if
3758: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3759: results. So we changed our mind and took the option of the best precision.
3760: */
3761: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3762:
3763: agelim=AGESUP;
3764: /* If stepm=6 months */
3765: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3766: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3767:
3768: /* nhstepm age range expressed in number of stepm */
3769: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3770: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3771: /* if (stepm >= YEARM) hstepm=1;*/
3772: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3773: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3774:
3775: for (age=bage; age<=fage; age ++){
3776: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3777: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3778: /* if (stepm >= YEARM) hstepm=1;*/
3779: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3780:
3781: /* If stepm=6 months */
3782: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3783: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3784:
3785: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3786:
3787: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3788:
3789: printf("%d|",(int)age);fflush(stdout);
3790: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3791:
3792: /* Computing expectancies */
3793: for(i=1; i<=nlstate;i++)
3794: for(j=1; j<=nlstate;j++)
3795: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3796: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3797:
3798: /* 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]);*/
3799:
3800: }
3801:
3802: fprintf(ficreseij,"%3.0f",age );
3803: for(i=1; i<=nlstate;i++){
3804: eip=0;
3805: for(j=1; j<=nlstate;j++){
3806: eip +=eij[i][j][(int)age];
3807: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3808: }
3809: fprintf(ficreseij,"%9.4f", eip );
3810: }
3811: fprintf(ficreseij,"\n");
3812:
3813: }
3814: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3815: printf("\n");
3816: fprintf(ficlog,"\n");
3817:
3818: }
3819:
3820: 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[] )
3821:
3822: {
3823: /* Covariances of health expectancies eij and of total life expectancies according
3824: to initial status i, ei. .
3825: */
3826: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3827: int nhstepma, nstepma; /* Decreasing with age */
3828: double age, agelim, hf;
3829: double ***p3matp, ***p3matm, ***varhe;
3830: double **dnewm,**doldm;
3831: double *xp, *xm;
3832: double **gp, **gm;
3833: double ***gradg, ***trgradg;
3834: int theta;
3835:
3836: double eip, vip;
3837:
3838: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3839: xp=vector(1,npar);
3840: xm=vector(1,npar);
3841: dnewm=matrix(1,nlstate*nlstate,1,npar);
3842: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3843:
3844: pstamp(ficresstdeij);
3845: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3846: fprintf(ficresstdeij,"# Age");
3847: for(i=1; i<=nlstate;i++){
3848: for(j=1; j<=nlstate;j++)
3849: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3850: fprintf(ficresstdeij," e%1d. ",i);
3851: }
3852: fprintf(ficresstdeij,"\n");
3853:
3854: pstamp(ficrescveij);
3855: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3856: fprintf(ficrescveij,"# Age");
3857: for(i=1; i<=nlstate;i++)
3858: for(j=1; j<=nlstate;j++){
3859: cptj= (j-1)*nlstate+i;
3860: for(i2=1; i2<=nlstate;i2++)
3861: for(j2=1; j2<=nlstate;j2++){
3862: cptj2= (j2-1)*nlstate+i2;
3863: if(cptj2 <= cptj)
3864: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3865: }
3866: }
3867: fprintf(ficrescveij,"\n");
3868:
3869: if(estepm < stepm){
3870: printf ("Problem %d lower than %d\n",estepm, stepm);
3871: }
3872: else hstepm=estepm;
3873: /* We compute the life expectancy from trapezoids spaced every estepm months
3874: * This is mainly to measure the difference between two models: for example
3875: * if stepm=24 months pijx are given only every 2 years and by summing them
3876: * we are calculating an estimate of the Life Expectancy assuming a linear
3877: * progression in between and thus overestimating or underestimating according
3878: * to the curvature of the survival function. If, for the same date, we
3879: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3880: * to compare the new estimate of Life expectancy with the same linear
3881: * hypothesis. A more precise result, taking into account a more precise
3882: * curvature will be obtained if estepm is as small as stepm. */
3883:
3884: /* For example we decided to compute the life expectancy with the smallest unit */
3885: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3886: nhstepm is the number of hstepm from age to agelim
3887: nstepm is the number of stepm from age to agelin.
3888: Look at hpijx to understand the reason of that which relies in memory size
3889: and note for a fixed period like estepm months */
3890: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3891: survival function given by stepm (the optimization length). Unfortunately it
3892: means that if the survival funtion is printed only each two years of age and if
3893: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3894: results. So we changed our mind and took the option of the best precision.
3895: */
3896: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3897:
3898: /* If stepm=6 months */
3899: /* nhstepm age range expressed in number of stepm */
3900: agelim=AGESUP;
3901: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3902: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3903: /* if (stepm >= YEARM) hstepm=1;*/
3904: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3905:
3906: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3907: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3908: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3909: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3910: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3911: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3912:
3913: for (age=bage; age<=fage; age ++){
3914: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3915: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3916: /* if (stepm >= YEARM) hstepm=1;*/
3917: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3918:
3919: /* If stepm=6 months */
3920: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3921: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3922:
3923: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3924:
3925: /* Computing Variances of health expectancies */
3926: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3927: decrease memory allocation */
3928: for(theta=1; theta <=npar; theta++){
3929: for(i=1; i<=npar; i++){
3930: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3931: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3932: }
3933: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3934: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3935:
3936: for(j=1; j<= nlstate; j++){
3937: for(i=1; i<=nlstate; i++){
3938: for(h=0; h<=nhstepm-1; h++){
3939: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3940: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3941: }
3942: }
3943: }
3944:
3945: for(ij=1; ij<= nlstate*nlstate; ij++)
3946: for(h=0; h<=nhstepm-1; h++){
3947: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3948: }
3949: }/* End theta */
3950:
3951:
3952: for(h=0; h<=nhstepm-1; h++)
3953: for(j=1; j<=nlstate*nlstate;j++)
3954: for(theta=1; theta <=npar; theta++)
3955: trgradg[h][j][theta]=gradg[h][theta][j];
3956:
3957:
3958: for(ij=1;ij<=nlstate*nlstate;ij++)
3959: for(ji=1;ji<=nlstate*nlstate;ji++)
3960: varhe[ij][ji][(int)age] =0.;
3961:
3962: printf("%d|",(int)age);fflush(stdout);
3963: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3964: for(h=0;h<=nhstepm-1;h++){
3965: for(k=0;k<=nhstepm-1;k++){
3966: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3967: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3968: for(ij=1;ij<=nlstate*nlstate;ij++)
3969: for(ji=1;ji<=nlstate*nlstate;ji++)
3970: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3971: }
3972: }
3973:
3974: /* Computing expectancies */
3975: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3976: for(i=1; i<=nlstate;i++)
3977: for(j=1; j<=nlstate;j++)
3978: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3979: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3980:
3981: /* 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]);*/
3982:
3983: }
3984:
3985: fprintf(ficresstdeij,"%3.0f",age );
3986: for(i=1; i<=nlstate;i++){
3987: eip=0.;
3988: vip=0.;
3989: for(j=1; j<=nlstate;j++){
3990: eip += eij[i][j][(int)age];
3991: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3992: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3993: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3994: }
3995: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3996: }
3997: fprintf(ficresstdeij,"\n");
3998:
3999: fprintf(ficrescveij,"%3.0f",age );
4000: for(i=1; i<=nlstate;i++)
4001: for(j=1; j<=nlstate;j++){
4002: cptj= (j-1)*nlstate+i;
4003: for(i2=1; i2<=nlstate;i2++)
4004: for(j2=1; j2<=nlstate;j2++){
4005: cptj2= (j2-1)*nlstate+i2;
4006: if(cptj2 <= cptj)
4007: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4008: }
4009: }
4010: fprintf(ficrescveij,"\n");
4011:
4012: }
4013: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4014: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4015: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4016: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4017: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4018: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4019: printf("\n");
4020: fprintf(ficlog,"\n");
4021:
4022: free_vector(xm,1,npar);
4023: free_vector(xp,1,npar);
4024: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4025: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4026: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4027: }
4028:
4029: /************ Variance ******************/
4030: 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[])
4031: {
4032: /* Variance of health expectancies */
4033: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4034: /* double **newm;*/
4035: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4036:
4037: int movingaverage();
4038: double **dnewm,**doldm;
4039: double **dnewmp,**doldmp;
4040: int i, j, nhstepm, hstepm, h, nstepm ;
4041: int k;
4042: double *xp;
4043: double **gp, **gm; /* for var eij */
4044: double ***gradg, ***trgradg; /*for var eij */
4045: double **gradgp, **trgradgp; /* for var p point j */
4046: double *gpp, *gmp; /* for var p point j */
4047: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4048: double ***p3mat;
4049: double age,agelim, hf;
4050: double ***mobaverage;
4051: int theta;
4052: char digit[4];
4053: char digitp[25];
4054:
4055: char fileresprobmorprev[FILENAMELENGTH];
4056:
4057: if(popbased==1){
4058: if(mobilav!=0)
4059: strcpy(digitp,"-POPULBASED-MOBILAV_");
4060: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4061: }
4062: else
4063: strcpy(digitp,"-STABLBASED_");
4064:
4065: if (mobilav!=0) {
4066: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4067: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4068: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4069: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4070: }
4071: }
4072:
4073: strcpy(fileresprobmorprev,"PRMORPREV-");
4074: sprintf(digit,"%-d",ij);
4075: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4076: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4077: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4078: strcat(fileresprobmorprev,fileresu);
4079: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4080: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4081: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4082: }
4083: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4084: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4085: pstamp(ficresprobmorprev);
4086: 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);
4087: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4088: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4089: fprintf(ficresprobmorprev," p.%-d SE",j);
4090: for(i=1; i<=nlstate;i++)
4091: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4092: }
4093: fprintf(ficresprobmorprev,"\n");
4094:
4095: fprintf(ficgp,"\n# Routine varevsij");
4096: fprintf(ficgp,"\nunset title \n");
4097: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4098: 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");
4099: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4100: /* } */
4101: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4102: pstamp(ficresvij);
4103: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4104: if(popbased==1)
4105: 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);
4106: else
4107: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4108: fprintf(ficresvij,"# Age");
4109: for(i=1; i<=nlstate;i++)
4110: for(j=1; j<=nlstate;j++)
4111: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4112: fprintf(ficresvij,"\n");
4113:
4114: xp=vector(1,npar);
4115: dnewm=matrix(1,nlstate,1,npar);
4116: doldm=matrix(1,nlstate,1,nlstate);
4117: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4118: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4119:
4120: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4121: gpp=vector(nlstate+1,nlstate+ndeath);
4122: gmp=vector(nlstate+1,nlstate+ndeath);
4123: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4124:
4125: if(estepm < stepm){
4126: printf ("Problem %d lower than %d\n",estepm, stepm);
4127: }
4128: else hstepm=estepm;
4129: /* For example we decided to compute the life expectancy with the smallest unit */
4130: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4131: nhstepm is the number of hstepm from age to agelim
4132: nstepm is the number of stepm from age to agelim.
4133: Look at function hpijx to understand why because of memory size limitations,
4134: we decided (b) to get a life expectancy respecting the most precise curvature of the
4135: survival function given by stepm (the optimization length). Unfortunately it
4136: means that if the survival funtion is printed every two years of age and if
4137: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4138: results. So we changed our mind and took the option of the best precision.
4139: */
4140: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4141: agelim = AGESUP;
4142: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4143: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4144: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4145: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4146: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4147: gp=matrix(0,nhstepm,1,nlstate);
4148: gm=matrix(0,nhstepm,1,nlstate);
4149:
4150:
4151: for(theta=1; theta <=npar; theta++){
4152: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4153: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4154: }
4155:
4156: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4157:
4158: if (popbased==1) {
4159: if(mobilav ==0){
4160: for(i=1; i<=nlstate;i++)
4161: prlim[i][i]=probs[(int)age][i][ij];
4162: }else{ /* mobilav */
4163: for(i=1; i<=nlstate;i++)
4164: prlim[i][i]=mobaverage[(int)age][i][ij];
4165: }
4166: }
4167:
4168: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
4169: for(j=1; j<= nlstate; j++){
4170: for(h=0; h<=nhstepm; h++){
4171: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4172: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4173: }
4174: }
4175: /* Next for computing probability of death (h=1 means
4176: computed over hstepm matrices product = hstepm*stepm months)
4177: as a weighted average of prlim.
4178: */
4179: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4180: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4181: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4182: }
4183: /* end probability of death */
4184:
4185: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4186: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4187:
4188: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
4189:
4190: if (popbased==1) {
4191: if(mobilav ==0){
4192: for(i=1; i<=nlstate;i++)
4193: prlim[i][i]=probs[(int)age][i][ij];
4194: }else{ /* mobilav */
4195: for(i=1; i<=nlstate;i++)
4196: prlim[i][i]=mobaverage[(int)age][i][ij];
4197: }
4198: }
4199:
4200: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4201:
4202: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4203: for(h=0; h<=nhstepm; h++){
4204: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4205: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4206: }
4207: }
4208: /* This for computing probability of death (h=1 means
4209: computed over hstepm matrices product = hstepm*stepm months)
4210: as a weighted average of prlim.
4211: */
4212: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4213: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4214: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4215: }
4216: /* end probability of death */
4217:
4218: for(j=1; j<= nlstate; j++) /* vareij */
4219: for(h=0; h<=nhstepm; h++){
4220: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4221: }
4222:
4223: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4224: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4225: }
4226:
4227: } /* End theta */
4228:
4229: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4230:
4231: for(h=0; h<=nhstepm; h++) /* veij */
4232: for(j=1; j<=nlstate;j++)
4233: for(theta=1; theta <=npar; theta++)
4234: trgradg[h][j][theta]=gradg[h][theta][j];
4235:
4236: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4237: for(theta=1; theta <=npar; theta++)
4238: trgradgp[j][theta]=gradgp[theta][j];
4239:
4240:
4241: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4242: for(i=1;i<=nlstate;i++)
4243: for(j=1;j<=nlstate;j++)
4244: vareij[i][j][(int)age] =0.;
4245:
4246: for(h=0;h<=nhstepm;h++){
4247: for(k=0;k<=nhstepm;k++){
4248: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4249: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4250: for(i=1;i<=nlstate;i++)
4251: for(j=1;j<=nlstate;j++)
4252: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4253: }
4254: }
4255:
4256: /* pptj */
4257: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4258: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4259: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4260: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4261: varppt[j][i]=doldmp[j][i];
4262: /* end ppptj */
4263: /* x centered again */
4264:
4265: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
4266:
4267: if (popbased==1) {
4268: if(mobilav ==0){
4269: for(i=1; i<=nlstate;i++)
4270: prlim[i][i]=probs[(int)age][i][ij];
4271: }else{ /* mobilav */
4272: for(i=1; i<=nlstate;i++)
4273: prlim[i][i]=mobaverage[(int)age][i][ij];
4274: }
4275: }
4276:
4277: /* This for computing probability of death (h=1 means
4278: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4279: as a weighted average of prlim.
4280: */
4281: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4282: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4283: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4284: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4285: }
4286: /* end probability of death */
4287:
4288: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4289: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4290: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4291: for(i=1; i<=nlstate;i++){
4292: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4293: }
4294: }
4295: fprintf(ficresprobmorprev,"\n");
4296:
4297: fprintf(ficresvij,"%.0f ",age );
4298: for(i=1; i<=nlstate;i++)
4299: for(j=1; j<=nlstate;j++){
4300: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4301: }
4302: fprintf(ficresvij,"\n");
4303: free_matrix(gp,0,nhstepm,1,nlstate);
4304: free_matrix(gm,0,nhstepm,1,nlstate);
4305: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4306: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4307: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4308: } /* End age */
4309: free_vector(gpp,nlstate+1,nlstate+ndeath);
4310: free_vector(gmp,nlstate+1,nlstate+ndeath);
4311: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4312: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4313: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4314: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4315: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4316: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4317: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4318: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4319: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4320: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4321: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4322: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4323: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4324: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4325: 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);
4326: /* 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);
4327: */
4328: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4329: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4330:
4331: free_vector(xp,1,npar);
4332: free_matrix(doldm,1,nlstate,1,nlstate);
4333: free_matrix(dnewm,1,nlstate,1,npar);
4334: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4335: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4336: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4337: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4338: fclose(ficresprobmorprev);
4339: fflush(ficgp);
4340: fflush(fichtm);
4341: } /* end varevsij */
4342:
4343: /************ Variance of prevlim ******************/
4344: 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[])
4345: {
4346: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4347: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4348:
4349: double **dnewm,**doldm;
4350: int i, j, nhstepm, hstepm;
4351: double *xp;
4352: double *gp, *gm;
4353: double **gradg, **trgradg;
4354: double **mgm, **mgp;
4355: double age,agelim;
4356: int theta;
4357:
4358: pstamp(ficresvpl);
4359: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4360: fprintf(ficresvpl,"# Age");
4361: for(i=1; i<=nlstate;i++)
4362: fprintf(ficresvpl," %1d-%1d",i,i);
4363: fprintf(ficresvpl,"\n");
4364:
4365: xp=vector(1,npar);
4366: dnewm=matrix(1,nlstate,1,npar);
4367: doldm=matrix(1,nlstate,1,nlstate);
4368:
4369: hstepm=1*YEARM; /* Every year of age */
4370: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4371: agelim = AGESUP;
4372: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4373: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4374: if (stepm >= YEARM) hstepm=1;
4375: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4376: gradg=matrix(1,npar,1,nlstate);
4377: mgp=matrix(1,npar,1,nlstate);
4378: mgm=matrix(1,npar,1,nlstate);
4379: gp=vector(1,nlstate);
4380: gm=vector(1,nlstate);
4381:
4382: for(theta=1; theta <=npar; theta++){
4383: for(i=1; i<=npar; i++){ /* Computes gradient */
4384: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4385: }
4386: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4387: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4388: else
4389: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4390: for(i=1;i<=nlstate;i++){
4391: gp[i] = prlim[i][i];
4392: mgp[theta][i] = prlim[i][i];
4393: }
4394: for(i=1; i<=npar; i++) /* Computes gradient */
4395: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4396: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4397: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4398: else
4399: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4400: for(i=1;i<=nlstate;i++){
4401: gm[i] = prlim[i][i];
4402: mgm[theta][i] = prlim[i][i];
4403: }
4404: for(i=1;i<=nlstate;i++)
4405: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4406: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
4407: } /* End theta */
4408:
4409: trgradg =matrix(1,nlstate,1,npar);
4410:
4411: for(j=1; j<=nlstate;j++)
4412: for(theta=1; theta <=npar; theta++)
4413: trgradg[j][theta]=gradg[theta][j];
4414: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4415: /* printf("\nmgm mgp %d ",(int)age); */
4416: /* for(j=1; j<=nlstate;j++){ */
4417: /* printf(" %d ",j); */
4418: /* for(theta=1; theta <=npar; theta++) */
4419: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4420: /* printf("\n "); */
4421: /* } */
4422: /* } */
4423: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4424: /* printf("\n gradg %d ",(int)age); */
4425: /* for(j=1; j<=nlstate;j++){ */
4426: /* printf("%d ",j); */
4427: /* for(theta=1; theta <=npar; theta++) */
4428: /* printf("%d %lf ",theta,gradg[theta][j]); */
4429: /* printf("\n "); */
4430: /* } */
4431: /* } */
4432:
4433: for(i=1;i<=nlstate;i++)
4434: varpl[i][(int)age] =0.;
4435: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
4436: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4437: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4438: }else{
4439: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4440: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4441: }
4442: for(i=1;i<=nlstate;i++)
4443: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4444:
4445: fprintf(ficresvpl,"%.0f ",age );
4446: for(i=1; i<=nlstate;i++)
4447: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4448: fprintf(ficresvpl,"\n");
4449: free_vector(gp,1,nlstate);
4450: free_vector(gm,1,nlstate);
4451: free_matrix(mgm,1,npar,1,nlstate);
4452: free_matrix(mgp,1,npar,1,nlstate);
4453: free_matrix(gradg,1,npar,1,nlstate);
4454: free_matrix(trgradg,1,nlstate,1,npar);
4455: } /* End age */
4456:
4457: free_vector(xp,1,npar);
4458: free_matrix(doldm,1,nlstate,1,npar);
4459: free_matrix(dnewm,1,nlstate,1,nlstate);
4460:
4461: }
4462:
4463: /************ Variance of one-step probabilities ******************/
4464: 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[])
4465: {
4466: int i, j=0, k1, l1, tj;
4467: int k2, l2, j1, z1;
4468: int k=0, l;
4469: int first=1, first1, first2;
4470: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4471: double **dnewm,**doldm;
4472: double *xp;
4473: double *gp, *gm;
4474: double **gradg, **trgradg;
4475: double **mu;
4476: double age, cov[NCOVMAX+1];
4477: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4478: int theta;
4479: char fileresprob[FILENAMELENGTH];
4480: char fileresprobcov[FILENAMELENGTH];
4481: char fileresprobcor[FILENAMELENGTH];
4482: double ***varpij;
4483:
4484: strcpy(fileresprob,"PROB_");
4485: strcat(fileresprob,fileres);
4486: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4487: printf("Problem with resultfile: %s\n", fileresprob);
4488: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4489: }
4490: strcpy(fileresprobcov,"PROBCOV_");
4491: strcat(fileresprobcov,fileresu);
4492: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4493: printf("Problem with resultfile: %s\n", fileresprobcov);
4494: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4495: }
4496: strcpy(fileresprobcor,"PROBCOR_");
4497: strcat(fileresprobcor,fileresu);
4498: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4499: printf("Problem with resultfile: %s\n", fileresprobcor);
4500: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4501: }
4502: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4503: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4504: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4505: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4506: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4507: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4508: pstamp(ficresprob);
4509: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4510: fprintf(ficresprob,"# Age");
4511: pstamp(ficresprobcov);
4512: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4513: fprintf(ficresprobcov,"# Age");
4514: pstamp(ficresprobcor);
4515: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4516: fprintf(ficresprobcor,"# Age");
4517:
4518:
4519: for(i=1; i<=nlstate;i++)
4520: for(j=1; j<=(nlstate+ndeath);j++){
4521: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4522: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4523: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4524: }
4525: /* fprintf(ficresprob,"\n");
4526: fprintf(ficresprobcov,"\n");
4527: fprintf(ficresprobcor,"\n");
4528: */
4529: xp=vector(1,npar);
4530: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4531: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4532: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4533: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4534: first=1;
4535: fprintf(ficgp,"\n# Routine varprob");
4536: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4537: fprintf(fichtm,"\n");
4538:
4539: 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);
4540: 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);
4541: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4542: and drawn. It helps understanding how is the covariance between two incidences.\
4543: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4544: 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. \
4545: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4546: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4547: standard deviations wide on each axis. <br>\
4548: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4549: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4550: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4551:
4552: cov[1]=1;
4553: /* tj=cptcoveff; */
4554: tj = (int) pow(2,cptcoveff);
4555: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4556: j1=0;
4557: for(j1=1; j1<=tj;j1++){
4558: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4559: /*j1++;*/
4560: if (cptcovn>0) {
4561: fprintf(ficresprob, "\n#********** Variable ");
4562: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4563: fprintf(ficresprob, "**********\n#\n");
4564: fprintf(ficresprobcov, "\n#********** Variable ");
4565: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4566: fprintf(ficresprobcov, "**********\n#\n");
4567:
4568: fprintf(ficgp, "\n#********** Variable ");
4569: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4570: fprintf(ficgp, "**********\n#\n");
4571:
4572:
4573: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4574: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4575: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4576:
4577: fprintf(ficresprobcor, "\n#********** Variable ");
4578: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4579: fprintf(ficresprobcor, "**********\n#");
4580: }
4581:
4582: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4583: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4584: gp=vector(1,(nlstate)*(nlstate+ndeath));
4585: gm=vector(1,(nlstate)*(nlstate+ndeath));
4586: for (age=bage; age<=fage; age ++){
4587: cov[2]=age;
4588: if(nagesqr==1)
4589: cov[3]= age*age;
4590: for (k=1; k<=cptcovn;k++) {
4591: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4592: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4593: * 1 1 1 1 1
4594: * 2 2 1 1 1
4595: * 3 1 2 1 1
4596: */
4597: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4598: }
4599: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4600: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4601: for (k=1; k<=cptcovprod;k++)
4602: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4603:
4604:
4605: for(theta=1; theta <=npar; theta++){
4606: for(i=1; i<=npar; i++)
4607: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4608:
4609: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4610:
4611: k=0;
4612: for(i=1; i<= (nlstate); i++){
4613: for(j=1; j<=(nlstate+ndeath);j++){
4614: k=k+1;
4615: gp[k]=pmmij[i][j];
4616: }
4617: }
4618:
4619: for(i=1; i<=npar; i++)
4620: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4621:
4622: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4623: k=0;
4624: for(i=1; i<=(nlstate); i++){
4625: for(j=1; j<=(nlstate+ndeath);j++){
4626: k=k+1;
4627: gm[k]=pmmij[i][j];
4628: }
4629: }
4630:
4631: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4632: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4633: }
4634:
4635: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4636: for(theta=1; theta <=npar; theta++)
4637: trgradg[j][theta]=gradg[theta][j];
4638:
4639: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4640: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4641:
4642: pmij(pmmij,cov,ncovmodel,x,nlstate);
4643:
4644: k=0;
4645: for(i=1; i<=(nlstate); i++){
4646: for(j=1; j<=(nlstate+ndeath);j++){
4647: k=k+1;
4648: mu[k][(int) age]=pmmij[i][j];
4649: }
4650: }
4651: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4652: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4653: varpij[i][j][(int)age] = doldm[i][j];
4654:
4655: /*printf("\n%d ",(int)age);
4656: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4657: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4658: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4659: }*/
4660:
4661: fprintf(ficresprob,"\n%d ",(int)age);
4662: fprintf(ficresprobcov,"\n%d ",(int)age);
4663: fprintf(ficresprobcor,"\n%d ",(int)age);
4664:
4665: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4666: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4667: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4668: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4669: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4670: }
4671: i=0;
4672: for (k=1; k<=(nlstate);k++){
4673: for (l=1; l<=(nlstate+ndeath);l++){
4674: i++;
4675: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4676: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4677: for (j=1; j<=i;j++){
4678: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4679: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4680: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4681: }
4682: }
4683: }/* end of loop for state */
4684: } /* end of loop for age */
4685: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4686: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4687: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4688: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4689:
4690: /* Confidence intervalle of pij */
4691: /*
4692: fprintf(ficgp,"\nunset parametric;unset label");
4693: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4694: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4695: 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);
4696: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4697: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4698: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4699: */
4700:
4701: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4702: first1=1;first2=2;
4703: for (k2=1; k2<=(nlstate);k2++){
4704: for (l2=1; l2<=(nlstate+ndeath);l2++){
4705: if(l2==k2) continue;
4706: j=(k2-1)*(nlstate+ndeath)+l2;
4707: for (k1=1; k1<=(nlstate);k1++){
4708: for (l1=1; l1<=(nlstate+ndeath);l1++){
4709: if(l1==k1) continue;
4710: i=(k1-1)*(nlstate+ndeath)+l1;
4711: if(i<=j) continue;
4712: for (age=bage; age<=fage; age ++){
4713: if ((int)age %5==0){
4714: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4715: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4716: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4717: mu1=mu[i][(int) age]/stepm*YEARM ;
4718: mu2=mu[j][(int) age]/stepm*YEARM;
4719: c12=cv12/sqrt(v1*v2);
4720: /* Computing eigen value of matrix of covariance */
4721: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4722: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4723: if ((lc2 <0) || (lc1 <0) ){
4724: if(first2==1){
4725: first1=0;
4726: 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);
4727: }
4728: 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);
4729: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4730: /* lc2=fabs(lc2); */
4731: }
4732:
4733: /* Eigen vectors */
4734: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4735: /*v21=sqrt(1.-v11*v11); *//* error */
4736: v21=(lc1-v1)/cv12*v11;
4737: v12=-v21;
4738: v22=v11;
4739: tnalp=v21/v11;
4740: if(first1==1){
4741: first1=0;
4742: 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);
4743: }
4744: 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);
4745: /*printf(fignu*/
4746: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4747: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4748: if(first==1){
4749: first=0;
4750: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4751: fprintf(ficgp,"\nset parametric;unset label");
4752: 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);
4753: fprintf(ficgp,"\nset ter svg size 640, 480");
4754: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4755: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4756: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4757: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4758: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4759: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4760: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4761: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4762: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4763: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4764: 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",\
4765: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4766: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4767: }else{
4768: first=0;
4769: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4770: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4771: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4772: 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",\
4773: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4774: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4775: }/* if first */
4776: } /* age mod 5 */
4777: } /* end loop age */
4778: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4779: first=1;
4780: } /*l12 */
4781: } /* k12 */
4782: } /*l1 */
4783: }/* k1 */
4784: /* } */ /* loop covariates */
4785: }
4786: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4787: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4788: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4789: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4790: free_vector(xp,1,npar);
4791: fclose(ficresprob);
4792: fclose(ficresprobcov);
4793: fclose(ficresprobcor);
4794: fflush(ficgp);
4795: fflush(fichtmcov);
4796: }
4797:
4798:
4799: /******************* Printing html file ***********/
4800: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4801: int lastpass, int stepm, int weightopt, char model[],\
4802: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4803: int popforecast, int estepm ,\
4804: double jprev1, double mprev1,double anprev1, \
4805: double jprev2, double mprev2,double anprev2){
4806: int jj1, k1, i1, cpt;
4807:
4808: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4809: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4810: </ul>");
4811: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4812: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4813: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
4814: fprintf(fichtm,"\
4815: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4816: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
4817: fprintf(fichtm,"\
4818: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4819: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
4820: fprintf(fichtm,"\
4821: - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
4822: <a href=\"%s\">%s</a> <br>\n",
4823: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
4824: fprintf(fichtm,"\
4825: - Population projections by age and states: \
4826: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
4827:
4828: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4829:
4830: m=pow(2,cptcoveff);
4831: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4832:
4833: jj1=0;
4834: for(k1=1; k1<=m;k1++){
4835: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4836: jj1++;
4837: if (cptcovn > 0) {
4838: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4839: for (cpt=1; cpt<=cptcoveff;cpt++){
4840: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4841: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
4842: }
4843: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4844: }
4845: /* aij, bij */
4846: fprintf(fichtm,"<br>- Logit model, 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> \
4847: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4848: /* Pij */
4849: fprintf(fichtm,"<br>\n- Pij 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> \
4850: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4851: /* Quasi-incidences */
4852: fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4853: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
4854: incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
4855: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
4856: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
4857: /* Survival functions (period) in state j */
4858: for(cpt=1; cpt<=nlstate;cpt++){
4859: 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> \
4860: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
4861: }
4862: /* State specific survival functions (period) */
4863: for(cpt=1; cpt<=nlstate;cpt++){
4864: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
4865: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
4866: <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);
4867: }
4868: /* Period (stable) prevalence in each health state */
4869: for(cpt=1; cpt<=nlstate;cpt++){
4870: 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> \
4871: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
4872: }
4873: for(cpt=1; cpt<=nlstate;cpt++) {
4874: 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> \
4875: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
4876: }
4877: /* } /\* end i1 *\/ */
4878: }/* End k1 */
4879: fprintf(fichtm,"</ul>");
4880:
4881: fprintf(fichtm,"\
4882: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4883: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
4884: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
4885: But because parameters are usually highly correlated (a higher incidence of disability \
4886: and a higher incidence of recovery can give very close observed transition) it might \
4887: be very useful to look not only at linear confidence intervals estimated from the \
4888: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
4889: (parameters) of the logistic regression, it might be more meaningful to visualize the \
4890: covariance matrix of the one-step probabilities. \
4891: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
4892:
4893: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4894: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
4895: fprintf(fichtm,"\
4896: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4897: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
4898:
4899: fprintf(fichtm,"\
4900: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4901: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
4902: fprintf(fichtm,"\
4903: - 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): \
4904: <a href=\"%s\">%s</a> <br>\n</li>",
4905: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
4906: fprintf(fichtm,"\
4907: - (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): \
4908: <a href=\"%s\">%s</a> <br>\n</li>",
4909: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
4910: fprintf(fichtm,"\
4911: - 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",
4912: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
4913: fprintf(fichtm,"\
4914: - 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",
4915: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
4916: fprintf(fichtm,"\
4917: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4918: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
4919:
4920: /* if(popforecast==1) fprintf(fichtm,"\n */
4921: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4922: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4923: /* <br>",fileres,fileres,fileres,fileres); */
4924: /* else */
4925: /* 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); */
4926: fflush(fichtm);
4927: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4928:
4929: m=pow(2,cptcoveff);
4930: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4931:
4932: jj1=0;
4933: for(k1=1; k1<=m;k1++){
4934: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
4935: jj1++;
4936: if (cptcovn > 0) {
4937: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4938: for (cpt=1; cpt<=cptcoveff;cpt++)
4939: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
4940: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4941: }
4942: for(cpt=1; cpt<=nlstate;cpt++) {
4943: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4944: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
4945: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
4946: }
4947: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4948: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4949: true period expectancies (those weighted with period prevalences are also\
4950: drawn in addition to the population based expectancies computed using\
4951: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
4952: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
4953: /* } /\* end i1 *\/ */
4954: }/* End k1 */
4955: fprintf(fichtm,"</ul>");
4956: fflush(fichtm);
4957: }
4958:
4959: /******************* Gnuplot file **************/
4960: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4961:
4962: char dirfileres[132],optfileres[132];
4963: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4964: int ng=0;
4965: int vpopbased;
4966: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4967: /* printf("Problem with file %s",optionfilegnuplot); */
4968: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4969: /* } */
4970:
4971: /*#ifdef windows */
4972: fprintf(ficgp,"cd \"%s\" \n",pathc);
4973: /*#endif */
4974: m=pow(2,cptcoveff);
4975:
4976: /* Contribution to likelihood */
4977: /* Plot the probability implied in the likelihood */
4978: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
4979: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
4980: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
4981: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
4982: /* nice for mle=4 plot by number of matrix products.
4983: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
4984: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
4985: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
4986: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
4987: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
4988: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
4989: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
4990: for (i=1; i<= nlstate ; i ++) {
4991: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
4992: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
4993: fprintf(ficgp," u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
4994: for (j=2; j<= nlstate+ndeath ; j ++) {
4995: fprintf(ficgp,",\\\n \"\" u 2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
4996: }
4997: fprintf(ficgp,";\nset out; unset ylabel;\n");
4998: }
4999: /* 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 */
5000: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5001: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
5002: fprintf(ficgp,"\nset out;unset log\n");
5003: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5004:
5005: strcpy(dirfileres,optionfilefiname);
5006: strcpy(optfileres,"vpl");
5007: /* 1eme*/
5008: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
5009: for (cpt=1; cpt<= nlstate ; cpt ++) {
5010: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5011: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5012: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5013: fprintf(ficgp,"set xlabel \"Age\" \n\
5014: set ylabel \"Probability\" \n\
5015: set ter svg size 640, 480\n\
5016: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5017:
5018: for (i=1; i<= nlstate ; i ++) {
5019: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5020: else fprintf(ficgp," %%*lf (%%*lf)");
5021: }
5022: 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);
5023: for (i=1; i<= nlstate ; i ++) {
5024: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5025: else fprintf(ficgp," %%*lf (%%*lf)");
5026: }
5027: 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);
5028: for (i=1; i<= nlstate ; i ++) {
5029: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5030: else fprintf(ficgp," %%*lf (%%*lf)");
5031: }
5032: 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));
5033: fprintf(ficgp,"\nset out \n");
5034: } /* k1 */
5035: } /* cpt */
5036: /*2 eme*/
5037: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
5038: for (k1=1; k1<= m ; k1 ++) {
5039: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5040: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5041: if(vpopbased==0)
5042: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5043: else
5044: fprintf(ficgp,"\nreplot ");
5045: for (i=1; i<= nlstate+1 ; i ++) {
5046: k=2*i;
5047: 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);
5048: for (j=1; j<= nlstate+1 ; j ++) {
5049: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5050: else fprintf(ficgp," %%*lf (%%*lf)");
5051: }
5052: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5053: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5054: 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);
5055: for (j=1; j<= nlstate+1 ; j ++) {
5056: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5057: else fprintf(ficgp," %%*lf (%%*lf)");
5058: }
5059: fprintf(ficgp,"\" t\"\" w l lt 0,");
5060: 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);
5061: for (j=1; j<= nlstate+1 ; j ++) {
5062: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5063: else fprintf(ficgp," %%*lf (%%*lf)");
5064: }
5065: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5066: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5067: } /* state */
5068: } /* vpopbased */
5069: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5070: } /* k1 */
5071: /*3eme*/
5072:
5073: for (k1=1; k1<= m ; k1 ++) {
5074: for (cpt=1; cpt<= nlstate ; cpt ++) {
5075: /* k=2+nlstate*(2*cpt-2); */
5076: k=2+(nlstate+1)*(cpt-1);
5077: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5078: fprintf(ficgp,"set ter svg size 640, 480\n\
5079: 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);
5080: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5081: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5082: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5083: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5084: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5085: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5086:
5087: */
5088: for (i=1; i< nlstate ; i ++) {
5089: 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);
5090: /* 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);*/
5091:
5092: }
5093: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5094: }
5095: }
5096:
5097: /* Survival functions (period) from state i in state j by initial state i */
5098: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5099: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5100: k=3;
5101: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
5102: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5103: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5104: set ter svg size 640, 480\n\
5105: unset log y\n\
5106: plot [%.f:%.f] ", ageminpar, agemaxpar);
5107: for (i=1; i<= nlstate ; i ++){
5108: if(i==1)
5109: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5110: else
5111: fprintf(ficgp,", '' ");
5112: l=(nlstate+ndeath)*(i-1)+1;
5113: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5114: for (j=2; j<= nlstate+ndeath ; j ++)
5115: fprintf(ficgp,"+$%d",k+l+j-1);
5116: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5117: } /* nlstate */
5118: fprintf(ficgp,"\nset out\n");
5119: } /* end cpt state*/
5120: } /* end covariate */
5121:
5122: /* Survival functions (period) from state i in state j by final state j */
5123: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5124: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5125: k=3;
5126: 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);
5127: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5128: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5129: set ter svg size 640, 480\n\
5130: unset log y\n\
5131: plot [%.f:%.f] ", ageminpar, agemaxpar);
5132: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5133: if(j==1)
5134: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5135: else
5136: fprintf(ficgp,", '' ");
5137: l=(nlstate+ndeath)*(cpt-1) +j;
5138: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5139: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5140: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5141: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5142: } /* nlstate */
5143: fprintf(ficgp,", '' ");
5144: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5145: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5146: l=(nlstate+ndeath)*(cpt-1) +j;
5147: if(j < nlstate)
5148: fprintf(ficgp,"$%d +",k+l);
5149: else
5150: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5151: }
5152: fprintf(ficgp,"\nset out\n");
5153: } /* end cpt state*/
5154: } /* end covariate */
5155:
5156: /* CV preval stable (period) for each covariate */
5157: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5158: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5159: k=3;
5160: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
5161: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5162: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5163: set ter svg size 640, 480\n\
5164: unset log y\n\
5165: plot [%.f:%.f] ", ageminpar, agemaxpar);
5166: for (i=1; i<= nlstate ; i ++){
5167: if(i==1)
5168: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5169: else
5170: fprintf(ficgp,", '' ");
5171: l=(nlstate+ndeath)*(i-1)+1;
5172: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5173: for (j=2; j<= nlstate ; j ++)
5174: fprintf(ficgp,"+$%d",k+l+j-1);
5175: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5176: } /* nlstate */
5177: fprintf(ficgp,"\nset out\n");
5178: } /* end cpt state*/
5179: } /* end covariate */
5180:
5181: /* proba elementaires */
5182: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5183: for(i=1,jk=1; i <=nlstate; i++){
5184: fprintf(ficgp,"# initial state %d\n",i);
5185: for(k=1; k <=(nlstate+ndeath); k++){
5186: if (k != i) {
5187: fprintf(ficgp,"# current state %d\n",k);
5188: for(j=1; j <=ncovmodel; j++){
5189: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5190: jk++;
5191: }
5192: fprintf(ficgp,"\n");
5193: }
5194: }
5195: }
5196: fprintf(ficgp,"##############\n#\n");
5197:
5198: /*goto avoid;*/
5199: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5200: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5201: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5202: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5203: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5204: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5205: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5206: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5207: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5208: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5209: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5210: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5211: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5212: fprintf(ficgp,"#\n");
5213: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5214: fprintf(ficgp,"# ng=%d\n",ng);
5215: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5216: for(jk=1; jk <=m; jk++) {
5217: fprintf(ficgp,"# jk=%d\n",jk);
5218: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5219: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5220: if (ng==1){
5221: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5222: fprintf(ficgp,"\nunset log y");
5223: }else if (ng==2){
5224: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5225: fprintf(ficgp,"\nset log y");
5226: }else if (ng==3){
5227: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5228: fprintf(ficgp,"\nset log y");
5229: }else
5230: fprintf(ficgp,"\nunset title ");
5231: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5232: i=1;
5233: for(k2=1; k2<=nlstate; k2++) {
5234: k3=i;
5235: for(k=1; k<=(nlstate+ndeath); k++) {
5236: if (k != k2){
5237: switch( ng) {
5238: case 1:
5239: if(nagesqr==0)
5240: fprintf(ficgp," p%d+p%d*x",i,i+1);
5241: else /* nagesqr =1 */
5242: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5243: break;
5244: case 2: /* ng=2 */
5245: if(nagesqr==0)
5246: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5247: else /* nagesqr =1 */
5248: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5249: break;
5250: case 3:
5251: if(nagesqr==0)
5252: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5253: else /* nagesqr =1 */
5254: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5255: break;
5256: }
5257: ij=1;/* To be checked else nbcode[0][0] wrong */
5258: for(j=3; j <=ncovmodel-nagesqr; j++) {
5259: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5260: if(ij <=cptcovage) { /* Bug valgrind */
5261: if((j-2)==Tage[ij]) { /* Bug valgrind */
5262: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5263: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5264: ij++;
5265: }
5266: }
5267: else
5268: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5269: }
5270: if(ng != 1){
5271: fprintf(ficgp,")/(1");
5272:
5273: for(k1=1; k1 <=nlstate; k1++){
5274: if(nagesqr==0)
5275: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5276: else /* nagesqr =1 */
5277: 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);
5278:
5279: ij=1;
5280: for(j=3; j <=ncovmodel-nagesqr; j++){
5281: if(ij <=cptcovage) { /* Bug valgrind */
5282: if((j-2)==Tage[ij]) { /* Bug valgrind */
5283: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5284: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5285: ij++;
5286: }
5287: }
5288: else
5289: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5290: }
5291: fprintf(ficgp,")");
5292: }
5293: fprintf(ficgp,")");
5294: if(ng ==2)
5295: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5296: else /* ng= 3 */
5297: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5298: }else{ /* end ng <> 1 */
5299: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5300: }
5301: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5302: i=i+ncovmodel;
5303: }
5304: } /* end k */
5305: } /* end k2 */
5306: fprintf(ficgp,"\n set out\n");
5307: } /* end jk */
5308: } /* end ng */
5309: /* avoid: */
5310: fflush(ficgp);
5311: } /* end gnuplot */
5312:
5313:
5314: /*************** Moving average **************/
5315: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5316:
5317: int i, cpt, cptcod;
5318: int modcovmax =1;
5319: int mobilavrange, mob;
5320: double age;
5321:
5322: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5323: a covariate has 2 modalities */
5324: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5325:
5326: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5327: if(mobilav==1) mobilavrange=5; /* default */
5328: else mobilavrange=mobilav;
5329: for (age=bage; age<=fage; age++)
5330: for (i=1; i<=nlstate;i++)
5331: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5332: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5333: /* We keep the original values on the extreme ages bage, fage and for
5334: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5335: we use a 5 terms etc. until the borders are no more concerned.
5336: */
5337: for (mob=3;mob <=mobilavrange;mob=mob+2){
5338: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5339: for (i=1; i<=nlstate;i++){
5340: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5341: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5342: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5343: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5344: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5345: }
5346: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5347: }
5348: }
5349: }/* end age */
5350: }/* end mob */
5351: }else return -1;
5352: return 0;
5353: }/* End movingaverage */
5354:
5355:
5356: /************** Forecasting ******************/
5357: 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){
5358: /* proj1, year, month, day of starting projection
5359: agemin, agemax range of age
5360: dateprev1 dateprev2 range of dates during which prevalence is computed
5361: anproj2 year of en of projection (same day and month as proj1).
5362: */
5363: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5364: double agec; /* generic age */
5365: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5366: double *popeffectif,*popcount;
5367: double ***p3mat;
5368: double ***mobaverage;
5369: char fileresf[FILENAMELENGTH];
5370:
5371: agelim=AGESUP;
5372: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5373:
5374: strcpy(fileresf,"F_");
5375: strcat(fileresf,fileresu);
5376: if((ficresf=fopen(fileresf,"w"))==NULL) {
5377: printf("Problem with forecast resultfile: %s\n", fileresf);
5378: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5379: }
5380: printf("Computing forecasting: result on file '%s' \n", fileresf);
5381: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
5382:
5383: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5384:
5385: if (mobilav!=0) {
5386: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5387: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5388: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5389: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5390: }
5391: }
5392:
5393: stepsize=(int) (stepm+YEARM-1)/YEARM;
5394: if (stepm<=12) stepsize=1;
5395: if(estepm < stepm){
5396: printf ("Problem %d lower than %d\n",estepm, stepm);
5397: }
5398: else hstepm=estepm;
5399:
5400: hstepm=hstepm/stepm;
5401: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5402: fractional in yp1 */
5403: anprojmean=yp;
5404: yp2=modf((yp1*12),&yp);
5405: mprojmean=yp;
5406: yp1=modf((yp2*30.5),&yp);
5407: jprojmean=yp;
5408: if(jprojmean==0) jprojmean=1;
5409: if(mprojmean==0) jprojmean=1;
5410:
5411: i1=cptcoveff;
5412: if (cptcovn < 1){i1=1;}
5413:
5414: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5415:
5416: fprintf(ficresf,"#****** Routine prevforecast **\n");
5417:
5418: /* if (h==(int)(YEARM*yearp)){ */
5419: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5420: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5421: k=k+1;
5422: fprintf(ficresf,"\n#******");
5423: for(j=1;j<=cptcoveff;j++) {
5424: fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5425: }
5426: fprintf(ficresf,"******\n");
5427: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
5428: for(j=1; j<=nlstate+ndeath;j++){
5429: for(i=1; i<=nlstate;i++)
5430: fprintf(ficresf," p%d%d",i,j);
5431: fprintf(ficresf," p.%d",j);
5432: }
5433: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5434: fprintf(ficresf,"\n");
5435: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5436:
5437: for (agec=fage; agec>=(ageminpar-1); agec--){
5438: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5439: nhstepm = nhstepm/hstepm;
5440: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5441: oldm=oldms;savm=savms;
5442: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5443:
5444: for (h=0; h<=nhstepm; h++){
5445: if (h*hstepm/YEARM*stepm ==yearp) {
5446: fprintf(ficresf,"\n");
5447: for(j=1;j<=cptcoveff;j++)
5448: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5449: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5450: }
5451: for(j=1; j<=nlstate+ndeath;j++) {
5452: ppij=0.;
5453: for(i=1; i<=nlstate;i++) {
5454: if (mobilav==1)
5455: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5456: else {
5457: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5458: }
5459: if (h*hstepm/YEARM*stepm== yearp) {
5460: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5461: }
5462: } /* end i */
5463: if (h*hstepm/YEARM*stepm==yearp) {
5464: fprintf(ficresf," %.3f", ppij);
5465: }
5466: }/* end j */
5467: } /* end h */
5468: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5469: } /* end agec */
5470: } /* end yearp */
5471: } /* end cptcod */
5472: } /* end cptcov */
5473:
5474: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5475:
5476: fclose(ficresf);
5477: }
5478:
5479: /************** Forecasting *****not tested NB*************/
5480: 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){
5481:
5482: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5483: int *popage;
5484: double calagedatem, agelim, kk1, kk2;
5485: double *popeffectif,*popcount;
5486: double ***p3mat,***tabpop,***tabpopprev;
5487: double ***mobaverage;
5488: char filerespop[FILENAMELENGTH];
5489:
5490: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5491: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5492: agelim=AGESUP;
5493: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5494:
5495: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5496:
5497:
5498: strcpy(filerespop,"POP_");
5499: strcat(filerespop,fileresu);
5500: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5501: printf("Problem with forecast resultfile: %s\n", filerespop);
5502: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5503: }
5504: printf("Computing forecasting: result on file '%s' \n", filerespop);
5505: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5506:
5507: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5508:
5509: if (mobilav!=0) {
5510: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5511: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5512: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5513: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5514: }
5515: }
5516:
5517: stepsize=(int) (stepm+YEARM-1)/YEARM;
5518: if (stepm<=12) stepsize=1;
5519:
5520: agelim=AGESUP;
5521:
5522: hstepm=1;
5523: hstepm=hstepm/stepm;
5524:
5525: if (popforecast==1) {
5526: if((ficpop=fopen(popfile,"r"))==NULL) {
5527: printf("Problem with population file : %s\n",popfile);exit(0);
5528: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5529: }
5530: popage=ivector(0,AGESUP);
5531: popeffectif=vector(0,AGESUP);
5532: popcount=vector(0,AGESUP);
5533:
5534: i=1;
5535: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5536:
5537: imx=i;
5538: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5539: }
5540:
5541: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5542: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5543: k=k+1;
5544: fprintf(ficrespop,"\n#******");
5545: for(j=1;j<=cptcoveff;j++) {
5546: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5547: }
5548: fprintf(ficrespop,"******\n");
5549: fprintf(ficrespop,"# Age");
5550: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5551: if (popforecast==1) fprintf(ficrespop," [Population]");
5552:
5553: for (cpt=0; cpt<=0;cpt++) {
5554: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5555:
5556: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5557: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5558: nhstepm = nhstepm/hstepm;
5559:
5560: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5561: oldm=oldms;savm=savms;
5562: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5563:
5564: for (h=0; h<=nhstepm; h++){
5565: if (h==(int) (calagedatem+YEARM*cpt)) {
5566: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5567: }
5568: for(j=1; j<=nlstate+ndeath;j++) {
5569: kk1=0.;kk2=0;
5570: for(i=1; i<=nlstate;i++) {
5571: if (mobilav==1)
5572: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5573: else {
5574: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5575: }
5576: }
5577: if (h==(int)(calagedatem+12*cpt)){
5578: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5579: /*fprintf(ficrespop," %.3f", kk1);
5580: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5581: }
5582: }
5583: for(i=1; i<=nlstate;i++){
5584: kk1=0.;
5585: for(j=1; j<=nlstate;j++){
5586: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5587: }
5588: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5589: }
5590:
5591: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5592: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5593: }
5594: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5595: }
5596: }
5597:
5598: /******/
5599:
5600: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5601: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5602: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5603: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5604: nhstepm = nhstepm/hstepm;
5605:
5606: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5607: oldm=oldms;savm=savms;
5608: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5609: for (h=0; h<=nhstepm; h++){
5610: if (h==(int) (calagedatem+YEARM*cpt)) {
5611: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5612: }
5613: for(j=1; j<=nlstate+ndeath;j++) {
5614: kk1=0.;kk2=0;
5615: for(i=1; i<=nlstate;i++) {
5616: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5617: }
5618: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5619: }
5620: }
5621: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5622: }
5623: }
5624: }
5625: }
5626:
5627: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5628:
5629: if (popforecast==1) {
5630: free_ivector(popage,0,AGESUP);
5631: free_vector(popeffectif,0,AGESUP);
5632: free_vector(popcount,0,AGESUP);
5633: }
5634: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5635: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5636: fclose(ficrespop);
5637: } /* End of popforecast */
5638:
5639: int fileappend(FILE *fichier, char *optionfich)
5640: {
5641: if((fichier=fopen(optionfich,"a"))==NULL) {
5642: printf("Problem with file: %s\n", optionfich);
5643: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5644: return (0);
5645: }
5646: fflush(fichier);
5647: return (1);
5648: }
5649:
5650:
5651: /**************** function prwizard **********************/
5652: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5653: {
5654:
5655: /* Wizard to print covariance matrix template */
5656:
5657: char ca[32], cb[32];
5658: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5659: int numlinepar;
5660:
5661: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5662: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5663: for(i=1; i <=nlstate; i++){
5664: jj=0;
5665: for(j=1; j <=nlstate+ndeath; j++){
5666: if(j==i) continue;
5667: jj++;
5668: /*ca[0]= k+'a'-1;ca[1]='\0';*/
5669: printf("%1d%1d",i,j);
5670: fprintf(ficparo,"%1d%1d",i,j);
5671: for(k=1; k<=ncovmodel;k++){
5672: /* printf(" %lf",param[i][j][k]); */
5673: /* fprintf(ficparo," %lf",param[i][j][k]); */
5674: printf(" 0.");
5675: fprintf(ficparo," 0.");
5676: }
5677: printf("\n");
5678: fprintf(ficparo,"\n");
5679: }
5680: }
5681: printf("# Scales (for hessian or gradient estimation)\n");
5682: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
5683: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
5684: for(i=1; i <=nlstate; i++){
5685: jj=0;
5686: for(j=1; j <=nlstate+ndeath; j++){
5687: if(j==i) continue;
5688: jj++;
5689: fprintf(ficparo,"%1d%1d",i,j);
5690: printf("%1d%1d",i,j);
5691: fflush(stdout);
5692: for(k=1; k<=ncovmodel;k++){
5693: /* printf(" %le",delti3[i][j][k]); */
5694: /* fprintf(ficparo," %le",delti3[i][j][k]); */
5695: printf(" 0.");
5696: fprintf(ficparo," 0.");
5697: }
5698: numlinepar++;
5699: printf("\n");
5700: fprintf(ficparo,"\n");
5701: }
5702: }
5703: printf("# Covariance matrix\n");
5704: /* # 121 Var(a12)\n\ */
5705: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5706: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
5707: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
5708: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
5709: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
5710: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
5711: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5712: fflush(stdout);
5713: fprintf(ficparo,"# Covariance matrix\n");
5714: /* # 121 Var(a12)\n\ */
5715: /* # 122 Cov(b12,a12) Var(b12)\n\ */
5716: /* # ...\n\ */
5717: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
5718:
5719: for(itimes=1;itimes<=2;itimes++){
5720: jj=0;
5721: for(i=1; i <=nlstate; i++){
5722: for(j=1; j <=nlstate+ndeath; j++){
5723: if(j==i) continue;
5724: for(k=1; k<=ncovmodel;k++){
5725: jj++;
5726: ca[0]= k+'a'-1;ca[1]='\0';
5727: if(itimes==1){
5728: printf("#%1d%1d%d",i,j,k);
5729: fprintf(ficparo,"#%1d%1d%d",i,j,k);
5730: }else{
5731: printf("%1d%1d%d",i,j,k);
5732: fprintf(ficparo,"%1d%1d%d",i,j,k);
5733: /* printf(" %.5le",matcov[i][j]); */
5734: }
5735: ll=0;
5736: for(li=1;li <=nlstate; li++){
5737: for(lj=1;lj <=nlstate+ndeath; lj++){
5738: if(lj==li) continue;
5739: for(lk=1;lk<=ncovmodel;lk++){
5740: ll++;
5741: if(ll<=jj){
5742: cb[0]= lk +'a'-1;cb[1]='\0';
5743: if(ll<jj){
5744: if(itimes==1){
5745: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5746: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
5747: }else{
5748: printf(" 0.");
5749: fprintf(ficparo," 0.");
5750: }
5751: }else{
5752: if(itimes==1){
5753: printf(" Var(%s%1d%1d)",ca,i,j);
5754: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
5755: }else{
5756: printf(" 0.");
5757: fprintf(ficparo," 0.");
5758: }
5759: }
5760: }
5761: } /* end lk */
5762: } /* end lj */
5763: } /* end li */
5764: printf("\n");
5765: fprintf(ficparo,"\n");
5766: numlinepar++;
5767: } /* end k*/
5768: } /*end j */
5769: } /* end i */
5770: } /* end itimes */
5771:
5772: } /* end of prwizard */
5773: /******************* Gompertz Likelihood ******************************/
5774: double gompertz(double x[])
5775: {
5776: double A,B,L=0.0,sump=0.,num=0.;
5777: int i,n=0; /* n is the size of the sample */
5778:
5779: for (i=0;i<=imx-1 ; i++) {
5780: sump=sump+weight[i];
5781: /* sump=sump+1;*/
5782: num=num+1;
5783: }
5784:
5785:
5786: /* for (i=0; i<=imx; i++)
5787: 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]);*/
5788:
5789: for (i=1;i<=imx ; i++)
5790: {
5791: if (cens[i] == 1 && wav[i]>1)
5792: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
5793:
5794: if (cens[i] == 0 && wav[i]>1)
5795: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
5796: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
5797:
5798: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5799: if (wav[i] > 1 ) { /* ??? */
5800: L=L+A*weight[i];
5801: /* 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]);*/
5802: }
5803: }
5804:
5805: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5806:
5807: return -2*L*num/sump;
5808: }
5809:
5810: #ifdef GSL
5811: /******************* Gompertz_f Likelihood ******************************/
5812: double gompertz_f(const gsl_vector *v, void *params)
5813: {
5814: double A,B,LL=0.0,sump=0.,num=0.;
5815: double *x= (double *) v->data;
5816: int i,n=0; /* n is the size of the sample */
5817:
5818: for (i=0;i<=imx-1 ; i++) {
5819: sump=sump+weight[i];
5820: /* sump=sump+1;*/
5821: num=num+1;
5822: }
5823:
5824:
5825: /* for (i=0; i<=imx; i++)
5826: 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]);*/
5827: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
5828: for (i=1;i<=imx ; i++)
5829: {
5830: if (cens[i] == 1 && wav[i]>1)
5831: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
5832:
5833: if (cens[i] == 0 && wav[i]>1)
5834: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
5835: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
5836:
5837: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
5838: if (wav[i] > 1 ) { /* ??? */
5839: LL=LL+A*weight[i];
5840: /* 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]);*/
5841: }
5842: }
5843:
5844: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
5845: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
5846:
5847: return -2*LL*num/sump;
5848: }
5849: #endif
5850:
5851: /******************* Printing html file ***********/
5852: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
5853: int lastpass, int stepm, int weightopt, char model[],\
5854: int imx, double p[],double **matcov,double agemortsup){
5855: int i,k;
5856:
5857: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5858: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5859: for (i=1;i<=2;i++)
5860: 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]));
5861: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
5862: fprintf(fichtm,"</ul>");
5863:
5864: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5865:
5866: 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>");
5867:
5868: for (k=agegomp;k<(agemortsup-2);k++)
5869: 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]);
5870:
5871:
5872: fflush(fichtm);
5873: }
5874:
5875: /******************* Gnuplot file **************/
5876: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5877:
5878: char dirfileres[132],optfileres[132];
5879:
5880: int ng;
5881:
5882:
5883: /*#ifdef windows */
5884: fprintf(ficgp,"cd \"%s\" \n",pathc);
5885: /*#endif */
5886:
5887:
5888: strcpy(dirfileres,optionfilefiname);
5889: strcpy(optfileres,"vpl");
5890: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
5891: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5892: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
5893: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5894: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5895:
5896: }
5897:
5898: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5899: {
5900:
5901: /*-------- data file ----------*/
5902: FILE *fic;
5903: char dummy[]=" ";
5904: int i=0, j=0, n=0;
5905: int linei, month, year,iout;
5906: char line[MAXLINE], linetmp[MAXLINE];
5907: char stra[MAXLINE], strb[MAXLINE];
5908: char *stratrunc;
5909: int lstra;
5910:
5911:
5912: if((fic=fopen(datafile,"r"))==NULL) {
5913: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
5914: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
5915: }
5916:
5917: i=1;
5918: linei=0;
5919: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5920: linei=linei+1;
5921: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5922: if(line[j] == '\t')
5923: line[j] = ' ';
5924: }
5925: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5926: ;
5927: };
5928: line[j+1]=0; /* Trims blanks at end of line */
5929: if(line[0]=='#'){
5930: fprintf(ficlog,"Comment line\n%s\n",line);
5931: printf("Comment line\n%s\n",line);
5932: continue;
5933: }
5934: trimbb(linetmp,line); /* Trims multiple blanks in line */
5935: strcpy(line, linetmp);
5936:
5937:
5938: for (j=maxwav;j>=1;j--){
5939: cutv(stra, strb, line, ' ');
5940: if(strb[0]=='.') { /* Missing status */
5941: lval=-1;
5942: }else{
5943: errno=0;
5944: lval=strtol(strb,&endptr,10);
5945: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5946: if( strb[0]=='\0' || (*endptr != '\0')){
5947: 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);
5948: 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);
5949: return 1;
5950: }
5951: }
5952: s[j][i]=lval;
5953:
5954: strcpy(line,stra);
5955: cutv(stra, strb,line,' ');
5956: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5957: }
5958: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5959: month=99;
5960: year=9999;
5961: }else{
5962: 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);
5963: 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);
5964: return 1;
5965: }
5966: anint[j][i]= (double) year;
5967: mint[j][i]= (double)month;
5968: strcpy(line,stra);
5969: } /* ENd Waves */
5970:
5971: cutv(stra, strb,line,' ');
5972: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5973: }
5974: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5975: month=99;
5976: year=9999;
5977: }else{
5978: 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);
5979: 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);
5980: return 1;
5981: }
5982: andc[i]=(double) year;
5983: moisdc[i]=(double) month;
5984: strcpy(line,stra);
5985:
5986: cutv(stra, strb,line,' ');
5987: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5988: }
5989: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5990: month=99;
5991: year=9999;
5992: }else{
5993: 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);
5994: 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);
5995: return 1;
5996: }
5997: if (year==9999) {
5998: 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);
5999: 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);
6000: return 1;
6001:
6002: }
6003: annais[i]=(double)(year);
6004: moisnais[i]=(double)(month);
6005: strcpy(line,stra);
6006:
6007: cutv(stra, strb,line,' ');
6008: errno=0;
6009: dval=strtod(strb,&endptr);
6010: if( strb[0]=='\0' || (*endptr != '\0')){
6011: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6012: 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);
6013: fflush(ficlog);
6014: return 1;
6015: }
6016: weight[i]=dval;
6017: strcpy(line,stra);
6018:
6019: for (j=ncovcol;j>=1;j--){
6020: cutv(stra, strb,line,' ');
6021: if(strb[0]=='.') { /* Missing status */
6022: lval=-1;
6023: }else{
6024: errno=0;
6025: lval=strtol(strb,&endptr,10);
6026: if( strb[0]=='\0' || (*endptr != '\0')){
6027: 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);
6028: 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);
6029: return 1;
6030: }
6031: }
6032: if(lval <-1 || lval >1){
6033: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6034: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6035: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6036: For example, for multinomial values like 1, 2 and 3,\n \
6037: build V1=0 V2=0 for the reference value (1),\n \
6038: V1=1 V2=0 for (2) \n \
6039: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6040: output of IMaCh is often meaningless.\n \
6041: Exiting.\n",lval,linei, i,line,j);
6042: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6043: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6044: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6045: For example, for multinomial values like 1, 2 and 3,\n \
6046: build V1=0 V2=0 for the reference value (1),\n \
6047: V1=1 V2=0 for (2) \n \
6048: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6049: output of IMaCh is often meaningless.\n \
6050: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6051: return 1;
6052: }
6053: covar[j][i]=(double)(lval);
6054: strcpy(line,stra);
6055: }
6056: lstra=strlen(stra);
6057:
6058: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6059: stratrunc = &(stra[lstra-9]);
6060: num[i]=atol(stratrunc);
6061: }
6062: else
6063: num[i]=atol(stra);
6064: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6065: 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;}*/
6066:
6067: i=i+1;
6068: } /* End loop reading data */
6069:
6070: *imax=i-1; /* Number of individuals */
6071: fclose(fic);
6072:
6073: return (0);
6074: /* endread: */
6075: printf("Exiting readdata: ");
6076: fclose(fic);
6077: return (1);
6078:
6079:
6080:
6081: }
6082: void removespace(char *str) {
6083: char *p1 = str, *p2 = str;
6084: do
6085: while (*p2 == ' ')
6086: p2++;
6087: while (*p1++ == *p2++);
6088: }
6089:
6090: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
6091: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6092: * - nagesqr = 1 if age*age in the model, otherwise 0.
6093: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6094: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6095: * - cptcovage number of covariates with age*products =2
6096: * - cptcovs number of simple covariates
6097: * - 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
6098: * which is a new column after the 9 (ncovcol) variables.
6099: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6100: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6101: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6102: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6103: */
6104: {
6105: int i, j, k, ks;
6106: int j1, k1, k2;
6107: char modelsav[80];
6108: char stra[80], strb[80], strc[80], strd[80],stre[80];
6109: char *strpt;
6110:
6111: /*removespace(model);*/
6112: if (strlen(model) >1){ /* If there is at least 1 covariate */
6113: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6114: if (strstr(model,"AGE") !=0){
6115: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6116: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6117: return 1;
6118: }
6119: if (strstr(model,"v") !=0){
6120: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6121: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6122: return 1;
6123: }
6124: strcpy(modelsav,model);
6125: if ((strpt=strstr(model,"age*age")) !=0){
6126: printf(" strpt=%s, model=%s\n",strpt, model);
6127: if(strpt != model){
6128: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6129: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6130: corresponding column of parameters.\n",model);
6131: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6132: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6133: corresponding column of parameters.\n",model); fflush(ficlog);
6134: return 1;
6135: }
6136:
6137: nagesqr=1;
6138: if (strstr(model,"+age*age") !=0)
6139: substrchaine(modelsav, model, "+age*age");
6140: else if (strstr(model,"age*age+") !=0)
6141: substrchaine(modelsav, model, "age*age+");
6142: else
6143: substrchaine(modelsav, model, "age*age");
6144: }else
6145: nagesqr=0;
6146: if (strlen(modelsav) >1){
6147: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6148: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6149: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6150: cptcovt= j+1; /* Number of total covariates in the model, not including
6151: * cst, age and age*age
6152: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6153: /* including age products which are counted in cptcovage.
6154: * but the covariates which are products must be treated
6155: * separately: ncovn=4- 2=2 (V1+V3). */
6156: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6157: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6158:
6159:
6160: /* Design
6161: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6162: * < ncovcol=8 >
6163: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6164: * k= 1 2 3 4 5 6 7 8
6165: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6166: * covar[k,i], value of kth covariate if not including age for individual i:
6167: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6168: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6169: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6170: * Tage[++cptcovage]=k
6171: * if products, new covar are created after ncovcol with k1
6172: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6173: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6174: * 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
6175: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6176: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6177: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6178: * < ncovcol=8 >
6179: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6180: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6181: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6182: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6183: * p Tprod[1]@2={ 6, 5}
6184: *p Tvard[1][1]@4= {7, 8, 5, 6}
6185: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6186: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6187: *How to reorganize?
6188: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6189: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6190: * {2, 1, 4, 8, 5, 6, 3, 7}
6191: * Struct []
6192: */
6193:
6194: /* This loop fills the array Tvar from the string 'model'.*/
6195: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6196: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6197: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6198: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6199: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6200: /* k=1 Tvar[1]=2 (from V2) */
6201: /* k=5 Tvar[5] */
6202: /* for (k=1; k<=cptcovn;k++) { */
6203: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6204: /* } */
6205: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6206: /*
6207: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6208: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6209: Tvar[k]=0;
6210: cptcovage=0;
6211: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6212: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6213: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6214: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6215: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6216: /*scanf("%d",i);*/
6217: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6218: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6219: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6220: /* covar is not filled and then is empty */
6221: cptcovprod--;
6222: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6223: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6224: cptcovage++; /* Sums the number of covariates which include age as a product */
6225: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6226: /*printf("stre=%s ", stre);*/
6227: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6228: cptcovprod--;
6229: cutl(stre,strb,strc,'V');
6230: Tvar[k]=atoi(stre);
6231: cptcovage++;
6232: Tage[cptcovage]=k;
6233: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6234: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6235: cptcovn++;
6236: cptcovprodnoage++;k1++;
6237: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6238: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6239: because this model-covariate is a construction we invent a new column
6240: ncovcol + k1
6241: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6242: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6243: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6244: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6245: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6246: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6247: k2=k2+2;
6248: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6249: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6250: for (i=1; i<=lastobs;i++){
6251: /* Computes the new covariate which is a product of
6252: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6253: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6254: }
6255: } /* End age is not in the model */
6256: } /* End if model includes a product */
6257: else { /* no more sum */
6258: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6259: /* scanf("%d",i);*/
6260: cutl(strd,strc,strb,'V');
6261: ks++; /**< Number of simple covariates */
6262: cptcovn++;
6263: Tvar[k]=atoi(strd);
6264: }
6265: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6266: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6267: scanf("%d",i);*/
6268: } /* end of loop + on total covariates */
6269: } /* end if strlen(modelsave == 0) age*age might exist */
6270: } /* end if strlen(model == 0) */
6271:
6272: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6273: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6274:
6275: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6276: printf("cptcovprod=%d ", cptcovprod);
6277: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6278:
6279: scanf("%d ",i);*/
6280:
6281:
6282: return (0); /* with covar[new additional covariate if product] and Tage if age */
6283: /*endread:*/
6284: printf("Exiting decodemodel: ");
6285: return (1);
6286: }
6287:
6288: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6289: {
6290: int i, m;
6291:
6292: for (i=1; i<=imx; i++) {
6293: for(m=2; (m<= maxwav); m++) {
6294: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6295: anint[m][i]=9999;
6296: s[m][i]=-1;
6297: }
6298: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6299: *nberr = *nberr + 1;
6300: 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);
6301: 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);
6302: s[m][i]=-1;
6303: }
6304: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6305: (*nberr)++;
6306: 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]);
6307: 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]);
6308: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6309: }
6310: }
6311: }
6312:
6313: for (i=1; i<=imx; i++) {
6314: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6315: for(m=firstpass; (m<= lastpass); m++){
6316: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
6317: if (s[m][i] >= nlstate+1) {
6318: if(agedc[i]>0){
6319: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6320: agev[m][i]=agedc[i];
6321: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6322: }else {
6323: if ((int)andc[i]!=9999){
6324: nbwarn++;
6325: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6326: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6327: agev[m][i]=-1;
6328: }
6329: }
6330: } /* agedc > 0 */
6331: }
6332: else if(s[m][i] !=9){ /* Standard case, age in fractional
6333: years but with the precision of a month */
6334: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6335: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6336: agev[m][i]=1;
6337: else if(agev[m][i] < *agemin){
6338: *agemin=agev[m][i];
6339: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6340: }
6341: else if(agev[m][i] >*agemax){
6342: *agemax=agev[m][i];
6343: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6344: }
6345: /*agev[m][i]=anint[m][i]-annais[i];*/
6346: /* agev[m][i] = age[i]+2*m;*/
6347: }
6348: else { /* =9 */
6349: agev[m][i]=1;
6350: s[m][i]=-1;
6351: }
6352: }
6353: else /*= 0 Unknown */
6354: agev[m][i]=1;
6355: }
6356:
6357: }
6358: for (i=1; i<=imx; i++) {
6359: for(m=firstpass; (m<=lastpass); m++){
6360: if (s[m][i] > (nlstate+ndeath)) {
6361: (*nberr)++;
6362: 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);
6363: 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);
6364: return 1;
6365: }
6366: }
6367: }
6368:
6369: /*for (i=1; i<=imx; i++){
6370: for (m=firstpass; (m<lastpass); m++){
6371: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6372: }
6373:
6374: }*/
6375:
6376:
6377: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6378: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6379:
6380: return (0);
6381: /* endread:*/
6382: printf("Exiting calandcheckages: ");
6383: return (1);
6384: }
6385:
6386: #if defined(_MSC_VER)
6387: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6388: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6389: //#include "stdafx.h"
6390: //#include <stdio.h>
6391: //#include <tchar.h>
6392: //#include <windows.h>
6393: //#include <iostream>
6394: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6395:
6396: LPFN_ISWOW64PROCESS fnIsWow64Process;
6397:
6398: BOOL IsWow64()
6399: {
6400: BOOL bIsWow64 = FALSE;
6401:
6402: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6403: // (HANDLE, PBOOL);
6404:
6405: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6406:
6407: HMODULE module = GetModuleHandle(_T("kernel32"));
6408: const char funcName[] = "IsWow64Process";
6409: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6410: GetProcAddress(module, funcName);
6411:
6412: if (NULL != fnIsWow64Process)
6413: {
6414: if (!fnIsWow64Process(GetCurrentProcess(),
6415: &bIsWow64))
6416: //throw std::exception("Unknown error");
6417: printf("Unknown error\n");
6418: }
6419: return bIsWow64 != FALSE;
6420: }
6421: #endif
6422:
6423: void syscompilerinfo(int logged)
6424: {
6425: /* #include "syscompilerinfo.h"*/
6426: /* command line Intel compiler 32bit windows, XP compatible:*/
6427: /* /GS /W3 /Gy
6428: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6429: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6430: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6431: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6432: */
6433: /* 64 bits */
6434: /*
6435: /GS /W3 /Gy
6436: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6437: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6438: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6439: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6440: /* Optimization are useless and O3 is slower than O2 */
6441: /*
6442: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6443: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6444: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6445: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6446: */
6447: /* Link is */ /* /OUT:"visual studio
6448: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6449: /PDB:"visual studio
6450: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6451: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6452: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6453: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6454: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6455: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6456: uiAccess='false'"
6457: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6458: /NOLOGO /TLBID:1
6459: */
6460: #if defined __INTEL_COMPILER
6461: #if defined(__GNUC__)
6462: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6463: #endif
6464: #elif defined(__GNUC__)
6465: #ifndef __APPLE__
6466: #include <gnu/libc-version.h> /* Only on gnu */
6467: #endif
6468: struct utsname sysInfo;
6469: int cross = CROSS;
6470: if (cross){
6471: printf("Cross-");
6472: if(logged) fprintf(ficlog, "Cross-");
6473: }
6474: #endif
6475:
6476: #include <stdint.h>
6477:
6478: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6479: #if defined(__clang__)
6480: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6481: #endif
6482: #if defined(__ICC) || defined(__INTEL_COMPILER)
6483: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6484: #endif
6485: #if defined(__GNUC__) || defined(__GNUG__)
6486: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6487: #endif
6488: #if defined(__HP_cc) || defined(__HP_aCC)
6489: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6490: #endif
6491: #if defined(__IBMC__) || defined(__IBMCPP__)
6492: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6493: #endif
6494: #if defined(_MSC_VER)
6495: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6496: #endif
6497: #if defined(__PGI)
6498: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6499: #endif
6500: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6501: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6502: #endif
6503: printf(" for "); if (logged) fprintf(ficlog, " for ");
6504:
6505: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6506: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6507: // Windows (x64 and x86)
6508: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6509: #elif __unix__ // all unices, not all compilers
6510: // Unix
6511: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6512: #elif __linux__
6513: // linux
6514: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6515: #elif __APPLE__
6516: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6517: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6518: #endif
6519:
6520: /* __MINGW32__ */
6521: /* __CYGWIN__ */
6522: /* __MINGW64__ */
6523: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6524: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6525: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6526: /* _WIN64 // Defined for applications for Win64. */
6527: /* _M_X64 // Defined for compilations that target x64 processors. */
6528: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6529:
6530: #if UINTPTR_MAX == 0xffffffff
6531: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6532: #elif UINTPTR_MAX == 0xffffffffffffffff
6533: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6534: #else
6535: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6536: #endif
6537:
6538: #if defined(__GNUC__)
6539: # if defined(__GNUC_PATCHLEVEL__)
6540: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6541: + __GNUC_MINOR__ * 100 \
6542: + __GNUC_PATCHLEVEL__)
6543: # else
6544: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6545: + __GNUC_MINOR__ * 100)
6546: # endif
6547: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6548: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6549:
6550: if (uname(&sysInfo) != -1) {
6551: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6552: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6553: }
6554: else
6555: perror("uname() error");
6556: //#ifndef __INTEL_COMPILER
6557: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6558: printf("GNU libc version: %s\n", gnu_get_libc_version());
6559: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6560: #endif
6561: #endif
6562:
6563: // void main()
6564: // {
6565: #if defined(_MSC_VER)
6566: if (IsWow64()){
6567: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6568: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6569: }
6570: else{
6571: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6572: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6573: }
6574: // printf("\nPress Enter to continue...");
6575: // getchar();
6576: // }
6577:
6578: #endif
6579:
6580:
6581: }
6582:
6583: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
6584: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6585: int i, j, k, i1 ;
6586: /* double ftolpl = 1.e-10; */
6587: double age, agebase, agelim;
6588: double tot;
6589:
6590: strcpy(filerespl,"PL_");
6591: strcat(filerespl,fileresu);
6592: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6593: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6594: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6595: }
6596: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6597: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6598: pstamp(ficrespl);
6599: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6600: fprintf(ficrespl,"#Age ");
6601: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6602: fprintf(ficrespl,"\n");
6603:
6604: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6605:
6606: agebase=ageminpar;
6607: agelim=agemaxpar;
6608:
6609: i1=pow(2,cptcoveff);
6610: if (cptcovn < 1){i1=1;}
6611:
6612: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6613: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6614: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6615: k=k+1;
6616: /* to clean */
6617: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6618: fprintf(ficrespl,"#******");
6619: printf("#******");
6620: fprintf(ficlog,"#******");
6621: for(j=1;j<=cptcoveff;j++) {
6622: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6623: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6624: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6625: }
6626: fprintf(ficrespl,"******\n");
6627: printf("******\n");
6628: fprintf(ficlog,"******\n");
6629:
6630: fprintf(ficrespl,"#Age ");
6631: for(j=1;j<=cptcoveff;j++) {
6632: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6633: }
6634: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6635: fprintf(ficrespl,"Total Years_to_converge\n");
6636:
6637: for (age=agebase; age<=agelim; age++){
6638: /* for (age=agebase; age<=agebase; age++){ */
6639: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
6640: fprintf(ficrespl,"%.0f ",age );
6641: for(j=1;j<=cptcoveff;j++)
6642: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6643: tot=0.;
6644: for(i=1; i<=nlstate;i++){
6645: tot += prlim[i][i];
6646: fprintf(ficrespl," %.5f", prlim[i][i]);
6647: }
6648: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
6649: } /* Age */
6650: /* was end of cptcod */
6651: } /* cptcov */
6652: return 0;
6653: }
6654:
6655: int hPijx(double *p, int bage, int fage){
6656: /*------------- h Pij x at various ages ------------*/
6657:
6658: int stepsize;
6659: int agelim;
6660: int hstepm;
6661: int nhstepm;
6662: int h, i, i1, j, k;
6663:
6664: double agedeb;
6665: double ***p3mat;
6666:
6667: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
6668: if((ficrespij=fopen(filerespij,"w"))==NULL) {
6669: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
6670: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
6671: }
6672: printf("Computing pij: result on file '%s' \n", filerespij);
6673: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
6674:
6675: stepsize=(int) (stepm+YEARM-1)/YEARM;
6676: /*if (stepm<=24) stepsize=2;*/
6677:
6678: agelim=AGESUP;
6679: hstepm=stepsize*YEARM; /* Every year of age */
6680: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
6681:
6682: /* hstepm=1; aff par mois*/
6683: pstamp(ficrespij);
6684: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
6685: i1= pow(2,cptcoveff);
6686: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
6687: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
6688: /* k=k+1; */
6689: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6690: fprintf(ficrespij,"\n#****** ");
6691: for(j=1;j<=cptcoveff;j++)
6692: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6693: fprintf(ficrespij,"******\n");
6694:
6695: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
6696: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
6697: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
6698:
6699: /* nhstepm=nhstepm*YEARM; aff par mois*/
6700:
6701: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6702: oldm=oldms;savm=savms;
6703: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
6704: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
6705: for(i=1; i<=nlstate;i++)
6706: for(j=1; j<=nlstate+ndeath;j++)
6707: fprintf(ficrespij," %1d-%1d",i,j);
6708: fprintf(ficrespij,"\n");
6709: for (h=0; h<=nhstepm; h++){
6710: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
6711: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
6712: for(i=1; i<=nlstate;i++)
6713: for(j=1; j<=nlstate+ndeath;j++)
6714: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
6715: fprintf(ficrespij,"\n");
6716: }
6717: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
6718: fprintf(ficrespij,"\n");
6719: }
6720: /*}*/
6721: }
6722: return 0;
6723: }
6724:
6725:
6726: /***********************************************/
6727: /**************** Main Program *****************/
6728: /***********************************************/
6729:
6730: int main(int argc, char *argv[])
6731: {
6732: #ifdef GSL
6733: const gsl_multimin_fminimizer_type *T;
6734: size_t iteri = 0, it;
6735: int rval = GSL_CONTINUE;
6736: int status = GSL_SUCCESS;
6737: double ssval;
6738: #endif
6739: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
6740: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
6741: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
6742: int jj, ll, li, lj, lk;
6743: int numlinepar=0; /* Current linenumber of parameter file */
6744: int num_filled;
6745: int itimes;
6746: int NDIM=2;
6747: int vpopbased=0;
6748:
6749: char ca[32], cb[32];
6750: /* FILE *fichtm; *//* Html File */
6751: /* FILE *ficgp;*/ /*Gnuplot File */
6752: struct stat info;
6753: double agedeb=0.;
6754:
6755: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
6756:
6757: double fret;
6758: double dum=0.; /* Dummy variable */
6759: double ***p3mat;
6760: double ***mobaverage;
6761:
6762: char line[MAXLINE];
6763: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
6764:
6765: char model[MAXLINE], modeltemp[MAXLINE];
6766: char pathr[MAXLINE], pathimach[MAXLINE];
6767: char *tok, *val; /* pathtot */
6768: int firstobs=1, lastobs=10;
6769: int c, h , cpt, c2;
6770: int jl=0;
6771: int i1, j1, jk, stepsize=0;
6772: int count=0;
6773:
6774: int *tab;
6775: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
6776: int mobilav=0,popforecast=0;
6777: int hstepm=0, nhstepm=0;
6778: int agemortsup;
6779: float sumlpop=0.;
6780: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
6781: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
6782:
6783: double bage=0, fage=110., age, agelim=0., agebase=0.;
6784: double ftolpl=FTOL;
6785: double **prlim;
6786: double ***param; /* Matrix of parameters */
6787: double *p;
6788: double **matcov; /* Matrix of covariance */
6789: double **hess; /* Hessian matrix */
6790: double ***delti3; /* Scale */
6791: double *delti; /* Scale */
6792: double ***eij, ***vareij;
6793: double **varpl; /* Variances of prevalence limits by age */
6794: double *epj, vepp;
6795:
6796: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
6797: double **ximort;
6798: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
6799: int *dcwave;
6800:
6801: char z[1]="c";
6802:
6803: /*char *strt;*/
6804: char strtend[80];
6805:
6806:
6807: /* setlocale (LC_ALL, ""); */
6808: /* bindtextdomain (PACKAGE, LOCALEDIR); */
6809: /* textdomain (PACKAGE); */
6810: /* setlocale (LC_CTYPE, ""); */
6811: /* setlocale (LC_MESSAGES, ""); */
6812:
6813: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
6814: rstart_time = time(NULL);
6815: /* (void) gettimeofday(&start_time,&tzp);*/
6816: start_time = *localtime(&rstart_time);
6817: curr_time=start_time;
6818: /*tml = *localtime(&start_time.tm_sec);*/
6819: /* strcpy(strstart,asctime(&tml)); */
6820: strcpy(strstart,asctime(&start_time));
6821:
6822: /* printf("Localtime (at start)=%s",strstart); */
6823: /* tp.tm_sec = tp.tm_sec +86400; */
6824: /* tm = *localtime(&start_time.tm_sec); */
6825: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
6826: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
6827: /* tmg.tm_hour=tmg.tm_hour + 1; */
6828: /* tp.tm_sec = mktime(&tmg); */
6829: /* strt=asctime(&tmg); */
6830: /* printf("Time(after) =%s",strstart); */
6831: /* (void) time (&time_value);
6832: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
6833: * tm = *localtime(&time_value);
6834: * strstart=asctime(&tm);
6835: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
6836: */
6837:
6838: nberr=0; /* Number of errors and warnings */
6839: nbwarn=0;
6840: #ifdef WIN32
6841: _getcwd(pathcd, size);
6842: #else
6843: getcwd(pathcd, size);
6844: #endif
6845: syscompilerinfo(0);
6846: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
6847: if(argc <=1){
6848: printf("\nEnter the parameter file name: ");
6849: if(!fgets(pathr,FILENAMELENGTH,stdin)){
6850: printf("ERROR Empty parameter file name\n");
6851: goto end;
6852: }
6853: i=strlen(pathr);
6854: if(pathr[i-1]=='\n')
6855: pathr[i-1]='\0';
6856: i=strlen(pathr);
6857: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
6858: pathr[i-1]='\0';
6859: }
6860: i=strlen(pathr);
6861: if( i==0 ){
6862: printf("ERROR Empty parameter file name\n");
6863: goto end;
6864: }
6865: for (tok = pathr; tok != NULL; ){
6866: printf("Pathr |%s|\n",pathr);
6867: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
6868: printf("val= |%s| pathr=%s\n",val,pathr);
6869: strcpy (pathtot, val);
6870: if(pathr[0] == '\0') break; /* Dirty */
6871: }
6872: }
6873: else{
6874: strcpy(pathtot,argv[1]);
6875: }
6876: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
6877: /*cygwin_split_path(pathtot,path,optionfile);
6878: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
6879: /* cutv(path,optionfile,pathtot,'\\');*/
6880:
6881: /* Split argv[0], imach program to get pathimach */
6882: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
6883: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6884: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
6885: /* strcpy(pathimach,argv[0]); */
6886: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
6887: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
6888: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
6889: #ifdef WIN32
6890: _chdir(path); /* Can be a relative path */
6891: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
6892: #else
6893: chdir(path); /* Can be a relative path */
6894: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
6895: #endif
6896: printf("Current directory %s!\n",pathcd);
6897: strcpy(command,"mkdir ");
6898: strcat(command,optionfilefiname);
6899: if((outcmd=system(command)) != 0){
6900: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
6901: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
6902: /* fclose(ficlog); */
6903: /* exit(1); */
6904: }
6905: /* if((imk=mkdir(optionfilefiname))<0){ */
6906: /* perror("mkdir"); */
6907: /* } */
6908:
6909: /*-------- arguments in the command line --------*/
6910:
6911: /* Main Log file */
6912: strcat(filelog, optionfilefiname);
6913: strcat(filelog,".log"); /* */
6914: if((ficlog=fopen(filelog,"w"))==NULL) {
6915: printf("Problem with logfile %s\n",filelog);
6916: goto end;
6917: }
6918: fprintf(ficlog,"Log filename:%s\n",filelog);
6919: fprintf(ficlog,"Version %s %s",version,fullversion);
6920: fprintf(ficlog,"\nEnter the parameter file name: \n");
6921: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
6922: path=%s \n\
6923: optionfile=%s\n\
6924: optionfilext=%s\n\
6925: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
6926:
6927: syscompilerinfo(1);
6928:
6929: printf("Local time (at start):%s",strstart);
6930: fprintf(ficlog,"Local time (at start): %s",strstart);
6931: fflush(ficlog);
6932: /* (void) gettimeofday(&curr_time,&tzp); */
6933: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
6934:
6935: /* */
6936: strcpy(fileres,"r");
6937: strcat(fileres, optionfilefiname);
6938: strcat(fileresu, optionfilefiname); /* Without r in front */
6939: strcat(fileres,".txt"); /* Other files have txt extension */
6940: strcat(fileresu,".txt"); /* Other files have txt extension */
6941:
6942: /* Main ---------arguments file --------*/
6943:
6944: if((ficpar=fopen(optionfile,"r"))==NULL) {
6945: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6946: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6947: fflush(ficlog);
6948: /* goto end; */
6949: exit(70);
6950: }
6951:
6952:
6953:
6954: strcpy(filereso,"o");
6955: strcat(filereso,fileresu);
6956: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6957: printf("Problem with Output resultfile: %s\n", filereso);
6958: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6959: fflush(ficlog);
6960: goto end;
6961: }
6962:
6963: /* Reads comments: lines beginning with '#' */
6964: numlinepar=0;
6965:
6966: /* First parameter line */
6967: while(fgets(line, MAXLINE, ficpar)) {
6968: /* If line starts with a # it is a comment */
6969: if (line[0] == '#') {
6970: numlinepar++;
6971: fputs(line,stdout);
6972: fputs(line,ficparo);
6973: fputs(line,ficlog);
6974: continue;
6975: }else
6976: break;
6977: }
6978: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
6979: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
6980: if (num_filled != 5) {
6981: printf("Should be 5 parameters\n");
6982: }
6983: numlinepar++;
6984: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
6985: }
6986: /* Second parameter line */
6987: while(fgets(line, MAXLINE, ficpar)) {
6988: /* If line starts with a # it is a comment */
6989: if (line[0] == '#') {
6990: numlinepar++;
6991: fputs(line,stdout);
6992: fputs(line,ficparo);
6993: fputs(line,ficlog);
6994: continue;
6995: }else
6996: break;
6997: }
6998: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
6999: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7000: if (num_filled != 8) {
7001: 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");
7002: printf("but line=%s\n",line);
7003: }
7004: 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);
7005: }
7006: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
7007: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
7008: /* Third parameter line */
7009: while(fgets(line, MAXLINE, ficpar)) {
7010: /* If line starts with a # it is a comment */
7011: if (line[0] == '#') {
7012: numlinepar++;
7013: fputs(line,stdout);
7014: fputs(line,ficparo);
7015: fputs(line,ficlog);
7016: continue;
7017: }else
7018: break;
7019: }
7020: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7021: if (num_filled == 0)
7022: model[0]='\0';
7023: else if (num_filled != 1){
7024: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7025: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7026: model[0]='\0';
7027: goto end;
7028: }
7029: else{
7030: if (model[0]=='+'){
7031: for(i=1; i<=strlen(model);i++)
7032: modeltemp[i-1]=model[i];
7033: strcpy(model,modeltemp);
7034: }
7035: }
7036: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
7037: printf("model=1+age+%s\n",model);fflush(stdout);
7038: }
7039: /* 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); */
7040: /* numlinepar=numlinepar+3; /\* In general *\/ */
7041: /* 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); */
7042: 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);
7043: 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);
7044: fflush(ficlog);
7045: /* if(model[0]=='#'|| model[0]== '\0'){ */
7046: if(model[0]=='#'){
7047: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7048: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7049: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7050: if(mle != -1){
7051: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7052: exit(1);
7053: }
7054: }
7055: while((c=getc(ficpar))=='#' && c!= EOF){
7056: ungetc(c,ficpar);
7057: fgets(line, MAXLINE, ficpar);
7058: numlinepar++;
7059: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7060: z[0]=line[1];
7061: }
7062: /* printf("****line [1] = %c \n",line[1]); */
7063: fputs(line, stdout);
7064: //puts(line);
7065: fputs(line,ficparo);
7066: fputs(line,ficlog);
7067: }
7068: ungetc(c,ficpar);
7069:
7070:
7071: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
7072: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7073: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7074: v1+v2*age+v2*v3 makes cptcovn = 3
7075: */
7076: if (strlen(model)>1)
7077: 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*/
7078: else
7079: ncovmodel=2; /* Constant and age */
7080: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7081: npar= nforce*ncovmodel; /* Number of parameters like aij*/
7082: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7083: 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);
7084: 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);
7085: fflush(stdout);
7086: fclose (ficlog);
7087: goto end;
7088: }
7089: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7090: delti=delti3[1][1];
7091: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7092: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7093: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7094: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7095: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7096: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7097: fclose (ficparo);
7098: fclose (ficlog);
7099: goto end;
7100: exit(0);
7101: }
7102: else if(mle==-3) { /* Main Wizard */
7103: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7104: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7105: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7106: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7107: matcov=matrix(1,npar,1,npar);
7108: hess=matrix(1,npar,1,npar);
7109: }
7110: else{
7111: /* Read guessed parameters */
7112: /* Reads comments: lines beginning with '#' */
7113: while((c=getc(ficpar))=='#' && c!= EOF){
7114: ungetc(c,ficpar);
7115: fgets(line, MAXLINE, ficpar);
7116: numlinepar++;
7117: fputs(line,stdout);
7118: fputs(line,ficparo);
7119: fputs(line,ficlog);
7120: }
7121: ungetc(c,ficpar);
7122:
7123: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7124: for(i=1; i <=nlstate; i++){
7125: j=0;
7126: for(jj=1; jj <=nlstate+ndeath; jj++){
7127: if(jj==i) continue;
7128: j++;
7129: fscanf(ficpar,"%1d%1d",&i1,&j1);
7130: if ((i1 != i) || (j1 != jj)){
7131: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7132: It might be a problem of design; if ncovcol and the model are correct\n \
7133: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7134: exit(1);
7135: }
7136: fprintf(ficparo,"%1d%1d",i1,j1);
7137: if(mle==1)
7138: printf("%1d%1d",i,jj);
7139: fprintf(ficlog,"%1d%1d",i,jj);
7140: for(k=1; k<=ncovmodel;k++){
7141: fscanf(ficpar," %lf",¶m[i][j][k]);
7142: if(mle==1){
7143: printf(" %lf",param[i][j][k]);
7144: fprintf(ficlog," %lf",param[i][j][k]);
7145: }
7146: else
7147: fprintf(ficlog," %lf",param[i][j][k]);
7148: fprintf(ficparo," %lf",param[i][j][k]);
7149: }
7150: fscanf(ficpar,"\n");
7151: numlinepar++;
7152: if(mle==1)
7153: printf("\n");
7154: fprintf(ficlog,"\n");
7155: fprintf(ficparo,"\n");
7156: }
7157: }
7158: fflush(ficlog);
7159:
7160: /* Reads scales values */
7161: p=param[1][1];
7162:
7163: /* Reads comments: lines beginning with '#' */
7164: while((c=getc(ficpar))=='#' && c!= EOF){
7165: ungetc(c,ficpar);
7166: fgets(line, MAXLINE, ficpar);
7167: numlinepar++;
7168: fputs(line,stdout);
7169: fputs(line,ficparo);
7170: fputs(line,ficlog);
7171: }
7172: ungetc(c,ficpar);
7173:
7174: for(i=1; i <=nlstate; i++){
7175: for(j=1; j <=nlstate+ndeath-1; j++){
7176: fscanf(ficpar,"%1d%1d",&i1,&j1);
7177: if ( (i1-i) * (j1-j) != 0){
7178: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7179: exit(1);
7180: }
7181: printf("%1d%1d",i,j);
7182: fprintf(ficparo,"%1d%1d",i1,j1);
7183: fprintf(ficlog,"%1d%1d",i1,j1);
7184: for(k=1; k<=ncovmodel;k++){
7185: fscanf(ficpar,"%le",&delti3[i][j][k]);
7186: printf(" %le",delti3[i][j][k]);
7187: fprintf(ficparo," %le",delti3[i][j][k]);
7188: fprintf(ficlog," %le",delti3[i][j][k]);
7189: }
7190: fscanf(ficpar,"\n");
7191: numlinepar++;
7192: printf("\n");
7193: fprintf(ficparo,"\n");
7194: fprintf(ficlog,"\n");
7195: }
7196: }
7197: fflush(ficlog);
7198:
7199: /* Reads covariance matrix */
7200: delti=delti3[1][1];
7201:
7202:
7203: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7204:
7205: /* Reads comments: lines beginning with '#' */
7206: while((c=getc(ficpar))=='#' && c!= EOF){
7207: ungetc(c,ficpar);
7208: fgets(line, MAXLINE, ficpar);
7209: numlinepar++;
7210: fputs(line,stdout);
7211: fputs(line,ficparo);
7212: fputs(line,ficlog);
7213: }
7214: ungetc(c,ficpar);
7215:
7216: matcov=matrix(1,npar,1,npar);
7217: hess=matrix(1,npar,1,npar);
7218: for(i=1; i <=npar; i++)
7219: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7220:
7221: /* Scans npar lines */
7222: for(i=1; i <=npar; i++){
7223: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7224: if(count != 3){
7225: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7226: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7227: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7228: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7229: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7230: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7231: exit(1);
7232: }else
7233: if(mle==1)
7234: printf("%1d%1d%1d",i1,j1,jk);
7235: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7236: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7237: for(j=1; j <=i; j++){
7238: fscanf(ficpar," %le",&matcov[i][j]);
7239: if(mle==1){
7240: printf(" %.5le",matcov[i][j]);
7241: }
7242: fprintf(ficlog," %.5le",matcov[i][j]);
7243: fprintf(ficparo," %.5le",matcov[i][j]);
7244: }
7245: fscanf(ficpar,"\n");
7246: numlinepar++;
7247: if(mle==1)
7248: printf("\n");
7249: fprintf(ficlog,"\n");
7250: fprintf(ficparo,"\n");
7251: }
7252: /* End of read covariance matrix npar lines */
7253: for(i=1; i <=npar; i++)
7254: for(j=i+1;j<=npar;j++)
7255: matcov[i][j]=matcov[j][i];
7256:
7257: if(mle==1)
7258: printf("\n");
7259: fprintf(ficlog,"\n");
7260:
7261: fflush(ficlog);
7262:
7263: /*-------- Rewriting parameter file ----------*/
7264: strcpy(rfileres,"r"); /* "Rparameterfile */
7265: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7266: strcat(rfileres,"."); /* */
7267: strcat(rfileres,optionfilext); /* Other files have txt extension */
7268: if((ficres =fopen(rfileres,"w"))==NULL) {
7269: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7270: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7271: }
7272: fprintf(ficres,"#%s\n",version);
7273: } /* End of mle != -3 */
7274:
7275: /* Main data
7276: */
7277: n= lastobs;
7278: num=lvector(1,n);
7279: moisnais=vector(1,n);
7280: annais=vector(1,n);
7281: moisdc=vector(1,n);
7282: andc=vector(1,n);
7283: agedc=vector(1,n);
7284: cod=ivector(1,n);
7285: weight=vector(1,n);
7286: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7287: mint=matrix(1,maxwav,1,n);
7288: anint=matrix(1,maxwav,1,n);
7289: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7290: tab=ivector(1,NCOVMAX);
7291: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7292: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7293:
7294: /* Reads data from file datafile */
7295: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7296: goto end;
7297:
7298: /* Calculation of the number of parameters from char model */
7299: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7300: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7301: k=3 V4 Tvar[k=3]= 4 (from V4)
7302: k=2 V1 Tvar[k=2]= 1 (from V1)
7303: k=1 Tvar[1]=2 (from V2)
7304: */
7305: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7306: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7307: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7308: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7309: */
7310: /* For model-covariate k tells which data-covariate to use but
7311: because this model-covariate is a construction we invent a new column
7312: ncovcol + k1
7313: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7314: Tvar[3=V1*V4]=4+1 etc */
7315: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7316: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7317: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7318: */
7319: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7320: 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
7321: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7322: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7323: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7324: 4 covariates (3 plus signs)
7325: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7326: */
7327:
7328: /* Main decodemodel */
7329:
7330:
7331: if(decodemodel(model, lastobs) == 1)
7332: goto end;
7333:
7334: if((double)(lastobs-imx)/(double)imx > 1.10){
7335: nbwarn++;
7336: 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);
7337: 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);
7338: }
7339: /* if(mle==1){*/
7340: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7341: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7342: }
7343:
7344: /*-calculation of age at interview from date of interview and age at death -*/
7345: agev=matrix(1,maxwav,1,imx);
7346:
7347: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7348: goto end;
7349:
7350:
7351: agegomp=(int)agemin;
7352: free_vector(moisnais,1,n);
7353: free_vector(annais,1,n);
7354: /* free_matrix(mint,1,maxwav,1,n);
7355: free_matrix(anint,1,maxwav,1,n);*/
7356: free_vector(moisdc,1,n);
7357: free_vector(andc,1,n);
7358: /* */
7359:
7360: wav=ivector(1,imx);
7361: dh=imatrix(1,lastpass-firstpass+1,1,imx);
7362: bh=imatrix(1,lastpass-firstpass+1,1,imx);
7363: mw=imatrix(1,lastpass-firstpass+1,1,imx);
7364:
7365: /* Concatenates waves */
7366: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7367: /* */
7368:
7369: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7370:
7371: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7372: ncodemax[1]=1;
7373: Ndum =ivector(-1,NCOVMAX);
7374: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7375: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7376: /* Nbcode gives the value of the lth modality of jth covariate, in
7377: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7378: /* 1 to ncodemax[j] is the maximum value of this jth covariate */
7379:
7380: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7381: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7382: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7383: h=0;
7384:
7385:
7386: /*if (cptcovn > 0) */
7387:
7388:
7389: m=pow(2,cptcoveff);
7390:
7391: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7392: * For k=4 covariates, h goes from 1 to 2**k
7393: * codtabm(h,k)= 1 & (h-1) >> (k-1) ;
7394: * h\k 1 2 3 4
7395: *______________________________
7396: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7397: * 2 2 1 1 1
7398: * 3 i=2 1 2 1 1
7399: * 4 2 2 1 1
7400: * 5 i=3 1 i=2 1 2 1
7401: * 6 2 1 2 1
7402: * 7 i=4 1 2 2 1
7403: * 8 2 2 2 1
7404: * 9 i=5 1 i=3 1 i=2 1 2
7405: * 10 2 1 1 2
7406: * 11 i=6 1 2 1 2
7407: * 12 2 2 1 2
7408: * 13 i=7 1 i=4 1 2 2
7409: * 14 2 1 2 2
7410: * 15 i=8 1 2 2 2
7411: * 16 2 2 2 2
7412: */
7413: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7414: /* /\* printf("h=%2d ", h); *\/ */
7415: /* /\* for(k=1; k <=10; k++){ *\/ */
7416: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7417: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7418: /* /\* } *\/ */
7419: /* /\* printf("\n"); *\/ */
7420: /* } */
7421: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7422: /* 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 *\/ */
7423: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7424: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7425: /* h++; */
7426: /* if (h>m) */
7427: /* h=1; */
7428: /* codtab[h][k]=j; */
7429: /* /\* codtab[12][3]=1; *\/ */
7430: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7431: /* /\* 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]]); *\/ */
7432: /* } */
7433: /* } */
7434: /* } */
7435: /* } */
7436: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7437: codtab[1][2]=1;codtab[2][2]=2; */
7438: /* for(i=1; i <=m ;i++){ */
7439: /* for(k=1; k <=cptcovn; k++){ */
7440: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7441: /* } */
7442: /* printf("\n"); */
7443: /* } */
7444: /* scanf("%d",i);*/
7445:
7446: free_ivector(Ndum,-1,NCOVMAX);
7447:
7448:
7449:
7450: /* Initialisation of ----------- gnuplot -------------*/
7451: strcpy(optionfilegnuplot,optionfilefiname);
7452: if(mle==-3)
7453: strcat(optionfilegnuplot,"-MORT_");
7454: strcat(optionfilegnuplot,".gp");
7455:
7456: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7457: printf("Problem with file %s",optionfilegnuplot);
7458: }
7459: else{
7460: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7461: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7462: //fprintf(ficgp,"set missing 'NaNq'\n");
7463: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7464: }
7465: /* fclose(ficgp);*/
7466:
7467:
7468: /* Initialisation of --------- index.htm --------*/
7469:
7470: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7471: if(mle==-3)
7472: strcat(optionfilehtm,"-MORT_");
7473: strcat(optionfilehtm,".htm");
7474: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7475: printf("Problem with %s \n",optionfilehtm);
7476: exit(0);
7477: }
7478:
7479: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7480: strcat(optionfilehtmcov,"-cov.htm");
7481: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7482: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7483: }
7484: else{
7485: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7486: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7487: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7488: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7489: }
7490:
7491: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br> \
7492: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7493: <font size=\"2\">IMaCh-%s <br> %s</font> \
7494: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7495: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7496: \n\
7497: <hr size=\"2\" color=\"#EC5E5E\">\
7498: <ul><li><h4>Parameter files</h4>\n\
7499: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7500: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7501: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7502: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7503: - Date and time at start: %s</ul>\n",\
7504: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7505: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7506: fileres,fileres,\
7507: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7508: fflush(fichtm);
7509:
7510: strcpy(pathr,path);
7511: strcat(pathr,optionfilefiname);
7512: #ifdef WIN32
7513: _chdir(optionfilefiname); /* Move to directory named optionfile */
7514: #else
7515: chdir(optionfilefiname); /* Move to directory named optionfile */
7516: #endif
7517:
7518:
7519: /* Calculates basic frequencies. Computes observed prevalence at single age
7520: and prints on file fileres'p'. */
7521: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
7522:
7523: fprintf(fichtm,"\n");
7524: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7525: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7526: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7527: imx,agemin,agemax,jmin,jmax,jmean);
7528: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7529: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7530: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7531: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7532: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7533:
7534:
7535: /* For Powell, parameters are in a vector p[] starting at p[1]
7536: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7537: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7538:
7539: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7540: /* For mortality only */
7541: if (mle==-3){
7542: ximort=matrix(1,NDIM,1,NDIM);
7543: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7544: cens=ivector(1,n);
7545: ageexmed=vector(1,n);
7546: agecens=vector(1,n);
7547: dcwave=ivector(1,n);
7548:
7549: for (i=1; i<=imx; i++){
7550: dcwave[i]=-1;
7551: for (m=firstpass; m<=lastpass; m++)
7552: if (s[m][i]>nlstate) {
7553: dcwave[i]=m;
7554: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7555: break;
7556: }
7557: }
7558:
7559: for (i=1; i<=imx; i++) {
7560: if (wav[i]>0){
7561: ageexmed[i]=agev[mw[1][i]][i];
7562: j=wav[i];
7563: agecens[i]=1.;
7564:
7565: if (ageexmed[i]> 1 && wav[i] > 0){
7566: agecens[i]=agev[mw[j][i]][i];
7567: cens[i]= 1;
7568: }else if (ageexmed[i]< 1)
7569: cens[i]= -1;
7570: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7571: cens[i]=0 ;
7572: }
7573: else cens[i]=-1;
7574: }
7575:
7576: for (i=1;i<=NDIM;i++) {
7577: for (j=1;j<=NDIM;j++)
7578: ximort[i][j]=(i == j ? 1.0 : 0.0);
7579: }
7580:
7581: /*p[1]=0.0268; p[NDIM]=0.083;*/
7582: /*printf("%lf %lf", p[1], p[2]);*/
7583:
7584:
7585: #ifdef GSL
7586: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
7587: #else
7588: printf("Powell\n"); fprintf(ficlog,"Powell\n");
7589: #endif
7590: strcpy(filerespow,"POW-MORT_");
7591: strcat(filerespow,fileresu);
7592: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7593: printf("Problem with resultfile: %s\n", filerespow);
7594: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7595: }
7596: #ifdef GSL
7597: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
7598: #else
7599: fprintf(ficrespow,"# Powell\n# iter -2*LL");
7600: #endif
7601: /* for (i=1;i<=nlstate;i++)
7602: for(j=1;j<=nlstate+ndeath;j++)
7603: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
7604: */
7605: fprintf(ficrespow,"\n");
7606: #ifdef GSL
7607: /* gsl starts here */
7608: T = gsl_multimin_fminimizer_nmsimplex;
7609: gsl_multimin_fminimizer *sfm = NULL;
7610: gsl_vector *ss, *x;
7611: gsl_multimin_function minex_func;
7612:
7613: /* Initial vertex size vector */
7614: ss = gsl_vector_alloc (NDIM);
7615:
7616: if (ss == NULL){
7617: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
7618: }
7619: /* Set all step sizes to 1 */
7620: gsl_vector_set_all (ss, 0.001);
7621:
7622: /* Starting point */
7623:
7624: x = gsl_vector_alloc (NDIM);
7625:
7626: if (x == NULL){
7627: gsl_vector_free(ss);
7628: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
7629: }
7630:
7631: /* Initialize method and iterate */
7632: /* p[1]=0.0268; p[NDIM]=0.083; */
7633: /* gsl_vector_set(x, 0, 0.0268); */
7634: /* gsl_vector_set(x, 1, 0.083); */
7635: gsl_vector_set(x, 0, p[1]);
7636: gsl_vector_set(x, 1, p[2]);
7637:
7638: minex_func.f = &gompertz_f;
7639: minex_func.n = NDIM;
7640: minex_func.params = (void *)&p; /* ??? */
7641:
7642: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
7643: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
7644:
7645: printf("Iterations beginning .....\n\n");
7646: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
7647:
7648: iteri=0;
7649: while (rval == GSL_CONTINUE){
7650: iteri++;
7651: status = gsl_multimin_fminimizer_iterate(sfm);
7652:
7653: if (status) printf("error: %s\n", gsl_strerror (status));
7654: fflush(0);
7655:
7656: if (status)
7657: break;
7658:
7659: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
7660: ssval = gsl_multimin_fminimizer_size (sfm);
7661:
7662: if (rval == GSL_SUCCESS)
7663: printf ("converged to a local maximum at\n");
7664:
7665: printf("%5d ", iteri);
7666: for (it = 0; it < NDIM; it++){
7667: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
7668: }
7669: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
7670: }
7671:
7672: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
7673:
7674: gsl_vector_free(x); /* initial values */
7675: gsl_vector_free(ss); /* inital step size */
7676: for (it=0; it<NDIM; it++){
7677: p[it+1]=gsl_vector_get(sfm->x,it);
7678: fprintf(ficrespow," %.12lf", p[it]);
7679: }
7680: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
7681: #endif
7682: #ifdef POWELL
7683: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
7684: #endif
7685: fclose(ficrespow);
7686:
7687: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
7688:
7689: for(i=1; i <=NDIM; i++)
7690: for(j=i+1;j<=NDIM;j++)
7691: matcov[i][j]=matcov[j][i];
7692:
7693: printf("\nCovariance matrix\n ");
7694: fprintf(ficlog,"\nCovariance matrix\n ");
7695: for(i=1; i <=NDIM; i++) {
7696: for(j=1;j<=NDIM;j++){
7697: printf("%f ",matcov[i][j]);
7698: fprintf(ficlog,"%f ",matcov[i][j]);
7699: }
7700: printf("\n "); fprintf(ficlog,"\n ");
7701: }
7702:
7703: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
7704: for (i=1;i<=NDIM;i++) {
7705: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7706: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
7707: }
7708: lsurv=vector(1,AGESUP);
7709: lpop=vector(1,AGESUP);
7710: tpop=vector(1,AGESUP);
7711: lsurv[agegomp]=100000;
7712:
7713: for (k=agegomp;k<=AGESUP;k++) {
7714: agemortsup=k;
7715: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
7716: }
7717:
7718: for (k=agegomp;k<agemortsup;k++)
7719: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
7720:
7721: for (k=agegomp;k<agemortsup;k++){
7722: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
7723: sumlpop=sumlpop+lpop[k];
7724: }
7725:
7726: tpop[agegomp]=sumlpop;
7727: for (k=agegomp;k<(agemortsup-3);k++){
7728: /* tpop[k+1]=2;*/
7729: tpop[k+1]=tpop[k]-lpop[k];
7730: }
7731:
7732:
7733: printf("\nAge lx qx dx Lx Tx e(x)\n");
7734: for (k=agegomp;k<(agemortsup-2);k++)
7735: 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]);
7736:
7737:
7738: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
7739: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
7740: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7741: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7742: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7743: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
7744: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
7745: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
7746: }else
7747: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
7748: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
7749: stepm, weightopt,\
7750: model,imx,p,matcov,agemortsup);
7751:
7752: free_vector(lsurv,1,AGESUP);
7753: free_vector(lpop,1,AGESUP);
7754: free_vector(tpop,1,AGESUP);
7755: #ifdef GSL
7756: free_ivector(cens,1,n);
7757: free_vector(agecens,1,n);
7758: free_ivector(dcwave,1,n);
7759: free_matrix(ximort,1,NDIM,1,NDIM);
7760: #endif
7761: } /* Endof if mle==-3 mortality only */
7762: /* Standard */
7763: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
7764: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7765: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7766: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7767: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7768: for (k=1; k<=npar;k++)
7769: printf(" %d %8.5f",k,p[k]);
7770: printf("\n");
7771: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
7772: /* mlikeli uses func not funcone */
7773: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
7774: }
7775: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
7776: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
7777: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
7778: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7779: }
7780: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
7781: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
7782: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
7783: for (k=1; k<=npar;k++)
7784: printf(" %d %8.5f",k,p[k]);
7785: printf("\n");
7786:
7787: /*--------- results files --------------*/
7788: 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);
7789:
7790:
7791: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7792: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7793: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
7794: for(i=1,jk=1; i <=nlstate; i++){
7795: for(k=1; k <=(nlstate+ndeath); k++){
7796: if (k != i) {
7797: printf("%d%d ",i,k);
7798: fprintf(ficlog,"%d%d ",i,k);
7799: fprintf(ficres,"%1d%1d ",i,k);
7800: for(j=1; j <=ncovmodel; j++){
7801: printf("%12.7f ",p[jk]);
7802: fprintf(ficlog,"%12.7f ",p[jk]);
7803: fprintf(ficres,"%12.7f ",p[jk]);
7804: jk++;
7805: }
7806: printf("\n");
7807: fprintf(ficlog,"\n");
7808: fprintf(ficres,"\n");
7809: }
7810: }
7811: }
7812: if(mle != 0){
7813: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
7814: ftolhess=ftol; /* Usually correct */
7815: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
7816: 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");
7817: 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");
7818: for(i=1,jk=1; i <=nlstate; i++){
7819: for(k=1; k <=(nlstate+ndeath); k++){
7820: if (k != i) {
7821: printf("%d%d ",i,k);
7822: fprintf(ficlog,"%d%d ",i,k);
7823: for(j=1; j <=ncovmodel; j++){
7824: 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]));
7825: 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]));
7826: jk++;
7827: }
7828: printf("\n");
7829: fprintf(ficlog,"\n");
7830: }
7831: }
7832: }
7833: } /* end of hesscov and Wald tests */
7834:
7835: /* */
7836: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
7837: printf("# Scales (for hessian or gradient estimation)\n");
7838: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
7839: for(i=1,jk=1; i <=nlstate; i++){
7840: for(j=1; j <=nlstate+ndeath; j++){
7841: if (j!=i) {
7842: fprintf(ficres,"%1d%1d",i,j);
7843: printf("%1d%1d",i,j);
7844: fprintf(ficlog,"%1d%1d",i,j);
7845: for(k=1; k<=ncovmodel;k++){
7846: printf(" %.5e",delti[jk]);
7847: fprintf(ficlog," %.5e",delti[jk]);
7848: fprintf(ficres," %.5e",delti[jk]);
7849: jk++;
7850: }
7851: printf("\n");
7852: fprintf(ficlog,"\n");
7853: fprintf(ficres,"\n");
7854: }
7855: }
7856: }
7857:
7858: 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");
7859: if(mle >= 1) /* To big for the screen */
7860: 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");
7861: 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");
7862: /* # 121 Var(a12)\n\ */
7863: /* # 122 Cov(b12,a12) Var(b12)\n\ */
7864: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
7865: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
7866: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
7867: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
7868: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
7869: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
7870:
7871:
7872: /* Just to have a covariance matrix which will be more understandable
7873: even is we still don't want to manage dictionary of variables
7874: */
7875: for(itimes=1;itimes<=2;itimes++){
7876: jj=0;
7877: for(i=1; i <=nlstate; i++){
7878: for(j=1; j <=nlstate+ndeath; j++){
7879: if(j==i) continue;
7880: for(k=1; k<=ncovmodel;k++){
7881: jj++;
7882: ca[0]= k+'a'-1;ca[1]='\0';
7883: if(itimes==1){
7884: if(mle>=1)
7885: printf("#%1d%1d%d",i,j,k);
7886: fprintf(ficlog,"#%1d%1d%d",i,j,k);
7887: fprintf(ficres,"#%1d%1d%d",i,j,k);
7888: }else{
7889: if(mle>=1)
7890: printf("%1d%1d%d",i,j,k);
7891: fprintf(ficlog,"%1d%1d%d",i,j,k);
7892: fprintf(ficres,"%1d%1d%d",i,j,k);
7893: }
7894: ll=0;
7895: for(li=1;li <=nlstate; li++){
7896: for(lj=1;lj <=nlstate+ndeath; lj++){
7897: if(lj==li) continue;
7898: for(lk=1;lk<=ncovmodel;lk++){
7899: ll++;
7900: if(ll<=jj){
7901: cb[0]= lk +'a'-1;cb[1]='\0';
7902: if(ll<jj){
7903: if(itimes==1){
7904: if(mle>=1)
7905: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7906: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7907: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
7908: }else{
7909: if(mle>=1)
7910: printf(" %.5e",matcov[jj][ll]);
7911: fprintf(ficlog," %.5e",matcov[jj][ll]);
7912: fprintf(ficres," %.5e",matcov[jj][ll]);
7913: }
7914: }else{
7915: if(itimes==1){
7916: if(mle>=1)
7917: printf(" Var(%s%1d%1d)",ca,i,j);
7918: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
7919: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
7920: }else{
7921: if(mle>=1)
7922: printf(" %.7e",matcov[jj][ll]);
7923: fprintf(ficlog," %.7e",matcov[jj][ll]);
7924: fprintf(ficres," %.7e",matcov[jj][ll]);
7925: }
7926: }
7927: }
7928: } /* end lk */
7929: } /* end lj */
7930: } /* end li */
7931: if(mle>=1)
7932: printf("\n");
7933: fprintf(ficlog,"\n");
7934: fprintf(ficres,"\n");
7935: numlinepar++;
7936: } /* end k*/
7937: } /*end j */
7938: } /* end i */
7939: } /* end itimes */
7940:
7941: fflush(ficlog);
7942: fflush(ficres);
7943: while(fgets(line, MAXLINE, ficpar)) {
7944: /* If line starts with a # it is a comment */
7945: if (line[0] == '#') {
7946: numlinepar++;
7947: fputs(line,stdout);
7948: fputs(line,ficparo);
7949: fputs(line,ficlog);
7950: continue;
7951: }else
7952: break;
7953: }
7954:
7955: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
7956: /* ungetc(c,ficpar); */
7957: /* fgets(line, MAXLINE, ficpar); */
7958: /* fputs(line,stdout); */
7959: /* fputs(line,ficparo); */
7960: /* } */
7961: /* ungetc(c,ficpar); */
7962:
7963: estepm=0;
7964: 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){
7965:
7966: if (num_filled != 6) {
7967: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
7968: printf("but line=%s\n",line);
7969: goto end;
7970: }
7971: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
7972: }
7973: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
7974: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
7975:
7976: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
7977: if (estepm==0 || estepm < stepm) estepm=stepm;
7978: if (fage <= 2) {
7979: bage = ageminpar;
7980: fage = agemaxpar;
7981: }
7982:
7983: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
7984: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7985: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
7986:
7987: /* Other stuffs, more or less useful */
7988: while((c=getc(ficpar))=='#' && c!= EOF){
7989: ungetc(c,ficpar);
7990: fgets(line, MAXLINE, ficpar);
7991: fputs(line,stdout);
7992: fputs(line,ficparo);
7993: }
7994: ungetc(c,ficpar);
7995:
7996: 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);
7997: 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);
7998: 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);
7999: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8000: 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);
8001:
8002: while((c=getc(ficpar))=='#' && c!= EOF){
8003: ungetc(c,ficpar);
8004: fgets(line, MAXLINE, ficpar);
8005: fputs(line,stdout);
8006: fputs(line,ficparo);
8007: }
8008: ungetc(c,ficpar);
8009:
8010:
8011: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8012: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8013:
8014: fscanf(ficpar,"pop_based=%d\n",&popbased);
8015: fprintf(ficlog,"pop_based=%d\n",popbased);
8016: fprintf(ficparo,"pop_based=%d\n",popbased);
8017: fprintf(ficres,"pop_based=%d\n",popbased);
8018:
8019: while((c=getc(ficpar))=='#' && c!= EOF){
8020: ungetc(c,ficpar);
8021: fgets(line, MAXLINE, ficpar);
8022: fputs(line,stdout);
8023: fputs(line,ficparo);
8024: }
8025: ungetc(c,ficpar);
8026:
8027: 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);
8028: 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);
8029: 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);
8030: 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);
8031: 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);
8032: /* day and month of proj2 are not used but only year anproj2.*/
8033:
8034:
8035:
8036: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8037: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
8038:
8039: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8040: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8041: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8042: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8043: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8044: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8045: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8046: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8047: }else
8048: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8049:
8050: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
8051: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
8052: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
8053:
8054: /*------------ free_vector -------------*/
8055: /* chdir(path); */
8056:
8057: free_ivector(wav,1,imx);
8058: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
8059: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
8060: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
8061: free_lvector(num,1,n);
8062: free_vector(agedc,1,n);
8063: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8064: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8065: fclose(ficparo);
8066: fclose(ficres);
8067:
8068:
8069: /* Other results (useful)*/
8070:
8071:
8072: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
8073: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8074: prlim=matrix(1,nlstate,1,nlstate);
8075: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
8076: fclose(ficrespl);
8077:
8078: #ifdef FREEEXIT2
8079: #include "freeexit2.h"
8080: #endif
8081:
8082: /*------------- h Pij x at various ages ------------*/
8083: /*#include "hpijx.h"*/
8084: hPijx(p, bage, fage);
8085: fclose(ficrespij);
8086:
8087: /*-------------- Variance of one-step probabilities---*/
8088: k=1;
8089: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8090:
8091:
8092: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8093: for(i=1;i<=AGESUP;i++)
8094: for(j=1;j<=NCOVMAX;j++)
8095: for(k=1;k<=NCOVMAX;k++)
8096: probs[i][j][k]=0.;
8097:
8098: /*---------- Forecasting ------------------*/
8099: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8100: if(prevfcast==1){
8101: /* if(stepm ==1){*/
8102: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
8103: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8104: /* } */
8105: /* else{ */
8106: /* erreur=108; */
8107: /* 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); */
8108: /* 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); */
8109: /* } */
8110: }
8111:
8112: /* ------ Other prevalence ratios------------ */
8113:
8114: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8115:
8116: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8117: /* 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",\
8118: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8119: */
8120:
8121: if (mobilav!=0) {
8122: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8123: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8124: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8125: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8126: }
8127: }
8128:
8129:
8130: /*---------- Health expectancies, no variances ------------*/
8131:
8132: strcpy(filerese,"E_");
8133: strcat(filerese,fileresu);
8134: if((ficreseij=fopen(filerese,"w"))==NULL) {
8135: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8136: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8137: }
8138: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8139: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
8140: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8141: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8142:
8143: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8144: fprintf(ficreseij,"\n#****** ");
8145: for(j=1;j<=cptcoveff;j++) {
8146: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8147: }
8148: fprintf(ficreseij,"******\n");
8149:
8150: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8151: oldm=oldms;savm=savms;
8152: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8153:
8154: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8155: /*}*/
8156: }
8157: fclose(ficreseij);
8158: printf("done evsij\n");fflush(stdout);
8159: fprintf(ficlog,"done evsij\n");fflush(ficlog);
8160:
8161: /*---------- Health expectancies and variances ------------*/
8162:
8163:
8164: strcpy(filerest,"T_");
8165: strcat(filerest,fileresu);
8166: if((ficrest=fopen(filerest,"w"))==NULL) {
8167: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8168: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8169: }
8170: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8171: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
8172:
8173:
8174: strcpy(fileresstde,"STDE_");
8175: strcat(fileresstde,fileresu);
8176: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8177: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8178: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8179: }
8180: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8181: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8182:
8183: strcpy(filerescve,"CVE_");
8184: strcat(filerescve,fileresu);
8185: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8186: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8187: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8188: }
8189: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8190: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8191:
8192: strcpy(fileresv,"V_");
8193: strcat(fileresv,fileresu);
8194: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8195: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8196: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8197: }
8198: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8199: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
8200:
8201: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8202: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8203:
8204: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8205: fprintf(ficrest,"\n#****** ");
8206: for(j=1;j<=cptcoveff;j++)
8207: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8208: fprintf(ficrest,"******\n");
8209:
8210: fprintf(ficresstdeij,"\n#****** ");
8211: fprintf(ficrescveij,"\n#****** ");
8212: for(j=1;j<=cptcoveff;j++) {
8213: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8214: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8215: }
8216: fprintf(ficresstdeij,"******\n");
8217: fprintf(ficrescveij,"******\n");
8218:
8219: fprintf(ficresvij,"\n#****** ");
8220: for(j=1;j<=cptcoveff;j++)
8221: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8222: fprintf(ficresvij,"******\n");
8223:
8224: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8225: oldm=oldms;savm=savms;
8226: printf(" cvevsij %d, ",k);
8227: fprintf(ficlog, " cvevsij %d, ",k);
8228: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8229: printf(" end cvevsij \n ");
8230: fprintf(ficlog, " end cvevsij \n ");
8231:
8232: /*
8233: */
8234: /* goto endfree; */
8235:
8236: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8237: pstamp(ficrest);
8238:
8239:
8240: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8241: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8242: cptcod= 0; /* To be deleted */
8243: printf("varevsij %d \n",vpopbased);
8244: fprintf(ficlog, "varevsij %d \n",vpopbased);
8245: 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 */
8246: 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 ");
8247: if(vpopbased==1)
8248: 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);
8249: else
8250: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8251: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8252: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8253: fprintf(ficrest,"\n");
8254: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8255: epj=vector(1,nlstate+1);
8256: printf("Computing age specific period (stable) prevalences in each health state \n");
8257: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8258: for(age=bage; age <=fage ;age++){
8259: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
8260: if (vpopbased==1) {
8261: if(mobilav ==0){
8262: for(i=1; i<=nlstate;i++)
8263: prlim[i][i]=probs[(int)age][i][k];
8264: }else{ /* mobilav */
8265: for(i=1; i<=nlstate;i++)
8266: prlim[i][i]=mobaverage[(int)age][i][k];
8267: }
8268: }
8269:
8270: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8271: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8272: /* printf(" age %4.0f ",age); */
8273: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8274: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8275: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8276: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8277: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8278: }
8279: epj[nlstate+1] +=epj[j];
8280: }
8281: /* printf(" age %4.0f \n",age); */
8282:
8283: for(i=1, vepp=0.;i <=nlstate;i++)
8284: for(j=1;j <=nlstate;j++)
8285: vepp += vareij[i][j][(int)age];
8286: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8287: for(j=1;j <=nlstate;j++){
8288: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8289: }
8290: fprintf(ficrest,"\n");
8291: }
8292: } /* End vpopbased */
8293: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8294: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8295: free_vector(epj,1,nlstate+1);
8296: printf("done \n");fflush(stdout);
8297: fprintf(ficlog,"done\n");fflush(ficlog);
8298:
8299: /*}*/
8300: } /* End k */
8301: free_vector(weight,1,n);
8302: free_imatrix(Tvard,1,NCOVMAX,1,2);
8303: free_imatrix(s,1,maxwav+1,1,n);
8304: free_matrix(anint,1,maxwav,1,n);
8305: free_matrix(mint,1,maxwav,1,n);
8306: free_ivector(cod,1,n);
8307: free_ivector(tab,1,NCOVMAX);
8308: fclose(ficresstdeij);
8309: fclose(ficrescveij);
8310: fclose(ficresvij);
8311: fclose(ficrest);
8312: printf("done Health expectancies\n");fflush(stdout);
8313: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
8314: fclose(ficpar);
8315:
8316: /*------- Variance of period (stable) prevalence------*/
8317:
8318: strcpy(fileresvpl,"VPL_");
8319: strcat(fileresvpl,fileresu);
8320: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8321: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8322: exit(0);
8323: }
8324: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8325: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
8326:
8327: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8328: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8329:
8330: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8331: fprintf(ficresvpl,"\n#****** ");
8332: for(j=1;j<=cptcoveff;j++)
8333: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8334: fprintf(ficresvpl,"******\n");
8335:
8336: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8337: oldm=oldms;savm=savms;
8338: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
8339: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8340: /*}*/
8341: }
8342:
8343: fclose(ficresvpl);
8344: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8345: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
8346:
8347: /*---------- End : free ----------------*/
8348: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8349: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8350: } /* mle==-3 arrives here for freeing */
8351: /* endfree:*/
8352: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8353: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8354: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8355: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8356: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8357: free_matrix(covar,0,NCOVMAX,1,n);
8358: free_matrix(matcov,1,npar,1,npar);
8359: free_matrix(hess,1,npar,1,npar);
8360: /*free_vector(delti,1,npar);*/
8361: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8362: free_matrix(agev,1,maxwav,1,imx);
8363: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8364:
8365: free_ivector(ncodemax,1,NCOVMAX);
8366: free_ivector(ncodemaxwundef,1,NCOVMAX);
8367: free_ivector(Tvar,1,NCOVMAX);
8368: free_ivector(Tprod,1,NCOVMAX);
8369: free_ivector(Tvaraff,1,NCOVMAX);
8370: free_ivector(Tage,1,NCOVMAX);
8371:
8372: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8373: /* free_imatrix(codtab,1,100,1,10); */
8374: fflush(fichtm);
8375: fflush(ficgp);
8376:
8377:
8378: if((nberr >0) || (nbwarn>0)){
8379: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8380: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8381: }else{
8382: printf("End of Imach\n");
8383: fprintf(ficlog,"End of Imach\n");
8384: }
8385: printf("See log file on %s\n",filelog);
8386: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8387: /*(void) gettimeofday(&end_time,&tzp);*/
8388: rend_time = time(NULL);
8389: end_time = *localtime(&rend_time);
8390: /* tml = *localtime(&end_time.tm_sec); */
8391: strcpy(strtend,asctime(&end_time));
8392: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8393: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8394: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8395:
8396: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8397: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8398: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8399: /* printf("Total time was %d uSec.\n", total_usecs);*/
8400: /* if(fileappend(fichtm,optionfilehtm)){ */
8401: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8402: fclose(fichtm);
8403: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8404: fclose(fichtmcov);
8405: fclose(ficgp);
8406: fclose(ficlog);
8407: /*------ End -----------*/
8408:
8409:
8410: printf("Before Current directory %s!\n",pathcd);
8411: #ifdef WIN32
8412: if (_chdir(pathcd) != 0)
8413: printf("Can't move to directory %s!\n",path);
8414: if(_getcwd(pathcd,MAXLINE) > 0)
8415: #else
8416: if(chdir(pathcd) != 0)
8417: printf("Can't move to directory %s!\n", path);
8418: if (getcwd(pathcd, MAXLINE) > 0)
8419: #endif
8420: printf("Current directory %s!\n",pathcd);
8421: /*strcat(plotcmd,CHARSEPARATOR);*/
8422: sprintf(plotcmd,"gnuplot");
8423: #ifdef _WIN32
8424: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8425: #endif
8426: if(!stat(plotcmd,&info)){
8427: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8428: if(!stat(getenv("GNUPLOTBIN"),&info)){
8429: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8430: }else
8431: strcpy(pplotcmd,plotcmd);
8432: #ifdef __unix
8433: strcpy(plotcmd,GNUPLOTPROGRAM);
8434: if(!stat(plotcmd,&info)){
8435: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8436: }else
8437: strcpy(pplotcmd,plotcmd);
8438: #endif
8439: }else
8440: strcpy(pplotcmd,plotcmd);
8441:
8442: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8443: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8444:
8445: if((outcmd=system(plotcmd)) != 0){
8446: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8447: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8448: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8449: if((outcmd=system(plotcmd)) != 0)
8450: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8451: }
8452: printf(" Successful, please wait...");
8453: while (z[0] != 'q') {
8454: /* chdir(path); */
8455: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8456: scanf("%s",z);
8457: /* if (z[0] == 'c') system("./imach"); */
8458: if (z[0] == 'e') {
8459: #ifdef __APPLE__
8460: sprintf(pplotcmd, "open %s", optionfilehtm);
8461: #elif __linux
8462: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8463: #else
8464: sprintf(pplotcmd, "%s", optionfilehtm);
8465: #endif
8466: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8467: system(pplotcmd);
8468: }
8469: else if (z[0] == 'g') system(plotcmd);
8470: else if (z[0] == 'q') exit(0);
8471: }
8472: end:
8473: while (z[0] != 'q') {
8474: printf("\nType q for exiting: "); fflush(stdout);
8475: scanf("%s",z);
8476: }
8477: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>