1: /* $Id: imach.c,v 1.215 2015/12/16 08:52:24 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.215 2015/12/16 08:52:24 brouard
5: Summary: 0.98r4 working
6:
7: Revision 1.214 2015/12/16 06:57:54 brouard
8: Summary: temporary not working
9:
10: Revision 1.213 2015/12/11 18:22:17 brouard
11: Summary: 0.98r4
12:
13: Revision 1.212 2015/11/21 12:47:24 brouard
14: Summary: minor typo
15:
16: Revision 1.211 2015/11/21 12:41:11 brouard
17: Summary: 0.98r3 with some graph of projected cross-sectional
18:
19: Author: Nicolas Brouard
20:
21: Revision 1.210 2015/11/18 17:41:20 brouard
22: Summary: Start working on projected prevalences
23:
24: Revision 1.209 2015/11/17 22:12:03 brouard
25: Summary: Adding ftolpl parameter
26: Author: N Brouard
27:
28: We had difficulties to get smoothed confidence intervals. It was due
29: to the period prevalence which wasn't computed accurately. The inner
30: parameter ftolpl is now an outer parameter of the .imach parameter
31: file after estepm. If ftolpl is small 1.e-4 and estepm too,
32: computation are long.
33:
34: Revision 1.208 2015/11/17 14:31:57 brouard
35: Summary: temporary
36:
37: Revision 1.207 2015/10/27 17:36:57 brouard
38: *** empty log message ***
39:
40: Revision 1.206 2015/10/24 07:14:11 brouard
41: *** empty log message ***
42:
43: Revision 1.205 2015/10/23 15:50:53 brouard
44: Summary: 0.98r3 some clarification for graphs on likelihood contributions
45:
46: Revision 1.204 2015/10/01 16:20:26 brouard
47: Summary: Some new graphs of contribution to likelihood
48:
49: Revision 1.203 2015/09/30 17:45:14 brouard
50: Summary: looking at better estimation of the hessian
51:
52: Also a better criteria for convergence to the period prevalence And
53: therefore adding the number of years needed to converge. (The
54: prevalence in any alive state shold sum to one
55:
56: Revision 1.202 2015/09/22 19:45:16 brouard
57: Summary: Adding some overall graph on contribution to likelihood. Might change
58:
59: Revision 1.201 2015/09/15 17:34:58 brouard
60: Summary: 0.98r0
61:
62: - Some new graphs like suvival functions
63: - Some bugs fixed like model=1+age+V2.
64:
65: Revision 1.200 2015/09/09 16:53:55 brouard
66: Summary: Big bug thanks to Flavia
67:
68: Even model=1+age+V2. did not work anymore
69:
70: Revision 1.199 2015/09/07 14:09:23 brouard
71: Summary: 0.98q6 changing default small png format for graph to vectorized svg.
72:
73: Revision 1.198 2015/09/03 07:14:39 brouard
74: Summary: 0.98q5 Flavia
75:
76: Revision 1.197 2015/09/01 18:24:39 brouard
77: *** empty log message ***
78:
79: Revision 1.196 2015/08/18 23:17:52 brouard
80: Summary: 0.98q5
81:
82: Revision 1.195 2015/08/18 16:28:39 brouard
83: Summary: Adding a hack for testing purpose
84:
85: After reading the title, ftol and model lines, if the comment line has
86: a q, starting with #q, the answer at the end of the run is quit. It
87: permits to run test files in batch with ctest. The former workaround was
88: $ echo q | imach foo.imach
89:
90: Revision 1.194 2015/08/18 13:32:00 brouard
91: Summary: Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
92:
93: Revision 1.193 2015/08/04 07:17:42 brouard
94: Summary: 0.98q4
95:
96: Revision 1.192 2015/07/16 16:49:02 brouard
97: Summary: Fixing some outputs
98:
99: Revision 1.191 2015/07/14 10:00:33 brouard
100: Summary: Some fixes
101:
102: Revision 1.190 2015/05/05 08:51:13 brouard
103: Summary: Adding digits in output parameters (7 digits instead of 6)
104:
105: Fix 1+age+.
106:
107: Revision 1.189 2015/04/30 14:45:16 brouard
108: Summary: 0.98q2
109:
110: Revision 1.188 2015/04/30 08:27:53 brouard
111: *** empty log message ***
112:
113: Revision 1.187 2015/04/29 09:11:15 brouard
114: *** empty log message ***
115:
116: Revision 1.186 2015/04/23 12:01:52 brouard
117: Summary: V1*age is working now, version 0.98q1
118:
119: Some codes had been disabled in order to simplify and Vn*age was
120: working in the optimization phase, ie, giving correct MLE parameters,
121: but, as usual, outputs were not correct and program core dumped.
122:
123: Revision 1.185 2015/03/11 13:26:42 brouard
124: Summary: Inclusion of compile and links command line for Intel Compiler
125:
126: Revision 1.184 2015/03/11 11:52:39 brouard
127: Summary: Back from Windows 8. Intel Compiler
128:
129: Revision 1.183 2015/03/10 20:34:32 brouard
130: Summary: 0.98q0, trying with directest, mnbrak fixed
131:
132: We use directest instead of original Powell test; probably no
133: incidence on the results, but better justifications;
134: We fixed Numerical Recipes mnbrak routine which was wrong and gave
135: wrong results.
136:
137: Revision 1.182 2015/02/12 08:19:57 brouard
138: Summary: Trying to keep directest which seems simpler and more general
139: Author: Nicolas Brouard
140:
141: Revision 1.181 2015/02/11 23:22:24 brouard
142: Summary: Comments on Powell added
143:
144: Author:
145:
146: Revision 1.180 2015/02/11 17:33:45 brouard
147: Summary: Finishing move from main to function (hpijx and prevalence_limit)
148:
149: Revision 1.179 2015/01/04 09:57:06 brouard
150: Summary: back to OS/X
151:
152: Revision 1.178 2015/01/04 09:35:48 brouard
153: *** empty log message ***
154:
155: Revision 1.177 2015/01/03 18:40:56 brouard
156: Summary: Still testing ilc32 on OSX
157:
158: Revision 1.176 2015/01/03 16:45:04 brouard
159: *** empty log message ***
160:
161: Revision 1.175 2015/01/03 16:33:42 brouard
162: *** empty log message ***
163:
164: Revision 1.174 2015/01/03 16:15:49 brouard
165: Summary: Still in cross-compilation
166:
167: Revision 1.173 2015/01/03 12:06:26 brouard
168: Summary: trying to detect cross-compilation
169:
170: Revision 1.172 2014/12/27 12:07:47 brouard
171: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
172:
173: Revision 1.171 2014/12/23 13:26:59 brouard
174: Summary: Back from Visual C
175:
176: Still problem with utsname.h on Windows
177:
178: Revision 1.170 2014/12/23 11:17:12 brouard
179: Summary: Cleaning some \%% back to %%
180:
181: The escape was mandatory for a specific compiler (which one?), but too many warnings.
182:
183: Revision 1.169 2014/12/22 23:08:31 brouard
184: Summary: 0.98p
185:
186: Outputs some informations on compiler used, OS etc. Testing on different platforms.
187:
188: Revision 1.168 2014/12/22 15:17:42 brouard
189: Summary: update
190:
191: Revision 1.167 2014/12/22 13:50:56 brouard
192: Summary: Testing uname and compiler version and if compiled 32 or 64
193:
194: Testing on Linux 64
195:
196: Revision 1.166 2014/12/22 11:40:47 brouard
197: *** empty log message ***
198:
199: Revision 1.165 2014/12/16 11:20:36 brouard
200: Summary: After compiling on Visual C
201:
202: * imach.c (Module): Merging 1.61 to 1.162
203:
204: Revision 1.164 2014/12/16 10:52:11 brouard
205: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
206:
207: * imach.c (Module): Merging 1.61 to 1.162
208:
209: Revision 1.163 2014/12/16 10:30:11 brouard
210: * imach.c (Module): Merging 1.61 to 1.162
211:
212: Revision 1.162 2014/09/25 11:43:39 brouard
213: Summary: temporary backup 0.99!
214:
215: Revision 1.1 2014/09/16 11:06:58 brouard
216: Summary: With some code (wrong) for nlopt
217:
218: Author:
219:
220: Revision 1.161 2014/09/15 20:41:41 brouard
221: Summary: Problem with macro SQR on Intel compiler
222:
223: Revision 1.160 2014/09/02 09:24:05 brouard
224: *** empty log message ***
225:
226: Revision 1.159 2014/09/01 10:34:10 brouard
227: Summary: WIN32
228: Author: Brouard
229:
230: Revision 1.158 2014/08/27 17:11:51 brouard
231: *** empty log message ***
232:
233: Revision 1.157 2014/08/27 16:26:55 brouard
234: Summary: Preparing windows Visual studio version
235: Author: Brouard
236:
237: In order to compile on Visual studio, time.h is now correct and time_t
238: and tm struct should be used. difftime should be used but sometimes I
239: just make the differences in raw time format (time(&now).
240: Trying to suppress #ifdef LINUX
241: Add xdg-open for __linux in order to open default browser.
242:
243: Revision 1.156 2014/08/25 20:10:10 brouard
244: *** empty log message ***
245:
246: Revision 1.155 2014/08/25 18:32:34 brouard
247: Summary: New compile, minor changes
248: Author: Brouard
249:
250: Revision 1.154 2014/06/20 17:32:08 brouard
251: Summary: Outputs now all graphs of convergence to period prevalence
252:
253: Revision 1.153 2014/06/20 16:45:46 brouard
254: Summary: If 3 live state, convergence to period prevalence on same graph
255: Author: Brouard
256:
257: Revision 1.152 2014/06/18 17:54:09 brouard
258: Summary: open browser, use gnuplot on same dir than imach if not found in the path
259:
260: Revision 1.151 2014/06/18 16:43:30 brouard
261: *** empty log message ***
262:
263: Revision 1.150 2014/06/18 16:42:35 brouard
264: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
265: Author: brouard
266:
267: Revision 1.149 2014/06/18 15:51:14 brouard
268: Summary: Some fixes in parameter files errors
269: Author: Nicolas Brouard
270:
271: Revision 1.148 2014/06/17 17:38:48 brouard
272: Summary: Nothing new
273: Author: Brouard
274:
275: Just a new packaging for OS/X version 0.98nS
276:
277: Revision 1.147 2014/06/16 10:33:11 brouard
278: *** empty log message ***
279:
280: Revision 1.146 2014/06/16 10:20:28 brouard
281: Summary: Merge
282: Author: Brouard
283:
284: Merge, before building revised version.
285:
286: Revision 1.145 2014/06/10 21:23:15 brouard
287: Summary: Debugging with valgrind
288: Author: Nicolas Brouard
289:
290: Lot of changes in order to output the results with some covariates
291: After the Edimburgh REVES conference 2014, it seems mandatory to
292: improve the code.
293: No more memory valgrind error but a lot has to be done in order to
294: continue the work of splitting the code into subroutines.
295: Also, decodemodel has been improved. Tricode is still not
296: optimal. nbcode should be improved. Documentation has been added in
297: the source code.
298:
299: Revision 1.143 2014/01/26 09:45:38 brouard
300: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
301:
302: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
303: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
304:
305: Revision 1.142 2014/01/26 03:57:36 brouard
306: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
307:
308: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
309:
310: Revision 1.141 2014/01/26 02:42:01 brouard
311: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
312:
313: Revision 1.140 2011/09/02 10:37:54 brouard
314: Summary: times.h is ok with mingw32 now.
315:
316: Revision 1.139 2010/06/14 07:50:17 brouard
317: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
318: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
319:
320: Revision 1.138 2010/04/30 18:19:40 brouard
321: *** empty log message ***
322:
323: Revision 1.137 2010/04/29 18:11:38 brouard
324: (Module): Checking covariates for more complex models
325: than V1+V2. A lot of change to be done. Unstable.
326:
327: Revision 1.136 2010/04/26 20:30:53 brouard
328: (Module): merging some libgsl code. Fixing computation
329: of likelione (using inter/intrapolation if mle = 0) in order to
330: get same likelihood as if mle=1.
331: Some cleaning of code and comments added.
332:
333: Revision 1.135 2009/10/29 15:33:14 brouard
334: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
335:
336: Revision 1.134 2009/10/29 13:18:53 brouard
337: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
338:
339: Revision 1.133 2009/07/06 10:21:25 brouard
340: just nforces
341:
342: Revision 1.132 2009/07/06 08:22:05 brouard
343: Many tings
344:
345: Revision 1.131 2009/06/20 16:22:47 brouard
346: Some dimensions resccaled
347:
348: Revision 1.130 2009/05/26 06:44:34 brouard
349: (Module): Max Covariate is now set to 20 instead of 8. A
350: lot of cleaning with variables initialized to 0. Trying to make
351: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
352:
353: Revision 1.129 2007/08/31 13:49:27 lievre
354: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
355:
356: Revision 1.128 2006/06/30 13:02:05 brouard
357: (Module): Clarifications on computing e.j
358:
359: Revision 1.127 2006/04/28 18:11:50 brouard
360: (Module): Yes the sum of survivors was wrong since
361: imach-114 because nhstepm was no more computed in the age
362: loop. Now we define nhstepma in the age loop.
363: (Module): In order to speed up (in case of numerous covariates) we
364: compute health expectancies (without variances) in a first step
365: and then all the health expectancies with variances or standard
366: deviation (needs data from the Hessian matrices) which slows the
367: computation.
368: In the future we should be able to stop the program is only health
369: expectancies and graph are needed without standard deviations.
370:
371: Revision 1.126 2006/04/28 17:23:28 brouard
372: (Module): Yes the sum of survivors was wrong since
373: imach-114 because nhstepm was no more computed in the age
374: loop. Now we define nhstepma in the age loop.
375: Version 0.98h
376:
377: Revision 1.125 2006/04/04 15:20:31 lievre
378: Errors in calculation of health expectancies. Age was not initialized.
379: Forecasting file added.
380:
381: Revision 1.124 2006/03/22 17:13:53 lievre
382: Parameters are printed with %lf instead of %f (more numbers after the comma).
383: The log-likelihood is printed in the log file
384:
385: Revision 1.123 2006/03/20 10:52:43 brouard
386: * imach.c (Module): <title> changed, corresponds to .htm file
387: name. <head> headers where missing.
388:
389: * imach.c (Module): Weights can have a decimal point as for
390: English (a comma might work with a correct LC_NUMERIC environment,
391: otherwise the weight is truncated).
392: Modification of warning when the covariates values are not 0 or
393: 1.
394: Version 0.98g
395:
396: Revision 1.122 2006/03/20 09:45:41 brouard
397: (Module): Weights can have a decimal point as for
398: English (a comma might work with a correct LC_NUMERIC environment,
399: otherwise the weight is truncated).
400: Modification of warning when the covariates values are not 0 or
401: 1.
402: Version 0.98g
403:
404: Revision 1.121 2006/03/16 17:45:01 lievre
405: * imach.c (Module): Comments concerning covariates added
406:
407: * imach.c (Module): refinements in the computation of lli if
408: status=-2 in order to have more reliable computation if stepm is
409: not 1 month. Version 0.98f
410:
411: Revision 1.120 2006/03/16 15:10:38 lievre
412: (Module): refinements in the computation of lli if
413: status=-2 in order to have more reliable computation if stepm is
414: not 1 month. Version 0.98f
415:
416: Revision 1.119 2006/03/15 17:42:26 brouard
417: (Module): Bug if status = -2, the loglikelihood was
418: computed as likelihood omitting the logarithm. Version O.98e
419:
420: Revision 1.118 2006/03/14 18:20:07 brouard
421: (Module): varevsij Comments added explaining the second
422: table of variances if popbased=1 .
423: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
424: (Module): Function pstamp added
425: (Module): Version 0.98d
426:
427: Revision 1.117 2006/03/14 17:16:22 brouard
428: (Module): varevsij Comments added explaining the second
429: table of variances if popbased=1 .
430: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
431: (Module): Function pstamp added
432: (Module): Version 0.98d
433:
434: Revision 1.116 2006/03/06 10:29:27 brouard
435: (Module): Variance-covariance wrong links and
436: varian-covariance of ej. is needed (Saito).
437:
438: Revision 1.115 2006/02/27 12:17:45 brouard
439: (Module): One freematrix added in mlikeli! 0.98c
440:
441: Revision 1.114 2006/02/26 12:57:58 brouard
442: (Module): Some improvements in processing parameter
443: filename with strsep.
444:
445: Revision 1.113 2006/02/24 14:20:24 brouard
446: (Module): Memory leaks checks with valgrind and:
447: datafile was not closed, some imatrix were not freed and on matrix
448: allocation too.
449:
450: Revision 1.112 2006/01/30 09:55:26 brouard
451: (Module): Back to gnuplot.exe instead of wgnuplot.exe
452:
453: Revision 1.111 2006/01/25 20:38:18 brouard
454: (Module): Lots of cleaning and bugs added (Gompertz)
455: (Module): Comments can be added in data file. Missing date values
456: can be a simple dot '.'.
457:
458: Revision 1.110 2006/01/25 00:51:50 brouard
459: (Module): Lots of cleaning and bugs added (Gompertz)
460:
461: Revision 1.109 2006/01/24 19:37:15 brouard
462: (Module): Comments (lines starting with a #) are allowed in data.
463:
464: Revision 1.108 2006/01/19 18:05:42 lievre
465: Gnuplot problem appeared...
466: To be fixed
467:
468: Revision 1.107 2006/01/19 16:20:37 brouard
469: Test existence of gnuplot in imach path
470:
471: Revision 1.106 2006/01/19 13:24:36 brouard
472: Some cleaning and links added in html output
473:
474: Revision 1.105 2006/01/05 20:23:19 lievre
475: *** empty log message ***
476:
477: Revision 1.104 2005/09/30 16:11:43 lievre
478: (Module): sump fixed, loop imx fixed, and simplifications.
479: (Module): If the status is missing at the last wave but we know
480: that the person is alive, then we can code his/her status as -2
481: (instead of missing=-1 in earlier versions) and his/her
482: contributions to the likelihood is 1 - Prob of dying from last
483: health status (= 1-p13= p11+p12 in the easiest case of somebody in
484: the healthy state at last known wave). Version is 0.98
485:
486: Revision 1.103 2005/09/30 15:54:49 lievre
487: (Module): sump fixed, loop imx fixed, and simplifications.
488:
489: Revision 1.102 2004/09/15 17:31:30 brouard
490: Add the possibility to read data file including tab characters.
491:
492: Revision 1.101 2004/09/15 10:38:38 brouard
493: Fix on curr_time
494:
495: Revision 1.100 2004/07/12 18:29:06 brouard
496: Add version for Mac OS X. Just define UNIX in Makefile
497:
498: Revision 1.99 2004/06/05 08:57:40 brouard
499: *** empty log message ***
500:
501: Revision 1.98 2004/05/16 15:05:56 brouard
502: New version 0.97 . First attempt to estimate force of mortality
503: directly from the data i.e. without the need of knowing the health
504: state at each age, but using a Gompertz model: log u =a + b*age .
505: This is the basic analysis of mortality and should be done before any
506: other analysis, in order to test if the mortality estimated from the
507: cross-longitudinal survey is different from the mortality estimated
508: from other sources like vital statistic data.
509:
510: The same imach parameter file can be used but the option for mle should be -3.
511:
512: Agnès, who wrote this part of the code, tried to keep most of the
513: former routines in order to include the new code within the former code.
514:
515: The output is very simple: only an estimate of the intercept and of
516: the slope with 95% confident intervals.
517:
518: Current limitations:
519: A) Even if you enter covariates, i.e. with the
520: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
521: B) There is no computation of Life Expectancy nor Life Table.
522:
523: Revision 1.97 2004/02/20 13:25:42 lievre
524: Version 0.96d. Population forecasting command line is (temporarily)
525: suppressed.
526:
527: Revision 1.96 2003/07/15 15:38:55 brouard
528: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
529: rewritten within the same printf. Workaround: many printfs.
530:
531: Revision 1.95 2003/07/08 07:54:34 brouard
532: * imach.c (Repository):
533: (Repository): Using imachwizard code to output a more meaningful covariance
534: matrix (cov(a12,c31) instead of numbers.
535:
536: Revision 1.94 2003/06/27 13:00:02 brouard
537: Just cleaning
538:
539: Revision 1.93 2003/06/25 16:33:55 brouard
540: (Module): On windows (cygwin) function asctime_r doesn't
541: exist so I changed back to asctime which exists.
542: (Module): Version 0.96b
543:
544: Revision 1.92 2003/06/25 16:30:45 brouard
545: (Module): On windows (cygwin) function asctime_r doesn't
546: exist so I changed back to asctime which exists.
547:
548: Revision 1.91 2003/06/25 15:30:29 brouard
549: * imach.c (Repository): Duplicated warning errors corrected.
550: (Repository): Elapsed time after each iteration is now output. It
551: helps to forecast when convergence will be reached. Elapsed time
552: is stamped in powell. We created a new html file for the graphs
553: concerning matrix of covariance. It has extension -cov.htm.
554:
555: Revision 1.90 2003/06/24 12:34:15 brouard
556: (Module): Some bugs corrected for windows. Also, when
557: mle=-1 a template is output in file "or"mypar.txt with the design
558: of the covariance matrix to be input.
559:
560: Revision 1.89 2003/06/24 12:30:52 brouard
561: (Module): Some bugs corrected for windows. Also, when
562: mle=-1 a template is output in file "or"mypar.txt with the design
563: of the covariance matrix to be input.
564:
565: Revision 1.88 2003/06/23 17:54:56 brouard
566: * 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.
567:
568: Revision 1.87 2003/06/18 12:26:01 brouard
569: Version 0.96
570:
571: Revision 1.86 2003/06/17 20:04:08 brouard
572: (Module): Change position of html and gnuplot routines and added
573: routine fileappend.
574:
575: Revision 1.85 2003/06/17 13:12:43 brouard
576: * imach.c (Repository): Check when date of death was earlier that
577: current date of interview. It may happen when the death was just
578: prior to the death. In this case, dh was negative and likelihood
579: was wrong (infinity). We still send an "Error" but patch by
580: assuming that the date of death was just one stepm after the
581: interview.
582: (Repository): Because some people have very long ID (first column)
583: we changed int to long in num[] and we added a new lvector for
584: memory allocation. But we also truncated to 8 characters (left
585: truncation)
586: (Repository): No more line truncation errors.
587:
588: Revision 1.84 2003/06/13 21:44:43 brouard
589: * imach.c (Repository): Replace "freqsummary" at a correct
590: place. It differs from routine "prevalence" which may be called
591: many times. Probs is memory consuming and must be used with
592: parcimony.
593: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
594:
595: Revision 1.83 2003/06/10 13:39:11 lievre
596: *** empty log message ***
597:
598: Revision 1.82 2003/06/05 15:57:20 brouard
599: Add log in imach.c and fullversion number is now printed.
600:
601: */
602: /*
603: Interpolated Markov Chain
604:
605: Short summary of the programme:
606:
607: This program computes Healthy Life Expectancies from
608: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
609: first survey ("cross") where individuals from different ages are
610: interviewed on their health status or degree of disability (in the
611: case of a health survey which is our main interest) -2- at least a
612: second wave of interviews ("longitudinal") which measure each change
613: (if any) in individual health status. Health expectancies are
614: computed from the time spent in each health state according to a
615: model. More health states you consider, more time is necessary to reach the
616: Maximum Likelihood of the parameters involved in the model. The
617: simplest model is the multinomial logistic model where pij is the
618: probability to be observed in state j at the second wave
619: conditional to be observed in state i at the first wave. Therefore
620: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
621: 'age' is age and 'sex' is a covariate. If you want to have a more
622: complex model than "constant and age", you should modify the program
623: where the markup *Covariates have to be included here again* invites
624: you to do it. More covariates you add, slower the
625: convergence.
626:
627: The advantage of this computer programme, compared to a simple
628: multinomial logistic model, is clear when the delay between waves is not
629: identical for each individual. Also, if a individual missed an
630: intermediate interview, the information is lost, but taken into
631: account using an interpolation or extrapolation.
632:
633: hPijx is the probability to be observed in state i at age x+h
634: conditional to the observed state i at age x. The delay 'h' can be
635: split into an exact number (nh*stepm) of unobserved intermediate
636: states. This elementary transition (by month, quarter,
637: semester or year) is modelled as a multinomial logistic. The hPx
638: matrix is simply the matrix product of nh*stepm elementary matrices
639: and the contribution of each individual to the likelihood is simply
640: hPijx.
641:
642: Also this programme outputs the covariance matrix of the parameters but also
643: of the life expectancies. It also computes the period (stable) prevalence.
644:
645: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
646: Institut national d'études démographiques, Paris.
647: This software have been partly granted by Euro-REVES, a concerted action
648: from the European Union.
649: It is copyrighted identically to a GNU software product, ie programme and
650: software can be distributed freely for non commercial use. Latest version
651: can be accessed at http://euroreves.ined.fr/imach .
652:
653: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
654: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
655:
656: **********************************************************************/
657: /*
658: main
659: read parameterfile
660: read datafile
661: concatwav
662: freqsummary
663: if (mle >= 1)
664: mlikeli
665: print results files
666: if mle==1
667: computes hessian
668: read end of parameter file: agemin, agemax, bage, fage, estepm
669: begin-prev-date,...
670: open gnuplot file
671: open html file
672: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
673: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
674: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
675: freexexit2 possible for memory heap.
676:
677: h Pij x | pij_nom ficrestpij
678: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
679: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
680: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
681:
682: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
683: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
684: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
685: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
686: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
687:
688: forecasting if prevfcast==1 prevforecast call prevalence()
689: health expectancies
690: Variance-covariance of DFLE
691: prevalence()
692: movingaverage()
693: varevsij()
694: if popbased==1 varevsij(,popbased)
695: total life expectancies
696: Variance of period (stable) prevalence
697: end
698: */
699:
700: /* #define DEBUG */
701: /* #define DEBUGBRENT */
702: /* #define DEBUGLINMIN */
703: /* #define DEBUGHESS */
704: #define DEBUGHESSIJ
705: /* #define LINMINORIGINAL /\* Don't use loop on scale in linmin (accepting nan)*\/ */
706: #define POWELL /* Instead of NLOPT */
707: #define POWELLF1F3 /* Skip test */
708: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
709: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
710:
711: #include <math.h>
712: #include <stdio.h>
713: #include <stdlib.h>
714: #include <string.h>
715:
716: #ifdef _WIN32
717: #include <io.h>
718: #include <windows.h>
719: #include <tchar.h>
720: #else
721: #include <unistd.h>
722: #endif
723:
724: #include <limits.h>
725: #include <sys/types.h>
726:
727: #if defined(__GNUC__)
728: #include <sys/utsname.h> /* Doesn't work on Windows */
729: #endif
730:
731: #include <sys/stat.h>
732: #include <errno.h>
733: /* extern int errno; */
734:
735: /* #ifdef LINUX */
736: /* #include <time.h> */
737: /* #include "timeval.h" */
738: /* #else */
739: /* #include <sys/time.h> */
740: /* #endif */
741:
742: #include <time.h>
743:
744: #ifdef GSL
745: #include <gsl/gsl_errno.h>
746: #include <gsl/gsl_multimin.h>
747: #endif
748:
749:
750: #ifdef NLOPT
751: #include <nlopt.h>
752: typedef struct {
753: double (* function)(double [] );
754: } myfunc_data ;
755: #endif
756:
757: /* #include <libintl.h> */
758: /* #define _(String) gettext (String) */
759:
760: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
761:
762: #define GNUPLOTPROGRAM "gnuplot"
763: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
764: #define FILENAMELENGTH 132
765:
766: #define GLOCK_ERROR_NOPATH -1 /* empty path */
767: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
768:
769: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
770: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
771:
772: #define NINTERVMAX 8
773: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
774: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
775: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
776: #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
777: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
778: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1
779: #define MAXN 20000
780: #define YEARM 12. /**< Number of months per year */
781: #define AGESUP 130
782: #define AGEBASE 40
783: #define AGEOVERFLOW 1.e20
784: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
785: #ifdef _WIN32
786: #define DIRSEPARATOR '\\'
787: #define CHARSEPARATOR "\\"
788: #define ODIRSEPARATOR '/'
789: #else
790: #define DIRSEPARATOR '/'
791: #define CHARSEPARATOR "/"
792: #define ODIRSEPARATOR '\\'
793: #endif
794:
795: /* $Id: imach.c,v 1.215 2015/12/16 08:52:24 brouard Exp $ */
796: /* $State: Exp $ */
797: #include "version.h"
798: char version[]=__IMACH_VERSION__;
799: 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";
800: char fullversion[]="$Revision: 1.215 $ $Date: 2015/12/16 08:52:24 $";
801: char strstart[80];
802: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
803: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
804: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
805: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
806: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
807: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
808: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
809: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
810: int cptcovprodnoage=0; /**< Number of covariate products without age */
811: int cptcoveff=0; /* Total number of covariates to vary for printing results */
812: int cptcov=0; /* Working variable */
813: int npar=NPARMAX;
814: int nlstate=2; /* Number of live states */
815: int ndeath=1; /* Number of dead states */
816: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
817: int popbased=0;
818:
819: int *wav; /* Number of waves for this individuual 0 is possible */
820: int maxwav=0; /* Maxim number of waves */
821: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
822: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
823: int gipmx=0, gsw=0; /* Global variables on the number of contributions
824: to the likelihood and the sum of weights (done by funcone)*/
825: int mle=1, weightopt=0;
826: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
827: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
828: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
829: * wave mi and wave mi+1 is not an exact multiple of stepm. */
830: int countcallfunc=0; /* Count the number of calls to func */
831: double jmean=1; /* Mean space between 2 waves */
832: double **matprod2(); /* test */
833: double **oldm, **newm, **savm; /* Working pointers to matrices */
834: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
835: /*FILE *fic ; */ /* Used in readdata only */
836: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
837: FILE *ficlog, *ficrespow;
838: int globpr=0; /* Global variable for printing or not */
839: double fretone; /* Only one call to likelihood */
840: long ipmx=0; /* Number of contributions */
841: double sw; /* Sum of weights */
842: char filerespow[FILENAMELENGTH];
843: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
844: FILE *ficresilk;
845: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
846: FILE *ficresprobmorprev;
847: FILE *fichtm, *fichtmcov; /* Html File */
848: FILE *ficreseij;
849: char filerese[FILENAMELENGTH];
850: FILE *ficresstdeij;
851: char fileresstde[FILENAMELENGTH];
852: FILE *ficrescveij;
853: char filerescve[FILENAMELENGTH];
854: FILE *ficresvij;
855: char fileresv[FILENAMELENGTH];
856: FILE *ficresvpl;
857: char fileresvpl[FILENAMELENGTH];
858: char title[MAXLINE];
859: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
860: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
861: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
862: char command[FILENAMELENGTH];
863: int outcmd=0;
864:
865: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
866: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
867: char filelog[FILENAMELENGTH]; /* Log file */
868: char filerest[FILENAMELENGTH];
869: char fileregp[FILENAMELENGTH];
870: char popfile[FILENAMELENGTH];
871:
872: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
873:
874: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
875: /* struct timezone tzp; */
876: /* extern int gettimeofday(); */
877: struct tm tml, *gmtime(), *localtime();
878:
879: extern time_t time();
880:
881: struct tm start_time, end_time, curr_time, last_time, forecast_time;
882: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
883: struct tm tm;
884:
885: char strcurr[80], strfor[80];
886:
887: char *endptr;
888: long lval;
889: double dval;
890:
891: #define NR_END 1
892: #define FREE_ARG char*
893: #define FTOL 1.0e-10
894:
895: #define NRANSI
896: #define ITMAX 200
897:
898: #define TOL 2.0e-4
899:
900: #define CGOLD 0.3819660
901: #define ZEPS 1.0e-10
902: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
903:
904: #define GOLD 1.618034
905: #define GLIMIT 100.0
906: #define TINY 1.0e-20
907:
908: static double maxarg1,maxarg2;
909: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
910: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
911:
912: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
913: #define rint(a) floor(a+0.5)
914: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
915: #define mytinydouble 1.0e-16
916: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
917: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
918: /* static double dsqrarg; */
919: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
920: static double sqrarg;
921: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
922: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
923: int agegomp= AGEGOMP;
924:
925: int imx;
926: int stepm=1;
927: /* Stepm, step in month: minimum step interpolation*/
928:
929: int estepm;
930: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
931:
932: int m,nb;
933: long *num;
934: int firstpass=0, lastpass=4,*cod, *cens;
935: int *ncodemax; /* ncodemax[j]= Number of modalities of the j th
936: covariate for which somebody answered excluding
937: undefined. Usually 2: 0 and 1. */
938: int *ncodemaxwundef; /* ncodemax[j]= Number of modalities of the j th
939: covariate for which somebody answered including
940: undefined. Usually 3: -1, 0 and 1. */
941: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
942: double **pmmij, ***probs;
943: double *ageexmed,*agecens;
944: double dateintmean=0;
945:
946: double *weight;
947: int **s; /* Status */
948: double *agedc;
949: double **covar; /**< covar[j,i], value of jth covariate for individual i,
950: * covar=matrix(0,NCOVMAX,1,n);
951: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
952: double idx;
953: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
954: int *Tage;
955: int *Ndum; /** Freq of modality (tricode */
956: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
957: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
958: double *lsurv, *lpop, *tpop;
959:
960: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
961: double ftolhess; /**< Tolerance for computing hessian */
962:
963: /**************** split *************************/
964: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
965: {
966: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
967: the name of the file (name), its extension only (ext) and its first part of the name (finame)
968: */
969: char *ss; /* pointer */
970: int l1=0, l2=0; /* length counters */
971:
972: l1 = strlen(path ); /* length of path */
973: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
974: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
975: if ( ss == NULL ) { /* no directory, so determine current directory */
976: strcpy( name, path ); /* we got the fullname name because no directory */
977: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
978: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
979: /* get current working directory */
980: /* extern char* getcwd ( char *buf , int len);*/
981: #ifdef WIN32
982: if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
983: #else
984: if (getcwd(dirc, FILENAME_MAX) == NULL) {
985: #endif
986: return( GLOCK_ERROR_GETCWD );
987: }
988: /* got dirc from getcwd*/
989: printf(" DIRC = %s \n",dirc);
990: } else { /* strip directory from path */
991: ss++; /* after this, the filename */
992: l2 = strlen( ss ); /* length of filename */
993: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
994: strcpy( name, ss ); /* save file name */
995: strncpy( dirc, path, l1 - l2 ); /* now the directory */
996: dirc[l1-l2] = '\0'; /* add zero */
997: printf(" DIRC2 = %s \n",dirc);
998: }
999: /* We add a separator at the end of dirc if not exists */
1000: l1 = strlen( dirc ); /* length of directory */
1001: if( dirc[l1-1] != DIRSEPARATOR ){
1002: dirc[l1] = DIRSEPARATOR;
1003: dirc[l1+1] = 0;
1004: printf(" DIRC3 = %s \n",dirc);
1005: }
1006: ss = strrchr( name, '.' ); /* find last / */
1007: if (ss >0){
1008: ss++;
1009: strcpy(ext,ss); /* save extension */
1010: l1= strlen( name);
1011: l2= strlen(ss)+1;
1012: strncpy( finame, name, l1-l2);
1013: finame[l1-l2]= 0;
1014: }
1015:
1016: return( 0 ); /* we're done */
1017: }
1018:
1019:
1020: /******************************************/
1021:
1022: void replace_back_to_slash(char *s, char*t)
1023: {
1024: int i;
1025: int lg=0;
1026: i=0;
1027: lg=strlen(t);
1028: for(i=0; i<= lg; i++) {
1029: (s[i] = t[i]);
1030: if (t[i]== '\\') s[i]='/';
1031: }
1032: }
1033:
1034: char *trimbb(char *out, char *in)
1035: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1036: char *s;
1037: s=out;
1038: while (*in != '\0'){
1039: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1040: in++;
1041: }
1042: *out++ = *in++;
1043: }
1044: *out='\0';
1045: return s;
1046: }
1047:
1048: /* char *substrchaine(char *out, char *in, char *chain) */
1049: /* { */
1050: /* /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
1051: /* char *s, *t; */
1052: /* t=in;s=out; */
1053: /* while ((*in != *chain) && (*in != '\0')){ */
1054: /* *out++ = *in++; */
1055: /* } */
1056:
1057: /* /\* *in matches *chain *\/ */
1058: /* while ((*in++ == *chain++) && (*in != '\0')){ */
1059: /* printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1060: /* } */
1061: /* in--; chain--; */
1062: /* while ( (*in != '\0')){ */
1063: /* printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1064: /* *out++ = *in++; */
1065: /* printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain); */
1066: /* } */
1067: /* *out='\0'; */
1068: /* out=s; */
1069: /* return out; */
1070: /* } */
1071: char *substrchaine(char *out, char *in, char *chain)
1072: {
1073: /* Substract chain 'chain' from 'in', return and output 'out' */
1074: /* in="V1+V1*age+age*age+V2", chain="age*age" */
1075:
1076: char *strloc;
1077:
1078: strcpy (out, in);
1079: strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
1080: printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
1081: if(strloc != NULL){
1082: /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
1083: memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
1084: /* strcpy (strloc, strloc +strlen(chain));*/
1085: }
1086: printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
1087: return out;
1088: }
1089:
1090:
1091: char *cutl(char *blocc, char *alocc, char *in, char occ)
1092: {
1093: /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ'
1094: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1095: gives blocc="abcdef" and alocc="ghi2j".
1096: If occ is not found blocc is null and alocc is equal to in. Returns blocc
1097: */
1098: char *s, *t;
1099: t=in;s=in;
1100: while ((*in != occ) && (*in != '\0')){
1101: *alocc++ = *in++;
1102: }
1103: if( *in == occ){
1104: *(alocc)='\0';
1105: s=++in;
1106: }
1107:
1108: if (s == t) {/* occ not found */
1109: *(alocc-(in-s))='\0';
1110: in=s;
1111: }
1112: while ( *in != '\0'){
1113: *blocc++ = *in++;
1114: }
1115:
1116: *blocc='\0';
1117: return t;
1118: }
1119: char *cutv(char *blocc, char *alocc, char *in, char occ)
1120: {
1121: /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ'
1122: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1123: gives blocc="abcdef2ghi" and alocc="j".
1124: If occ is not found blocc is null and alocc is equal to in. Returns alocc
1125: */
1126: char *s, *t;
1127: t=in;s=in;
1128: while (*in != '\0'){
1129: while( *in == occ){
1130: *blocc++ = *in++;
1131: s=in;
1132: }
1133: *blocc++ = *in++;
1134: }
1135: if (s == t) /* occ not found */
1136: *(blocc-(in-s))='\0';
1137: else
1138: *(blocc-(in-s)-1)='\0';
1139: in=s;
1140: while ( *in != '\0'){
1141: *alocc++ = *in++;
1142: }
1143:
1144: *alocc='\0';
1145: return s;
1146: }
1147:
1148: int nbocc(char *s, char occ)
1149: {
1150: int i,j=0;
1151: int lg=20;
1152: i=0;
1153: lg=strlen(s);
1154: for(i=0; i<= lg; i++) {
1155: if (s[i] == occ ) j++;
1156: }
1157: return j;
1158: }
1159:
1160: /* void cutv(char *u,char *v, char*t, char occ) */
1161: /* { */
1162: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
1163: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
1164: /* gives u="abcdef2ghi" and v="j" *\/ */
1165: /* int i,lg,j,p=0; */
1166: /* i=0; */
1167: /* lg=strlen(t); */
1168: /* for(j=0; j<=lg-1; j++) { */
1169: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
1170: /* } */
1171:
1172: /* for(j=0; j<p; j++) { */
1173: /* (u[j] = t[j]); */
1174: /* } */
1175: /* u[p]='\0'; */
1176:
1177: /* for(j=0; j<= lg; j++) { */
1178: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
1179: /* } */
1180: /* } */
1181:
1182: #ifdef _WIN32
1183: char * strsep(char **pp, const char *delim)
1184: {
1185: char *p, *q;
1186:
1187: if ((p = *pp) == NULL)
1188: return 0;
1189: if ((q = strpbrk (p, delim)) != NULL)
1190: {
1191: *pp = q + 1;
1192: *q = '\0';
1193: }
1194: else
1195: *pp = 0;
1196: return p;
1197: }
1198: #endif
1199:
1200: /********************** nrerror ********************/
1201:
1202: void nrerror(char error_text[])
1203: {
1204: fprintf(stderr,"ERREUR ...\n");
1205: fprintf(stderr,"%s\n",error_text);
1206: exit(EXIT_FAILURE);
1207: }
1208: /*********************** vector *******************/
1209: double *vector(int nl, int nh)
1210: {
1211: double *v;
1212: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1213: if (!v) nrerror("allocation failure in vector");
1214: return v-nl+NR_END;
1215: }
1216:
1217: /************************ free vector ******************/
1218: void free_vector(double*v, int nl, int nh)
1219: {
1220: free((FREE_ARG)(v+nl-NR_END));
1221: }
1222:
1223: /************************ivector *******************************/
1224: int *ivector(long nl,long nh)
1225: {
1226: int *v;
1227: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1228: if (!v) nrerror("allocation failure in ivector");
1229: return v-nl+NR_END;
1230: }
1231:
1232: /******************free ivector **************************/
1233: void free_ivector(int *v, long nl, long nh)
1234: {
1235: free((FREE_ARG)(v+nl-NR_END));
1236: }
1237:
1238: /************************lvector *******************************/
1239: long *lvector(long nl,long nh)
1240: {
1241: long *v;
1242: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1243: if (!v) nrerror("allocation failure in ivector");
1244: return v-nl+NR_END;
1245: }
1246:
1247: /******************free lvector **************************/
1248: void free_lvector(long *v, long nl, long nh)
1249: {
1250: free((FREE_ARG)(v+nl-NR_END));
1251: }
1252:
1253: /******************* imatrix *******************************/
1254: int **imatrix(long nrl, long nrh, long ncl, long nch)
1255: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1256: {
1257: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1258: int **m;
1259:
1260: /* allocate pointers to rows */
1261: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1262: if (!m) nrerror("allocation failure 1 in matrix()");
1263: m += NR_END;
1264: m -= nrl;
1265:
1266:
1267: /* allocate rows and set pointers to them */
1268: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1269: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1270: m[nrl] += NR_END;
1271: m[nrl] -= ncl;
1272:
1273: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1274:
1275: /* return pointer to array of pointers to rows */
1276: return m;
1277: }
1278:
1279: /****************** free_imatrix *************************/
1280: void free_imatrix(m,nrl,nrh,ncl,nch)
1281: int **m;
1282: long nch,ncl,nrh,nrl;
1283: /* free an int matrix allocated by imatrix() */
1284: {
1285: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1286: free((FREE_ARG) (m+nrl-NR_END));
1287: }
1288:
1289: /******************* matrix *******************************/
1290: double **matrix(long nrl, long nrh, long ncl, long nch)
1291: {
1292: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1293: double **m;
1294:
1295: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1296: if (!m) nrerror("allocation failure 1 in matrix()");
1297: m += NR_END;
1298: m -= nrl;
1299:
1300: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1301: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1302: m[nrl] += NR_END;
1303: m[nrl] -= ncl;
1304:
1305: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1306: return m;
1307: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1308: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1309: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1310: */
1311: }
1312:
1313: /*************************free matrix ************************/
1314: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1315: {
1316: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1317: free((FREE_ARG)(m+nrl-NR_END));
1318: }
1319:
1320: /******************* ma3x *******************************/
1321: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1322: {
1323: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1324: double ***m;
1325:
1326: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1327: if (!m) nrerror("allocation failure 1 in matrix()");
1328: m += NR_END;
1329: m -= nrl;
1330:
1331: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1332: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1333: m[nrl] += NR_END;
1334: m[nrl] -= ncl;
1335:
1336: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1337:
1338: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1339: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1340: m[nrl][ncl] += NR_END;
1341: m[nrl][ncl] -= nll;
1342: for (j=ncl+1; j<=nch; j++)
1343: m[nrl][j]=m[nrl][j-1]+nlay;
1344:
1345: for (i=nrl+1; i<=nrh; i++) {
1346: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1347: for (j=ncl+1; j<=nch; j++)
1348: m[i][j]=m[i][j-1]+nlay;
1349: }
1350: return m;
1351: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1352: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1353: */
1354: }
1355:
1356: /*************************free ma3x ************************/
1357: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1358: {
1359: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1360: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1361: free((FREE_ARG)(m+nrl-NR_END));
1362: }
1363:
1364: /*************** function subdirf ***********/
1365: char *subdirf(char fileres[])
1366: {
1367: /* Caution optionfilefiname is hidden */
1368: strcpy(tmpout,optionfilefiname);
1369: strcat(tmpout,"/"); /* Add to the right */
1370: strcat(tmpout,fileres);
1371: return tmpout;
1372: }
1373:
1374: /*************** function subdirf2 ***********/
1375: char *subdirf2(char fileres[], char *preop)
1376: {
1377:
1378: /* Caution optionfilefiname is hidden */
1379: strcpy(tmpout,optionfilefiname);
1380: strcat(tmpout,"/");
1381: strcat(tmpout,preop);
1382: strcat(tmpout,fileres);
1383: return tmpout;
1384: }
1385:
1386: /*************** function subdirf3 ***********/
1387: char *subdirf3(char fileres[], char *preop, char *preop2)
1388: {
1389:
1390: /* Caution optionfilefiname is hidden */
1391: strcpy(tmpout,optionfilefiname);
1392: strcat(tmpout,"/");
1393: strcat(tmpout,preop);
1394: strcat(tmpout,preop2);
1395: strcat(tmpout,fileres);
1396: return tmpout;
1397: }
1398:
1399: /*************** function subdirfext ***********/
1400: char *subdirfext(char fileres[], char *preop, char *postop)
1401: {
1402:
1403: strcpy(tmpout,preop);
1404: strcat(tmpout,fileres);
1405: strcat(tmpout,postop);
1406: return tmpout;
1407: }
1408:
1409: /*************** function subdirfext3 ***********/
1410: char *subdirfext3(char fileres[], char *preop, char *postop)
1411: {
1412:
1413: /* Caution optionfilefiname is hidden */
1414: strcpy(tmpout,optionfilefiname);
1415: strcat(tmpout,"/");
1416: strcat(tmpout,preop);
1417: strcat(tmpout,fileres);
1418: strcat(tmpout,postop);
1419: return tmpout;
1420: }
1421:
1422: char *asc_diff_time(long time_sec, char ascdiff[])
1423: {
1424: long sec_left, days, hours, minutes;
1425: days = (time_sec) / (60*60*24);
1426: sec_left = (time_sec) % (60*60*24);
1427: hours = (sec_left) / (60*60) ;
1428: sec_left = (sec_left) %(60*60);
1429: minutes = (sec_left) /60;
1430: sec_left = (sec_left) % (60);
1431: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1432: return ascdiff;
1433: }
1434:
1435: /***************** f1dim *************************/
1436: extern int ncom;
1437: extern double *pcom,*xicom;
1438: extern double (*nrfunc)(double []);
1439:
1440: double f1dim(double x)
1441: {
1442: int j;
1443: double f;
1444: double *xt;
1445:
1446: xt=vector(1,ncom);
1447: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1448: f=(*nrfunc)(xt);
1449: free_vector(xt,1,ncom);
1450: return f;
1451: }
1452:
1453: /*****************brent *************************/
1454: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1455: {
1456: /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
1457: * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
1458: * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
1459: * the minimum is returned as xmin, and the minimum function value is returned as brent , the
1460: * returned function value.
1461: */
1462: int iter;
1463: double a,b,d,etemp;
1464: double fu=0,fv,fw,fx;
1465: double ftemp=0.;
1466: double p,q,r,tol1,tol2,u,v,w,x,xm;
1467: double e=0.0;
1468:
1469: a=(ax < cx ? ax : cx);
1470: b=(ax > cx ? ax : cx);
1471: x=w=v=bx;
1472: fw=fv=fx=(*f)(x);
1473: for (iter=1;iter<=ITMAX;iter++) {
1474: xm=0.5*(a+b);
1475: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1476: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1477: printf(".");fflush(stdout);
1478: fprintf(ficlog,".");fflush(ficlog);
1479: #ifdef DEBUGBRENT
1480: 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);
1481: 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);
1482: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1483: #endif
1484: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1485: *xmin=x;
1486: return fx;
1487: }
1488: ftemp=fu;
1489: if (fabs(e) > tol1) {
1490: r=(x-w)*(fx-fv);
1491: q=(x-v)*(fx-fw);
1492: p=(x-v)*q-(x-w)*r;
1493: q=2.0*(q-r);
1494: if (q > 0.0) p = -p;
1495: q=fabs(q);
1496: etemp=e;
1497: e=d;
1498: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1499: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1500: else {
1501: d=p/q;
1502: u=x+d;
1503: if (u-a < tol2 || b-u < tol2)
1504: d=SIGN(tol1,xm-x);
1505: }
1506: } else {
1507: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1508: }
1509: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1510: fu=(*f)(u);
1511: if (fu <= fx) {
1512: if (u >= x) a=x; else b=x;
1513: SHFT(v,w,x,u)
1514: SHFT(fv,fw,fx,fu)
1515: } else {
1516: if (u < x) a=u; else b=u;
1517: if (fu <= fw || w == x) {
1518: v=w;
1519: w=u;
1520: fv=fw;
1521: fw=fu;
1522: } else if (fu <= fv || v == x || v == w) {
1523: v=u;
1524: fv=fu;
1525: }
1526: }
1527: }
1528: nrerror("Too many iterations in brent");
1529: *xmin=x;
1530: return fx;
1531: }
1532:
1533: /****************** mnbrak ***********************/
1534:
1535: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1536: double (*func)(double))
1537: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
1538: the downhill direction (defined by the function as evaluated at the initial points) and returns
1539: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
1540: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
1541: */
1542: double ulim,u,r,q, dum;
1543: double fu;
1544:
1545: double scale=10.;
1546: int iterscale=0;
1547:
1548: *fa=(*func)(*ax); /* xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
1549: *fb=(*func)(*bx); /* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
1550:
1551:
1552: /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
1553: /* printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
1554: /* *bx = *ax - (*ax - *bx)/scale; */
1555: /* *fb=(*func)(*bx); /\* xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
1556: /* } */
1557:
1558: if (*fb > *fa) {
1559: SHFT(dum,*ax,*bx,dum)
1560: SHFT(dum,*fb,*fa,dum)
1561: }
1562: *cx=(*bx)+GOLD*(*bx-*ax);
1563: *fc=(*func)(*cx);
1564: #ifdef DEBUG
1565: printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1566: fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
1567: #endif
1568: while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1569: r=(*bx-*ax)*(*fb-*fc);
1570: q=(*bx-*cx)*(*fb-*fa);
1571: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1572: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1573: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1574: if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1575: fu=(*func)(u);
1576: #ifdef DEBUG
1577: /* f(x)=A(x-u)**2+f(u) */
1578: double A, fparabu;
1579: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1580: fparabu= *fa - A*(*ax-u)*(*ax-u);
1581: 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);
1582: 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);
1583: /* And thus,it can be that fu > *fc even if fparabu < *fc */
1584: /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
1585: (*cx=10.098840694817, *fc=298946.631474258087), (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
1586: /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1587: #endif
1588: #ifdef MNBRAKORIGINAL
1589: #else
1590: /* if (fu > *fc) { */
1591: /* #ifdef DEBUG */
1592: /* printf("mnbrak4 fu > fc \n"); */
1593: /* fprintf(ficlog, "mnbrak4 fu > fc\n"); */
1594: /* #endif */
1595: /* /\* 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 *\\/ *\/ */
1596: /* /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc will exit *\\/ *\/ */
1597: /* dum=u; /\* Shifting c and u *\/ */
1598: /* u = *cx; */
1599: /* *cx = dum; */
1600: /* dum = fu; */
1601: /* fu = *fc; */
1602: /* *fc =dum; */
1603: /* } else { /\* end *\/ */
1604: /* #ifdef DEBUG */
1605: /* printf("mnbrak3 fu < fc \n"); */
1606: /* fprintf(ficlog, "mnbrak3 fu < fc\n"); */
1607: /* #endif */
1608: /* dum=u; /\* Shifting c and u *\/ */
1609: /* u = *cx; */
1610: /* *cx = dum; */
1611: /* dum = fu; */
1612: /* fu = *fc; */
1613: /* *fc =dum; */
1614: /* } */
1615: #ifdef DEBUG
1616: printf("mnbrak34 fu < or >= fc \n");
1617: fprintf(ficlog, "mnbrak34 fu < fc\n");
1618: #endif
1619: dum=u; /* Shifting c and u */
1620: u = *cx;
1621: *cx = dum;
1622: dum = fu;
1623: fu = *fc;
1624: *fc =dum;
1625: #endif
1626: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1627: #ifdef DEBUG
1628: printf("mnbrak2 u after c but before ulim\n");
1629: fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
1630: #endif
1631: fu=(*func)(u);
1632: if (fu < *fc) {
1633: #ifdef DEBUG
1634: printf("mnbrak2 u after c but before ulim AND fu < fc\n");
1635: fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
1636: #endif
1637: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1638: SHFT(*fb,*fc,fu,(*func)(u))
1639: }
1640: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1641: #ifdef DEBUG
1642: printf("mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1643: fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
1644: #endif
1645: u=ulim;
1646: fu=(*func)(u);
1647: } else { /* u could be left to b (if r > q parabola has a maximum) */
1648: #ifdef DEBUG
1649: printf("mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1650: fprintf(ficlog, "mnbrak2 u could be left to b (if r > q parabola has a maximum)\n");
1651: #endif
1652: u=(*cx)+GOLD*(*cx-*bx);
1653: fu=(*func)(u);
1654: } /* end tests */
1655: SHFT(*ax,*bx,*cx,u)
1656: SHFT(*fa,*fb,*fc,fu)
1657: #ifdef DEBUG
1658: 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);
1659: 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);
1660: #endif
1661: } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1662: }
1663:
1664: /*************** linmin ************************/
1665: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1666: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1667: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1668: the value of func at the returned location p . This is actually all accomplished by calling the
1669: routines mnbrak and brent .*/
1670: int ncom;
1671: double *pcom,*xicom;
1672: double (*nrfunc)(double []);
1673:
1674: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1675: {
1676: double brent(double ax, double bx, double cx,
1677: double (*f)(double), double tol, double *xmin);
1678: double f1dim(double x);
1679: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1680: double *fc, double (*func)(double));
1681: int j;
1682: double xx,xmin,bx,ax;
1683: double fx,fb,fa;
1684:
1685: #ifdef LINMINORIGINAL
1686: #else
1687: double scale=10., axs, xxs; /* Scale added for infinity */
1688: #endif
1689:
1690: ncom=n;
1691: pcom=vector(1,n);
1692: xicom=vector(1,n);
1693: nrfunc=func;
1694: for (j=1;j<=n;j++) {
1695: pcom[j]=p[j];
1696: xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1697: }
1698:
1699: #ifdef LINMINORIGINAL
1700: xx=1.;
1701: #else
1702: axs=0.0;
1703: xxs=1.;
1704: do{
1705: xx= xxs;
1706: #endif
1707: ax=0.;
1708: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
1709: /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
1710: /* 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)) */
1711: /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
1712: /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
1713: /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
1714: /* 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]]*/
1715: #ifdef LINMINORIGINAL
1716: #else
1717: if (fx != fx){
1718: xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
1719: printf("|");
1720: fprintf(ficlog,"|");
1721: #ifdef DEBUGLINMIN
1722: 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);
1723: #endif
1724: }
1725: }while(fx != fx);
1726: #endif
1727:
1728: #ifdef DEBUGLINMIN
1729: 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);
1730: 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);
1731: #endif
1732: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
1733: /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
1734: /* fmin = f(p[j] + xmin * xi[j]) */
1735: /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
1736: /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1737: #ifdef DEBUG
1738: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1739: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1740: #endif
1741: #ifdef DEBUGLINMIN
1742: printf("linmin end ");
1743: fprintf(ficlog,"linmin end ");
1744: #endif
1745: for (j=1;j<=n;j++) {
1746: #ifdef LINMINORIGINAL
1747: xi[j] *= xmin;
1748: #else
1749: #ifdef DEBUGLINMIN
1750: if(xxs <1.0)
1751: printf(" before xi[%d]=%12.8f", j,xi[j]);
1752: #endif
1753: 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) */
1754: #ifdef DEBUGLINMIN
1755: if(xxs <1.0)
1756: 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 );
1757: #endif
1758: #endif
1759: p[j] += xi[j]; /* Parameters values are updated accordingly */
1760: }
1761: #ifdef DEBUGLINMIN
1762: printf("\n");
1763: printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1764: fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1765: for (j=1;j<=n;j++) {
1766: printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1767: fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
1768: if(j % ncovmodel == 0){
1769: printf("\n");
1770: fprintf(ficlog,"\n");
1771: }
1772: }
1773: #else
1774: #endif
1775: free_vector(xicom,1,n);
1776: free_vector(pcom,1,n);
1777: }
1778:
1779:
1780: /*************** powell ************************/
1781: /*
1782: Minimization of a function func of n variables. Input consists of an initial starting point
1783: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1784: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1785: such that failure to decrease by more than this amount on one iteration signals doneness. On
1786: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1787: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1788: */
1789: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1790: double (*func)(double []))
1791: {
1792: void linmin(double p[], double xi[], int n, double *fret,
1793: double (*func)(double []));
1794: int i,ibig,j;
1795: double del,t,*pt,*ptt,*xit;
1796: double directest;
1797: double fp,fptt;
1798: double *xits;
1799: int niterf, itmp;
1800:
1801: pt=vector(1,n);
1802: ptt=vector(1,n);
1803: xit=vector(1,n);
1804: xits=vector(1,n);
1805: *fret=(*func)(p);
1806: for (j=1;j<=n;j++) pt[j]=p[j];
1807: rcurr_time = time(NULL);
1808: for (*iter=1;;++(*iter)) {
1809: fp=(*fret); /* From former iteration or initial value */
1810: ibig=0;
1811: del=0.0;
1812: rlast_time=rcurr_time;
1813: /* (void) gettimeofday(&curr_time,&tzp); */
1814: rcurr_time = time(NULL);
1815: curr_time = *localtime(&rcurr_time);
1816: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1817: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1818: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1819: for (i=1;i<=n;i++) {
1820: printf(" %d %.12f",i, p[i]);
1821: fprintf(ficlog," %d %.12lf",i, p[i]);
1822: fprintf(ficrespow," %.12lf", p[i]);
1823: }
1824: printf("\n");
1825: fprintf(ficlog,"\n");
1826: fprintf(ficrespow,"\n");fflush(ficrespow);
1827: if(*iter <=3){
1828: tml = *localtime(&rcurr_time);
1829: strcpy(strcurr,asctime(&tml));
1830: rforecast_time=rcurr_time;
1831: itmp = strlen(strcurr);
1832: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1833: strcurr[itmp-1]='\0';
1834: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1835: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1836: for(niterf=10;niterf<=30;niterf+=10){
1837: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1838: forecast_time = *localtime(&rforecast_time);
1839: strcpy(strfor,asctime(&forecast_time));
1840: itmp = strlen(strfor);
1841: if(strfor[itmp-1]=='\n')
1842: strfor[itmp-1]='\0';
1843: 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);
1844: 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);
1845: }
1846: }
1847: for (i=1;i<=n;i++) { /* For each direction i */
1848: for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1849: fptt=(*fret);
1850: #ifdef DEBUG
1851: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1852: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1853: #endif
1854: printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1855: fprintf(ficlog,"%d",i);fflush(ficlog);
1856: linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1857: /* Outputs are fret(new point p) p is updated and xit rescaled */
1858: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1859: /* because that direction will be replaced unless the gain del is small */
1860: /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
1861: /* Unless the n directions are conjugate some gain in the determinant may be obtained */
1862: /* with the new direction. */
1863: del=fabs(fptt-(*fret));
1864: ibig=i;
1865: }
1866: #ifdef DEBUG
1867: printf("%d %.12e",i,(*fret));
1868: fprintf(ficlog,"%d %.12e",i,(*fret));
1869: for (j=1;j<=n;j++) {
1870: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1871: printf(" x(%d)=%.12e",j,xit[j]);
1872: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1873: }
1874: for(j=1;j<=n;j++) {
1875: printf(" p(%d)=%.12e",j,p[j]);
1876: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1877: }
1878: printf("\n");
1879: fprintf(ficlog,"\n");
1880: #endif
1881: } /* end loop on each direction i */
1882: /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */
1883: /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit */
1884: /* New value of last point Pn is not computed, P(n-1) */
1885: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1886: /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
1887: /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
1888: /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
1889: /* decreased of more than 3.84 */
1890: /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
1891: /* By using V1+V2+V3, the gain should be 7.82, compared with basic 1+age. */
1892: /* By adding 10 parameters more the gain should be 18.31 */
1893:
1894: /* Starting the program with initial values given by a former maximization will simply change */
1895: /* the scales of the directions and the directions, because the are reset to canonical directions */
1896: /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
1897: /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long. */
1898: #ifdef DEBUG
1899: int k[2],l;
1900: k[0]=1;
1901: k[1]=-1;
1902: printf("Max: %.12e",(*func)(p));
1903: fprintf(ficlog,"Max: %.12e",(*func)(p));
1904: for (j=1;j<=n;j++) {
1905: printf(" %.12e",p[j]);
1906: fprintf(ficlog," %.12e",p[j]);
1907: }
1908: printf("\n");
1909: fprintf(ficlog,"\n");
1910: for(l=0;l<=1;l++) {
1911: for (j=1;j<=n;j++) {
1912: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1913: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1914: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1915: }
1916: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1917: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1918: }
1919: #endif
1920:
1921:
1922: free_vector(xit,1,n);
1923: free_vector(xits,1,n);
1924: free_vector(ptt,1,n);
1925: free_vector(pt,1,n);
1926: return;
1927: } /* enough precision */
1928: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1929: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1930: ptt[j]=2.0*p[j]-pt[j];
1931: xit[j]=p[j]-pt[j];
1932: pt[j]=p[j];
1933: }
1934: fptt=(*func)(ptt); /* f_3 */
1935: #ifdef POWELLF1F3
1936: #else
1937: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1938: #endif
1939: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1940: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1941: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1942: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1943: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1944: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1945: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1946: #ifdef NRCORIGINAL
1947: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
1948: #else
1949: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1950: t= t- del*SQR(fp-fptt);
1951: #endif
1952: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1953: #ifdef DEBUG
1954: 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);
1955: 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);
1956: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1957: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1958: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1959: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1960: 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);
1961: 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);
1962: #endif
1963: #ifdef POWELLORIGINAL
1964: if (t < 0.0) { /* Then we use it for new direction */
1965: #else
1966: if (directest*t < 0.0) { /* Contradiction between both tests */
1967: 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);
1968: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1969: 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);
1970: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1971: }
1972: if (directest < 0.0) { /* Then we use it for new direction */
1973: #endif
1974: #ifdef DEBUGLINMIN
1975: printf("Before linmin in direction P%d-P0\n",n);
1976: for (j=1;j<=n;j++) {
1977: printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1978: fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1979: if(j % ncovmodel == 0){
1980: printf("\n");
1981: fprintf(ficlog,"\n");
1982: }
1983: }
1984: #endif
1985: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1986: #ifdef DEBUGLINMIN
1987: for (j=1;j<=n;j++) {
1988: printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1989: fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1990: if(j % ncovmodel == 0){
1991: printf("\n");
1992: fprintf(ficlog,"\n");
1993: }
1994: }
1995: #endif
1996: for (j=1;j<=n;j++) {
1997: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1998: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1999: }
2000: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2001: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
2002:
2003: #ifdef DEBUG
2004: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2005: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
2006: for(j=1;j<=n;j++){
2007: printf(" %.12e",xit[j]);
2008: fprintf(ficlog," %.12e",xit[j]);
2009: }
2010: printf("\n");
2011: fprintf(ficlog,"\n");
2012: #endif
2013: } /* end of t or directest negative */
2014: #ifdef POWELLF1F3
2015: #else
2016: } /* end if (fptt < fp) */
2017: #endif
2018: } /* loop iteration */
2019: }
2020:
2021: /**** Prevalence limit (stable or period prevalence) ****************/
2022:
2023: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
2024: {
2025: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
2026: matrix by transitions matrix until convergence is reached with precision ftolpl */
2027: /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1 = Wx-n Px-n ... Px-2 Px-1 I */
2028: /* Wx is row vector: population in state 1, population in state 2, population dead */
2029: /* or prevalence in state 1, prevalence in state 2, 0 */
2030: /* newm is the matrix after multiplications, its rows are identical at a factor */
2031: /* Initial matrix pimij */
2032: /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
2033: /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
2034: /* 0, 0 , 1} */
2035: /*
2036: * and after some iteration: */
2037: /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
2038: /* 0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
2039: /* 0, 0 , 1} */
2040: /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
2041: /* {0.51571254859325999, 0.4842874514067399, */
2042: /* 0.51326036147820708, 0.48673963852179264} */
2043: /* If we start from prlim again, prlim tends to a constant matrix */
2044:
2045: int i, ii,j,k;
2046: double *min, *max, *meandiff, maxmax,sumnew=0.;
2047: /* double **matprod2(); */ /* test */
2048: double **out, cov[NCOVMAX+1], **pmij();
2049: double **newm;
2050: double agefin, delaymax=200. ; /* 100 Max number of years to converge */
2051: int ncvloop=0;
2052:
2053: min=vector(1,nlstate);
2054: max=vector(1,nlstate);
2055: meandiff=vector(1,nlstate);
2056:
2057: for (ii=1;ii<=nlstate+ndeath;ii++)
2058: for (j=1;j<=nlstate+ndeath;j++){
2059: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2060: }
2061:
2062: cov[1]=1.;
2063:
2064: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2065: /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
2066: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
2067: ncvloop++;
2068: newm=savm;
2069: /* Covariates have to be included here again */
2070: cov[2]=agefin;
2071: if(nagesqr==1)
2072: cov[3]= agefin*agefin;;
2073: for (k=1; k<=cptcovn;k++) {
2074: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2075: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2076: /* 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])]); */
2077: }
2078: /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2079: /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
2080: for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
2081: for (k=1; k<=cptcovprod;k++) /* Useless */
2082: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2083: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
2084:
2085: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
2086: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
2087: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
2088: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2089: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
2090: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
2091:
2092: savm=oldm;
2093: oldm=newm;
2094:
2095: for(j=1; j<=nlstate; j++){
2096: max[j]=0.;
2097: min[j]=1.;
2098: }
2099: for(i=1;i<=nlstate;i++){
2100: sumnew=0;
2101: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
2102: for(j=1; j<=nlstate; j++){
2103: prlim[i][j]= newm[i][j]/(1-sumnew);
2104: max[j]=FMAX(max[j],prlim[i][j]);
2105: min[j]=FMIN(min[j],prlim[i][j]);
2106: }
2107: }
2108:
2109: maxmax=0.;
2110: for(j=1; j<=nlstate; j++){
2111: meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
2112: maxmax=FMAX(maxmax,meandiff[j]);
2113: /* 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); */
2114: } /* j loop */
2115: *ncvyear= (int)age- (int)agefin;
2116: /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
2117: if(maxmax < ftolpl){
2118: /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
2119: free_vector(min,1,nlstate);
2120: free_vector(max,1,nlstate);
2121: free_vector(meandiff,1,nlstate);
2122: return prlim;
2123: }
2124: } /* age loop */
2125: /* After some age loop it doesn't converge */
2126: 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\
2127: 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);
2128: /* 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); */
2129: free_vector(min,1,nlstate);
2130: free_vector(max,1,nlstate);
2131: free_vector(meandiff,1,nlstate);
2132:
2133: return prlim; /* should not reach here */
2134: }
2135:
2136: /*************** transition probabilities ***************/
2137:
2138: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
2139: {
2140: /* According to parameters values stored in x and the covariate's values stored in cov,
2141: computes the probability to be observed in state j being in state i by appying the
2142: model to the ncovmodel covariates (including constant and age).
2143: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
2144: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
2145: ncth covariate in the global vector x is given by the formula:
2146: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
2147: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
2148: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
2149: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
2150: Outputs ps[i][j] the probability to be observed in j being in j according to
2151: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
2152: */
2153: double s1, lnpijopii;
2154: /*double t34;*/
2155: int i,j, nc, ii, jj;
2156:
2157: for(i=1; i<= nlstate; i++){
2158: for(j=1; j<i;j++){
2159: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2160: /*lnpijopii += param[i][j][nc]*cov[nc];*/
2161: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
2162: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2163: }
2164: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2165: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
2166: }
2167: for(j=i+1; j<=nlstate+ndeath;j++){
2168: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
2169: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
2170: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
2171: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
2172: }
2173: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
2174: }
2175: }
2176:
2177: for(i=1; i<= nlstate; i++){
2178: s1=0;
2179: for(j=1; j<i; j++){
2180: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2181: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2182: }
2183: for(j=i+1; j<=nlstate+ndeath; j++){
2184: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
2185: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
2186: }
2187: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
2188: ps[i][i]=1./(s1+1.);
2189: /* Computing other pijs */
2190: for(j=1; j<i; j++)
2191: ps[i][j]= exp(ps[i][j])*ps[i][i];
2192: for(j=i+1; j<=nlstate+ndeath; j++)
2193: ps[i][j]= exp(ps[i][j])*ps[i][i];
2194: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
2195: } /* end i */
2196:
2197: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
2198: for(jj=1; jj<= nlstate+ndeath; jj++){
2199: ps[ii][jj]=0;
2200: ps[ii][ii]=1;
2201: }
2202: }
2203:
2204:
2205: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
2206: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
2207: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
2208: /* } */
2209: /* printf("\n "); */
2210: /* } */
2211: /* printf("\n ");printf("%lf ",cov[2]);*/
2212: /*
2213: for(i=1; i<= npar; i++) printf("%f ",x[i]);
2214: goto end;*/
2215: return ps;
2216: }
2217:
2218: /**************** Product of 2 matrices ******************/
2219:
2220: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
2221: {
2222: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
2223: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
2224: /* in, b, out are matrice of pointers which should have been initialized
2225: before: only the contents of out is modified. The function returns
2226: a pointer to pointers identical to out */
2227: int i, j, k;
2228: for(i=nrl; i<= nrh; i++)
2229: for(k=ncolol; k<=ncoloh; k++){
2230: out[i][k]=0.;
2231: for(j=ncl; j<=nch; j++)
2232: out[i][k] +=in[i][j]*b[j][k];
2233: }
2234: return out;
2235: }
2236:
2237:
2238: /************* Higher Matrix Product ***************/
2239:
2240: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
2241: {
2242: /* Computes the transition matrix starting at age 'age' over
2243: 'nhstepm*hstepm*stepm' months (i.e. until
2244: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
2245: nhstepm*hstepm matrices.
2246: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
2247: (typically every 2 years instead of every month which is too big
2248: for the memory).
2249: Model is determined by parameters x and covariates have to be
2250: included manually here.
2251:
2252: */
2253:
2254: int i, j, d, h, k;
2255: double **out, cov[NCOVMAX+1];
2256: double **newm;
2257: double agexact;
2258: double agebegin, ageend;
2259:
2260: /* Hstepm could be zero and should return the unit matrix */
2261: for (i=1;i<=nlstate+ndeath;i++)
2262: for (j=1;j<=nlstate+ndeath;j++){
2263: oldm[i][j]=(i==j ? 1.0 : 0.0);
2264: po[i][j][0]=(i==j ? 1.0 : 0.0);
2265: }
2266: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
2267: for(h=1; h <=nhstepm; h++){
2268: for(d=1; d <=hstepm; d++){
2269: newm=savm;
2270: /* Covariates have to be included here again */
2271: cov[1]=1.;
2272: agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
2273: cov[2]=agexact;
2274: if(nagesqr==1)
2275: cov[3]= agexact*agexact;
2276: for (k=1; k<=cptcovn;k++)
2277: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
2278: /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
2279: for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
2280: /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
2281: cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
2282: /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
2283: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
2284: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
2285: /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
2286:
2287:
2288: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
2289: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
2290: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
2291: pmij(pmmij,cov,ncovmodel,x,nlstate));
2292: savm=oldm;
2293: oldm=newm;
2294: }
2295: for(i=1; i<=nlstate+ndeath; i++)
2296: for(j=1;j<=nlstate+ndeath;j++) {
2297: po[i][j][h]=newm[i][j];
2298: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
2299: }
2300: /*printf("h=%d ",h);*/
2301: } /* end h */
2302: /* printf("\n H=%d \n",h); */
2303: return po;
2304: }
2305:
2306: #ifdef NLOPT
2307: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
2308: double fret;
2309: double *xt;
2310: int j;
2311: myfunc_data *d2 = (myfunc_data *) pd;
2312: /* xt = (p1-1); */
2313: xt=vector(1,n);
2314: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
2315:
2316: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
2317: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
2318: printf("Function = %.12lf ",fret);
2319: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
2320: printf("\n");
2321: free_vector(xt,1,n);
2322: return fret;
2323: }
2324: #endif
2325:
2326: /*************** log-likelihood *************/
2327: double func( double *x)
2328: {
2329: int i, ii, j, k, mi, d, kk;
2330: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2331: double **out;
2332: double sw; /* Sum of weights */
2333: double lli; /* Individual log likelihood */
2334: int s1, s2;
2335: double bbh, survp;
2336: long ipmx;
2337: double agexact;
2338: /*extern weight */
2339: /* We are differentiating ll according to initial status */
2340: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2341: /*for(i=1;i<imx;i++)
2342: printf(" %d\n",s[4][i]);
2343: */
2344:
2345: ++countcallfunc;
2346:
2347: cov[1]=1.;
2348:
2349: for(k=1; k<=nlstate; k++) ll[k]=0.;
2350:
2351: if(mle==1){
2352: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2353: /* Computes the values of the ncovmodel covariates of the model
2354: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
2355: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
2356: to be observed in j being in i according to the model.
2357: */
2358: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
2359: cov[2+nagesqr+k]=covar[Tvar[k]][i];
2360: }
2361: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
2362: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
2363: has been calculated etc */
2364: for(mi=1; mi<= wav[i]-1; mi++){
2365: for (ii=1;ii<=nlstate+ndeath;ii++)
2366: for (j=1;j<=nlstate+ndeath;j++){
2367: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2368: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2369: }
2370: for(d=0; d<dh[mi][i]; d++){
2371: newm=savm;
2372: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2373: cov[2]=agexact;
2374: if(nagesqr==1)
2375: cov[3]= agexact*agexact;
2376: for (kk=1; kk<=cptcovage;kk++) {
2377: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
2378: }
2379: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2380: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2381: savm=oldm;
2382: oldm=newm;
2383: } /* end mult */
2384:
2385: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
2386: /* But now since version 0.9 we anticipate for bias at large stepm.
2387: * If stepm is larger than one month (smallest stepm) and if the exact delay
2388: * (in months) between two waves is not a multiple of stepm, we rounded to
2389: * the nearest (and in case of equal distance, to the lowest) interval but now
2390: * we keep into memory the bias bh[mi][i] and also the previous matrix product
2391: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
2392: * probability in order to take into account the bias as a fraction of the way
2393: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
2394: * -stepm/2 to stepm/2 .
2395: * For stepm=1 the results are the same as for previous versions of Imach.
2396: * For stepm > 1 the results are less biased than in previous versions.
2397: */
2398: s1=s[mw[mi][i]][i];
2399: s2=s[mw[mi+1][i]][i];
2400: bbh=(double)bh[mi][i]/(double)stepm;
2401: /* bias bh is positive if real duration
2402: * is higher than the multiple of stepm and negative otherwise.
2403: */
2404: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
2405: if( s2 > nlstate){
2406: /* i.e. if s2 is a death state and if the date of death is known
2407: then the contribution to the likelihood is the probability to
2408: die between last step unit time and current step unit time,
2409: which is also equal to probability to die before dh
2410: minus probability to die before dh-stepm .
2411: In version up to 0.92 likelihood was computed
2412: as if date of death was unknown. Death was treated as any other
2413: health state: the date of the interview describes the actual state
2414: and not the date of a change in health state. The former idea was
2415: to consider that at each interview the state was recorded
2416: (healthy, disable or death) and IMaCh was corrected; but when we
2417: introduced the exact date of death then we should have modified
2418: the contribution of an exact death to the likelihood. This new
2419: contribution is smaller and very dependent of the step unit
2420: stepm. It is no more the probability to die between last interview
2421: and month of death but the probability to survive from last
2422: interview up to one month before death multiplied by the
2423: probability to die within a month. Thanks to Chris
2424: Jackson for correcting this bug. Former versions increased
2425: mortality artificially. The bad side is that we add another loop
2426: which slows down the processing. The difference can be up to 10%
2427: lower mortality.
2428: */
2429: /* If, at the beginning of the maximization mostly, the
2430: cumulative probability or probability to be dead is
2431: constant (ie = 1) over time d, the difference is equal to
2432: 0. out[s1][3] = savm[s1][3]: probability, being at state
2433: s1 at precedent wave, to be dead a month before current
2434: wave is equal to probability, being at state s1 at
2435: precedent wave, to be dead at mont of the current
2436: wave. Then the observed probability (that this person died)
2437: is null according to current estimated parameter. In fact,
2438: it should be very low but not zero otherwise the log go to
2439: infinity.
2440: */
2441: /* #ifdef INFINITYORIGINAL */
2442: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2443: /* #else */
2444: /* if ((out[s1][s2] - savm[s1][s2]) < mytinydouble) */
2445: /* lli=log(mytinydouble); */
2446: /* else */
2447: /* lli=log(out[s1][s2] - savm[s1][s2]); */
2448: /* #endif */
2449: lli=log(out[s1][s2] - savm[s1][s2]);
2450:
2451: } else if (s2==-2) {
2452: for (j=1,survp=0. ; j<=nlstate; j++)
2453: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2454: /*survp += out[s1][j]; */
2455: lli= log(survp);
2456: }
2457:
2458: else if (s2==-4) {
2459: for (j=3,survp=0. ; j<=nlstate; j++)
2460: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2461: lli= log(survp);
2462: }
2463:
2464: else if (s2==-5) {
2465: for (j=1,survp=0. ; j<=2; j++)
2466: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2467: lli= log(survp);
2468: }
2469:
2470: else{
2471: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2472: /* 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 */
2473: }
2474: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
2475: /*if(lli ==000.0)*/
2476: /*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); */
2477: ipmx +=1;
2478: sw += weight[i];
2479: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2480: /* if (lli < log(mytinydouble)){ */
2481: /* 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); */
2482: /* 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]); */
2483: /* } */
2484: } /* end of wave */
2485: } /* end of individual */
2486: } else if(mle==2){
2487: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2488: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2489: for(mi=1; mi<= wav[i]-1; mi++){
2490: for (ii=1;ii<=nlstate+ndeath;ii++)
2491: for (j=1;j<=nlstate+ndeath;j++){
2492: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2493: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2494: }
2495: for(d=0; d<=dh[mi][i]; d++){
2496: newm=savm;
2497: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2498: cov[2]=agexact;
2499: if(nagesqr==1)
2500: cov[3]= agexact*agexact;
2501: for (kk=1; kk<=cptcovage;kk++) {
2502: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2503: }
2504: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2505: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2506: savm=oldm;
2507: oldm=newm;
2508: } /* end mult */
2509:
2510: s1=s[mw[mi][i]][i];
2511: s2=s[mw[mi+1][i]][i];
2512: bbh=(double)bh[mi][i]/(double)stepm;
2513: 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 */
2514: ipmx +=1;
2515: sw += weight[i];
2516: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2517: } /* end of wave */
2518: } /* end of individual */
2519: } else if(mle==3){ /* exponential inter-extrapolation */
2520: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2521: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2522: for(mi=1; mi<= wav[i]-1; mi++){
2523: for (ii=1;ii<=nlstate+ndeath;ii++)
2524: for (j=1;j<=nlstate+ndeath;j++){
2525: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2526: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2527: }
2528: for(d=0; d<dh[mi][i]; d++){
2529: newm=savm;
2530: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2531: cov[2]=agexact;
2532: if(nagesqr==1)
2533: cov[3]= agexact*agexact;
2534: for (kk=1; kk<=cptcovage;kk++) {
2535: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2536: }
2537: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2538: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2539: savm=oldm;
2540: oldm=newm;
2541: } /* end mult */
2542:
2543: s1=s[mw[mi][i]][i];
2544: s2=s[mw[mi+1][i]][i];
2545: bbh=(double)bh[mi][i]/(double)stepm;
2546: 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 */
2547: ipmx +=1;
2548: sw += weight[i];
2549: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2550: } /* end of wave */
2551: } /* end of individual */
2552: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2553: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2554: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2555: for(mi=1; mi<= wav[i]-1; mi++){
2556: for (ii=1;ii<=nlstate+ndeath;ii++)
2557: for (j=1;j<=nlstate+ndeath;j++){
2558: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2559: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2560: }
2561: for(d=0; d<dh[mi][i]; d++){
2562: newm=savm;
2563: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2564: cov[2]=agexact;
2565: if(nagesqr==1)
2566: cov[3]= agexact*agexact;
2567: for (kk=1; kk<=cptcovage;kk++) {
2568: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2569: }
2570:
2571: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2572: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2573: savm=oldm;
2574: oldm=newm;
2575: } /* end mult */
2576:
2577: s1=s[mw[mi][i]][i];
2578: s2=s[mw[mi+1][i]][i];
2579: if( s2 > nlstate){
2580: lli=log(out[s1][s2] - savm[s1][s2]);
2581: }else{
2582: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2583: }
2584: ipmx +=1;
2585: sw += weight[i];
2586: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2587: /* 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]); */
2588: } /* end of wave */
2589: } /* end of individual */
2590: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2591: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2592: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2593: for(mi=1; mi<= wav[i]-1; mi++){
2594: for (ii=1;ii<=nlstate+ndeath;ii++)
2595: for (j=1;j<=nlstate+ndeath;j++){
2596: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2597: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2598: }
2599: for(d=0; d<dh[mi][i]; d++){
2600: newm=savm;
2601: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2602: cov[2]=agexact;
2603: if(nagesqr==1)
2604: cov[3]= agexact*agexact;
2605: for (kk=1; kk<=cptcovage;kk++) {
2606: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2607: }
2608:
2609: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2610: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2611: savm=oldm;
2612: oldm=newm;
2613: } /* end mult */
2614:
2615: s1=s[mw[mi][i]][i];
2616: s2=s[mw[mi+1][i]][i];
2617: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2618: ipmx +=1;
2619: sw += weight[i];
2620: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2621: /*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]);*/
2622: } /* end of wave */
2623: } /* end of individual */
2624: } /* End of if */
2625: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2626: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2627: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2628: return -l;
2629: }
2630:
2631: /*************** log-likelihood *************/
2632: double funcone( double *x)
2633: {
2634: /* Same as likeli but slower because of a lot of printf and if */
2635: int i, ii, j, k, mi, d, kk;
2636: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2637: double **out;
2638: double lli; /* Individual log likelihood */
2639: double llt;
2640: int s1, s2;
2641: double bbh, survp;
2642: double agexact;
2643: double agebegin, ageend;
2644: /*extern weight */
2645: /* We are differentiating ll according to initial status */
2646: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2647: /*for(i=1;i<imx;i++)
2648: printf(" %d\n",s[4][i]);
2649: */
2650: cov[1]=1.;
2651:
2652: for(k=1; k<=nlstate; k++) ll[k]=0.;
2653:
2654: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2655: for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
2656: for(mi=1; mi<= wav[i]-1; mi++){
2657: for (ii=1;ii<=nlstate+ndeath;ii++)
2658: for (j=1;j<=nlstate+ndeath;j++){
2659: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2660: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2661: }
2662:
2663: agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
2664: ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
2665: for(d=0; d<dh[mi][i]; d++){ /* Delay between two effective waves */
2666: /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2667: and mw[mi+1][i]. dh depends on stepm.*/
2668: newm=savm;
2669: agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
2670: cov[2]=agexact;
2671: if(nagesqr==1)
2672: cov[3]= agexact*agexact;
2673: for (kk=1; kk<=cptcovage;kk++) {
2674: cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
2675: }
2676:
2677: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2678: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2679: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2680: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2681: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2682: savm=oldm;
2683: oldm=newm;
2684: } /* end mult */
2685:
2686: s1=s[mw[mi][i]][i];
2687: s2=s[mw[mi+1][i]][i];
2688: bbh=(double)bh[mi][i]/(double)stepm;
2689: /* bias is positive if real duration
2690: * is higher than the multiple of stepm and negative otherwise.
2691: */
2692: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2693: lli=log(out[s1][s2] - savm[s1][s2]);
2694: } else if (s2==-2) {
2695: for (j=1,survp=0. ; j<=nlstate; j++)
2696: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2697: lli= log(survp);
2698: }else if (mle==1){
2699: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2700: } else if(mle==2){
2701: 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 */
2702: } else if(mle==3){ /* exponential inter-extrapolation */
2703: 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 */
2704: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2705: lli=log(out[s1][s2]); /* Original formula */
2706: } else{ /* mle=0 back to 1 */
2707: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2708: /*lli=log(out[s1][s2]); */ /* Original formula */
2709: } /* End of if */
2710: ipmx +=1;
2711: sw += weight[i];
2712: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2713: /*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]); */
2714: if(globpr){
2715: fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
2716: %11.6f %11.6f %11.6f ", \
2717: num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
2718: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2719: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2720: llt +=ll[k]*gipmx/gsw;
2721: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2722: }
2723: fprintf(ficresilk," %10.6f\n", -llt);
2724: }
2725: } /* end of wave */
2726: } /* end of individual */
2727: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2728: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2729: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2730: if(globpr==0){ /* First time we count the contributions and weights */
2731: gipmx=ipmx;
2732: gsw=sw;
2733: }
2734: return -l;
2735: }
2736:
2737:
2738: /*************** function likelione ***********/
2739: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2740: {
2741: /* This routine should help understanding what is done with
2742: the selection of individuals/waves and
2743: to check the exact contribution to the likelihood.
2744: Plotting could be done.
2745: */
2746: int k;
2747:
2748: if(*globpri !=0){ /* Just counts and sums, no printings */
2749: strcpy(fileresilk,"ILK_");
2750: strcat(fileresilk,fileresu);
2751: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2752: printf("Problem with resultfile: %s\n", fileresilk);
2753: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2754: }
2755: fprintf(ficresilk, "#individual(line's_record) count ageb ageend s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
2756: fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
2757: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2758: for(k=1; k<=nlstate; k++)
2759: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2760: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2761: }
2762:
2763: *fretone=(*funcone)(p);
2764: if(*globpri !=0){
2765: fclose(ficresilk);
2766: if (mle ==0)
2767: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
2768: else if(mle >=1)
2769: fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
2770: 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));
2771:
2772:
2773: for (k=1; k<= nlstate ; k++) {
2774: fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
2775: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
2776: }
2777: 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> \
2778: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2779: fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
2780: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
2781: fflush(fichtm);
2782: }
2783: return;
2784: }
2785:
2786:
2787: /*********** Maximum Likelihood Estimation ***************/
2788:
2789: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2790: {
2791: int i,j, iter=0;
2792: double **xi;
2793: double fret;
2794: double fretone; /* Only one call to likelihood */
2795: /* char filerespow[FILENAMELENGTH];*/
2796:
2797: #ifdef NLOPT
2798: int creturn;
2799: nlopt_opt opt;
2800: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2801: double *lb;
2802: double minf; /* the minimum objective value, upon return */
2803: double * p1; /* Shifted parameters from 0 instead of 1 */
2804: myfunc_data dinst, *d = &dinst;
2805: #endif
2806:
2807:
2808: xi=matrix(1,npar,1,npar);
2809: for (i=1;i<=npar;i++)
2810: for (j=1;j<=npar;j++)
2811: xi[i][j]=(i==j ? 1.0 : 0.0);
2812: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2813: strcpy(filerespow,"POW_");
2814: strcat(filerespow,fileres);
2815: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2816: printf("Problem with resultfile: %s\n", filerespow);
2817: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2818: }
2819: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2820: for (i=1;i<=nlstate;i++)
2821: for(j=1;j<=nlstate+ndeath;j++)
2822: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2823: fprintf(ficrespow,"\n");
2824: #ifdef POWELL
2825: powell(p,xi,npar,ftol,&iter,&fret,func);
2826: #endif
2827:
2828: #ifdef NLOPT
2829: #ifdef NEWUOA
2830: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2831: #else
2832: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2833: #endif
2834: lb=vector(0,npar-1);
2835: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2836: nlopt_set_lower_bounds(opt, lb);
2837: nlopt_set_initial_step1(opt, 0.1);
2838:
2839: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2840: d->function = func;
2841: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2842: nlopt_set_min_objective(opt, myfunc, d);
2843: nlopt_set_xtol_rel(opt, ftol);
2844: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2845: printf("nlopt failed! %d\n",creturn);
2846: }
2847: else {
2848: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2849: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2850: iter=1; /* not equal */
2851: }
2852: nlopt_destroy(opt);
2853: #endif
2854: free_matrix(xi,1,npar,1,npar);
2855: fclose(ficrespow);
2856: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2857: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2858: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2859:
2860: }
2861:
2862: /**** Computes Hessian and covariance matrix ***/
2863: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2864: {
2865: double **a,**y,*x,pd;
2866: /* double **hess; */
2867: int i, j;
2868: int *indx;
2869:
2870: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2871: double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
2872: void lubksb(double **a, int npar, int *indx, double b[]) ;
2873: void ludcmp(double **a, int npar, int *indx, double *d) ;
2874: double gompertz(double p[]);
2875: /* hess=matrix(1,npar,1,npar); */
2876:
2877: printf("\nCalculation of the hessian matrix. Wait...\n");
2878: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2879: for (i=1;i<=npar;i++){
2880: printf("%d-",i);fflush(stdout);
2881: fprintf(ficlog,"%d-",i);fflush(ficlog);
2882:
2883: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2884:
2885: /* printf(" %f ",p[i]);
2886: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2887: }
2888:
2889: for (i=1;i<=npar;i++) {
2890: for (j=1;j<=npar;j++) {
2891: if (j>i) {
2892: printf(".%d-%d",i,j);fflush(stdout);
2893: fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
2894: hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
2895:
2896: hess[j][i]=hess[i][j];
2897: /*printf(" %lf ",hess[i][j]);*/
2898: }
2899: }
2900: }
2901: printf("\n");
2902: fprintf(ficlog,"\n");
2903:
2904: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2905: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2906:
2907: a=matrix(1,npar,1,npar);
2908: y=matrix(1,npar,1,npar);
2909: x=vector(1,npar);
2910: indx=ivector(1,npar);
2911: for (i=1;i<=npar;i++)
2912: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2913: ludcmp(a,npar,indx,&pd);
2914:
2915: for (j=1;j<=npar;j++) {
2916: for (i=1;i<=npar;i++) x[i]=0;
2917: x[j]=1;
2918: lubksb(a,npar,indx,x);
2919: for (i=1;i<=npar;i++){
2920: matcov[i][j]=x[i];
2921: }
2922: }
2923:
2924: printf("\n#Hessian matrix#\n");
2925: fprintf(ficlog,"\n#Hessian matrix#\n");
2926: for (i=1;i<=npar;i++) {
2927: for (j=1;j<=npar;j++) {
2928: printf("%.6e ",hess[i][j]);
2929: fprintf(ficlog,"%.6e ",hess[i][j]);
2930: }
2931: printf("\n");
2932: fprintf(ficlog,"\n");
2933: }
2934:
2935: /* printf("\n#Covariance matrix#\n"); */
2936: /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
2937: /* for (i=1;i<=npar;i++) { */
2938: /* for (j=1;j<=npar;j++) { */
2939: /* printf("%.6e ",matcov[i][j]); */
2940: /* fprintf(ficlog,"%.6e ",matcov[i][j]); */
2941: /* } */
2942: /* printf("\n"); */
2943: /* fprintf(ficlog,"\n"); */
2944: /* } */
2945:
2946: /* Recompute Inverse */
2947: /* for (i=1;i<=npar;i++) */
2948: /* for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
2949: /* ludcmp(a,npar,indx,&pd); */
2950:
2951: /* printf("\n#Hessian matrix recomputed#\n"); */
2952:
2953: /* for (j=1;j<=npar;j++) { */
2954: /* for (i=1;i<=npar;i++) x[i]=0; */
2955: /* x[j]=1; */
2956: /* lubksb(a,npar,indx,x); */
2957: /* for (i=1;i<=npar;i++){ */
2958: /* y[i][j]=x[i]; */
2959: /* printf("%.3e ",y[i][j]); */
2960: /* fprintf(ficlog,"%.3e ",y[i][j]); */
2961: /* } */
2962: /* printf("\n"); */
2963: /* fprintf(ficlog,"\n"); */
2964: /* } */
2965:
2966: /* Verifying the inverse matrix */
2967: #ifdef DEBUGHESS
2968: y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
2969:
2970: printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
2971: fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
2972:
2973: for (j=1;j<=npar;j++) {
2974: for (i=1;i<=npar;i++){
2975: printf("%.2f ",y[i][j]);
2976: fprintf(ficlog,"%.2f ",y[i][j]);
2977: }
2978: printf("\n");
2979: fprintf(ficlog,"\n");
2980: }
2981: #endif
2982:
2983: free_matrix(a,1,npar,1,npar);
2984: free_matrix(y,1,npar,1,npar);
2985: free_vector(x,1,npar);
2986: free_ivector(indx,1,npar);
2987: /* free_matrix(hess,1,npar,1,npar); */
2988:
2989:
2990: }
2991:
2992: /*************** hessian matrix ****************/
2993: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2994: { /* Around values of x, computes the function func and returns the scales delti and hessian */
2995: int i;
2996: int l=1, lmax=20;
2997: double k1,k2, res, fx;
2998: double p2[MAXPARM+1]; /* identical to x */
2999: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
3000: int k=0,kmax=10;
3001: double l1;
3002:
3003: fx=func(x);
3004: for (i=1;i<=npar;i++) p2[i]=x[i];
3005: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
3006: l1=pow(10,l);
3007: delts=delt;
3008: for(k=1 ; k <kmax; k=k+1){
3009: delt = delta*(l1*k);
3010: p2[theta]=x[theta] +delt;
3011: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
3012: p2[theta]=x[theta]-delt;
3013: k2=func(p2)-fx;
3014: /*res= (k1-2.0*fx+k2)/delt/delt; */
3015: res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
3016:
3017: #ifdef DEBUGHESSII
3018: 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);
3019: 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);
3020: #endif
3021: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
3022: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
3023: k=kmax;
3024: }
3025: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
3026: k=kmax; l=lmax*10;
3027: }
3028: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
3029: delts=delt;
3030: }
3031: } /* End loop k */
3032: }
3033: delti[theta]=delts;
3034: return res;
3035:
3036: }
3037:
3038: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
3039: {
3040: int i;
3041: int l=1, lmax=20;
3042: double k1,k2,k3,k4,res,fx;
3043: double p2[MAXPARM+1];
3044: int k, kmax=1;
3045: double v1, v2, cv12, lc1, lc2;
3046:
3047: int firstime=0;
3048:
3049: fx=func(x);
3050: for (k=1; k<=kmax; k=k+10) {
3051: for (i=1;i<=npar;i++) p2[i]=x[i];
3052: p2[thetai]=x[thetai]+delti[thetai]*k;
3053: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3054: k1=func(p2)-fx;
3055:
3056: p2[thetai]=x[thetai]+delti[thetai]*k;
3057: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3058: k2=func(p2)-fx;
3059:
3060: p2[thetai]=x[thetai]-delti[thetai]*k;
3061: p2[thetaj]=x[thetaj]+delti[thetaj]*k;
3062: k3=func(p2)-fx;
3063:
3064: p2[thetai]=x[thetai]-delti[thetai]*k;
3065: p2[thetaj]=x[thetaj]-delti[thetaj]*k;
3066: k4=func(p2)-fx;
3067: res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
3068: if(k1*k2*k3*k4 <0.){
3069: firstime=1;
3070: kmax=kmax+10;
3071: }
3072: if(kmax >=10 || firstime ==1){
3073: printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3074: fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
3075: 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);
3076: 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);
3077: }
3078: #ifdef DEBUGHESSIJ
3079: v1=hess[thetai][thetai];
3080: v2=hess[thetaj][thetaj];
3081: cv12=res;
3082: /* Computing eigen value of Hessian matrix */
3083: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3084: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3085: if ((lc2 <0) || (lc1 <0) ){
3086: printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3087: fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
3088: printf("%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
3089: fprintf(ficlog,"%d %d k=%d, k1=%.12e k2=%.12e k3=%.12e k4=%.12e delti/k=%.12e deltj/k=%.12e, xi-de/k=%.12e xj-de/k=%.12e res=%.12e k1234=%.12e,k1-2=%.12e,k3-4=%.12e\n",thetai,thetaj,k,k1,k2,k3,k4,delti[thetai]/k,delti[thetaj]/k,x[thetai]-delti[thetai]/k,x[thetaj]-delti[thetaj]/k, res,k1-k2-k3+k4,k1-k2,k3-k4);
3090: }
3091: #endif
3092: }
3093: return res;
3094: }
3095:
3096: /* Not done yet: Was supposed to fix if not exactly at the maximum */
3097: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
3098: /* { */
3099: /* int i; */
3100: /* int l=1, lmax=20; */
3101: /* double k1,k2,k3,k4,res,fx; */
3102: /* double p2[MAXPARM+1]; */
3103: /* double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
3104: /* int k=0,kmax=10; */
3105: /* double l1; */
3106:
3107: /* fx=func(x); */
3108: /* for(l=0 ; l <=lmax; l++){ /\* Enlarging the zone around the Maximum *\/ */
3109: /* l1=pow(10,l); */
3110: /* delts=delt; */
3111: /* for(k=1 ; k <kmax; k=k+1){ */
3112: /* delt = delti*(l1*k); */
3113: /* for (i=1;i<=npar;i++) p2[i]=x[i]; */
3114: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3115: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3116: /* k1=func(p2)-fx; */
3117:
3118: /* p2[thetai]=x[thetai]+delti[thetai]/k; */
3119: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3120: /* k2=func(p2)-fx; */
3121:
3122: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3123: /* p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
3124: /* k3=func(p2)-fx; */
3125:
3126: /* p2[thetai]=x[thetai]-delti[thetai]/k; */
3127: /* p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
3128: /* k4=func(p2)-fx; */
3129: /* res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
3130: /* #ifdef DEBUGHESSIJ */
3131: /* 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); */
3132: /* 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); */
3133: /* #endif */
3134: /* if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
3135: /* k=kmax; */
3136: /* } */
3137: /* else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
3138: /* k=kmax; l=lmax*10; */
3139: /* } */
3140: /* else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ */
3141: /* delts=delt; */
3142: /* } */
3143: /* } /\* End loop k *\/ */
3144: /* } */
3145: /* delti[theta]=delts; */
3146: /* return res; */
3147: /* } */
3148:
3149:
3150: /************** Inverse of matrix **************/
3151: void ludcmp(double **a, int n, int *indx, double *d)
3152: {
3153: int i,imax,j,k;
3154: double big,dum,sum,temp;
3155: double *vv;
3156:
3157: vv=vector(1,n);
3158: *d=1.0;
3159: for (i=1;i<=n;i++) {
3160: big=0.0;
3161: for (j=1;j<=n;j++)
3162: if ((temp=fabs(a[i][j])) > big) big=temp;
3163: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
3164: vv[i]=1.0/big;
3165: }
3166: for (j=1;j<=n;j++) {
3167: for (i=1;i<j;i++) {
3168: sum=a[i][j];
3169: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
3170: a[i][j]=sum;
3171: }
3172: big=0.0;
3173: for (i=j;i<=n;i++) {
3174: sum=a[i][j];
3175: for (k=1;k<j;k++)
3176: sum -= a[i][k]*a[k][j];
3177: a[i][j]=sum;
3178: if ( (dum=vv[i]*fabs(sum)) >= big) {
3179: big=dum;
3180: imax=i;
3181: }
3182: }
3183: if (j != imax) {
3184: for (k=1;k<=n;k++) {
3185: dum=a[imax][k];
3186: a[imax][k]=a[j][k];
3187: a[j][k]=dum;
3188: }
3189: *d = -(*d);
3190: vv[imax]=vv[j];
3191: }
3192: indx[j]=imax;
3193: if (a[j][j] == 0.0) a[j][j]=TINY;
3194: if (j != n) {
3195: dum=1.0/(a[j][j]);
3196: for (i=j+1;i<=n;i++) a[i][j] *= dum;
3197: }
3198: }
3199: free_vector(vv,1,n); /* Doesn't work */
3200: ;
3201: }
3202:
3203: void lubksb(double **a, int n, int *indx, double b[])
3204: {
3205: int i,ii=0,ip,j;
3206: double sum;
3207:
3208: for (i=1;i<=n;i++) {
3209: ip=indx[i];
3210: sum=b[ip];
3211: b[ip]=b[i];
3212: if (ii)
3213: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
3214: else if (sum) ii=i;
3215: b[i]=sum;
3216: }
3217: for (i=n;i>=1;i--) {
3218: sum=b[i];
3219: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
3220: b[i]=sum/a[i][i];
3221: }
3222: }
3223:
3224: void pstamp(FILE *fichier)
3225: {
3226: fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
3227: }
3228:
3229: /************ Frequencies ********************/
3230: void freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
3231: int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
3232: int firstpass, int lastpass, int stepm, int weightopt, char model[])
3233: { /* Some frequencies */
3234:
3235: int i, m, jk, j1, bool, z1,j;
3236: int mi; /* Effective wave */
3237: int first;
3238: double ***freq; /* Frequencies */
3239: double *pp, **prop;
3240: double pos,posprop, k2, dateintsum=0,k2cpt=0;
3241: char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
3242: double agebegin, ageend;
3243:
3244: pp=vector(1,nlstate);
3245: prop=matrix(1,nlstate,iagemin,iagemax+3);
3246: strcpy(fileresp,"P_");
3247: strcat(fileresp,fileresu);
3248: /*strcat(fileresphtm,fileresu);*/
3249: if((ficresp=fopen(fileresp,"w"))==NULL) {
3250: printf("Problem with prevalence resultfile: %s\n", fileresp);
3251: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
3252: exit(0);
3253: }
3254:
3255: strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
3256: if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
3257: printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3258: fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
3259: fflush(ficlog);
3260: exit(70);
3261: }
3262: else{
3263: fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3264: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3265: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3266: fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3267: }
3268: fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
3269:
3270: strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
3271: if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
3272: printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3273: fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
3274: fflush(ficlog);
3275: exit(70);
3276: }
3277: else{
3278: fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
3279: <hr size=\"2\" color=\"#EC5E5E\"> \n\
3280: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
3281: fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
3282: }
3283: fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
3284:
3285: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
3286: j1=0;
3287:
3288: j=cptcoveff;
3289: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3290:
3291: first=1;
3292:
3293: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
3294: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
3295: scanf("%d", i);*/
3296: for (i=-5; i<=nlstate+ndeath; i++)
3297: for (jk=-5; jk<=nlstate+ndeath; jk++)
3298: for(m=iagemin; m <= iagemax+3; m++)
3299: freq[i][jk][m]=0;
3300:
3301: for (i=1; i<=nlstate; i++)
3302: for(m=iagemin; m <= iagemax+3; m++)
3303: prop[i][m]=0;
3304:
3305: dateintsum=0;
3306: k2cpt=0;
3307: for (i=1; i<=imx; i++) { /* For each individual i */
3308: bool=1;
3309: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3310: for (z1=1; z1<=cptcoveff; z1++)
3311: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
3312: /* Tests if the value of each of the covariates of i is equal to filter j1 */
3313: bool=0;
3314: /* 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",
3315: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
3316: j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
3317: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
3318: }
3319: } /* cptcovn > 0 */
3320:
3321: if (bool==1){
3322: /* for(m=firstpass; m<=lastpass; m++){ */
3323: for(mi=1; mi<wav[i];mi++){
3324: m=mw[mi][i];
3325: /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
3326: and mw[mi+1][i]. dh depends on stepm. */
3327: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3328: ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
3329: if(m >=firstpass && m <=lastpass){
3330: k2=anint[m][i]+(mint[m][i]/12.);
3331: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
3332: if(agev[m][i]==0) agev[m][i]=iagemax+1; /* All ages equal to 0 are in iagemax+1 */
3333: if(agev[m][i]==1) agev[m][i]=iagemax+2; /* All ages equal to 1 are in iagemax+2 */
3334: if (s[m][i]>0 && s[m][i]<=nlstate) /* If status at wave m is known and a live state */
3335: prop[s[m][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3336: if (m<lastpass) {
3337: /* if(s[m][i]==4 && s[m+1][i]==4) */
3338: /* printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
3339: if(s[m][i]==-1)
3340: printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
3341: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
3342: /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
3343: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
3344: }
3345: }
3346: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
3347: dateintsum=dateintsum+k2;
3348: k2cpt++;
3349: /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
3350: }
3351: /*}*/
3352: } /* end m */
3353: } /* end bool */
3354: } /* end i = 1 to imx */
3355:
3356: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
3357: pstamp(ficresp);
3358: if (cptcovn>0) {
3359: fprintf(ficresp, "\n#********** Variable ");
3360: fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable ");
3361: fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable ");
3362: for (z1=1; z1<=cptcoveff; z1++){
3363: fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3364: fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3365: fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3366: }
3367: fprintf(ficresp, "**********\n#");
3368: fprintf(ficresphtm, "**********</h3>\n");
3369: fprintf(ficresphtmfr, "**********</h3>\n");
3370: fprintf(ficlog, "\n#********** Variable ");
3371: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
3372: fprintf(ficlog, "**********\n");
3373: }
3374: fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
3375: for(i=1; i<=nlstate;i++) {
3376: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
3377: fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
3378: }
3379: fprintf(ficresp, "\n");
3380: fprintf(ficresphtm, "\n");
3381:
3382: /* Header of frequency table by age */
3383: fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
3384: fprintf(ficresphtmfr,"<th>Age</th> ");
3385: for(jk=-1; jk <=nlstate+ndeath; jk++){
3386: for(m=-1; m <=nlstate+ndeath; m++){
3387: if(jk!=0 && m!=0)
3388: fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
3389: }
3390: }
3391: fprintf(ficresphtmfr, "\n");
3392:
3393: /* For each age */
3394: for(i=iagemin; i <= iagemax+3; i++){
3395: fprintf(ficresphtm,"<tr>");
3396: if(i==iagemax+1){
3397: fprintf(ficlog,"1");
3398: fprintf(ficresphtmfr,"<tr><th>0</th> ");
3399: }else if(i==iagemax+2){
3400: fprintf(ficlog,"0");
3401: fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
3402: }else if(i==iagemax+3){
3403: fprintf(ficlog,"Total");
3404: fprintf(ficresphtmfr,"<tr><th>Total</th> ");
3405: }else{
3406: if(first==1){
3407: first=0;
3408: printf("See log file for details...\n");
3409: }
3410: fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
3411: fprintf(ficlog,"Age %d", i);
3412: }
3413: for(jk=1; jk <=nlstate ; jk++){
3414: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
3415: pp[jk] += freq[jk][m][i];
3416: }
3417: for(jk=1; jk <=nlstate ; jk++){
3418: for(m=-1, pos=0; m <=0 ; m++)
3419: pos += freq[jk][m][i];
3420: if(pp[jk]>=1.e-10){
3421: if(first==1){
3422: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3423: }
3424: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
3425: }else{
3426: if(first==1)
3427: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3428: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
3429: }
3430: }
3431:
3432: for(jk=1; jk <=nlstate ; jk++){
3433: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
3434: pp[jk] += freq[jk][m][i];
3435: }
3436: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
3437: pos += pp[jk];
3438: posprop += prop[jk][i];
3439: }
3440: for(jk=1; jk <=nlstate ; jk++){
3441: if(pos>=1.e-5){
3442: if(first==1)
3443: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3444: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
3445: }else{
3446: if(first==1)
3447: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3448: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
3449: }
3450: if( i <= iagemax){
3451: if(pos>=1.e-5){
3452: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3453: fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
3454: /*probs[i][jk][j1]= pp[jk]/pos;*/
3455: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
3456: }
3457: else{
3458: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
3459: fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
3460: }
3461: }
3462: }
3463:
3464: for(jk=-1; jk <=nlstate+ndeath; jk++){
3465: for(m=-1; m <=nlstate+ndeath; m++){
3466: if(freq[jk][m][i] !=0 ) { /* minimizing output */
3467: if(first==1){
3468: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
3469: }
3470: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
3471: }
3472: if(jk!=0 && m!=0)
3473: fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
3474: }
3475: }
3476: fprintf(ficresphtmfr,"</tr>\n ");
3477: if(i <= iagemax){
3478: fprintf(ficresp,"\n");
3479: fprintf(ficresphtm,"</tr>\n");
3480: }
3481: if(first==1)
3482: printf("Others in log...\n");
3483: fprintf(ficlog,"\n");
3484: } /* end loop i */
3485: fprintf(ficresphtm,"</table>\n");
3486: fprintf(ficresphtmfr,"</table>\n");
3487: /*}*/
3488: } /* end j1 */
3489: dateintmean=dateintsum/k2cpt;
3490:
3491: fclose(ficresp);
3492: fclose(ficresphtm);
3493: fclose(ficresphtmfr);
3494: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
3495: free_vector(pp,1,nlstate);
3496: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
3497: /* End of Freq */
3498: }
3499:
3500: /************ Prevalence ********************/
3501: 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)
3502: {
3503: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
3504: in each health status at the date of interview (if between dateprev1 and dateprev2).
3505: We still use firstpass and lastpass as another selection.
3506: */
3507:
3508: int i, m, jk, j1, bool, z1,j;
3509: int mi; /* Effective wave */
3510: int iage;
3511: double agebegin, ageend;
3512:
3513: double **prop;
3514: double posprop;
3515: double y2; /* in fractional years */
3516: int iagemin, iagemax;
3517: int first; /** to stop verbosity which is redirected to log file */
3518:
3519: iagemin= (int) agemin;
3520: iagemax= (int) agemax;
3521: /*pp=vector(1,nlstate);*/
3522: prop=matrix(1,nlstate,iagemin,iagemax+3);
3523: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
3524: j1=0;
3525:
3526: /*j=cptcoveff;*/
3527: if (cptcovn<1) {j=1;ncodemax[1]=1;}
3528:
3529: first=1;
3530: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
3531: for (i=1; i<=nlstate; i++)
3532: for(iage=iagemin; iage <= iagemax+3; iage++)
3533: prop[i][iage]=0.0;
3534:
3535: for (i=1; i<=imx; i++) { /* Each individual */
3536: bool=1;
3537: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
3538: for (z1=1; z1<=cptcoveff; z1++)
3539: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)])
3540: bool=0;
3541: }
3542: if (bool==1) {
3543: /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
3544: for(mi=1; mi<wav[i];mi++){
3545: m=mw[mi][i];
3546: agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
3547: /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
3548: if(m >=firstpass && m <=lastpass){
3549: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
3550: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
3551: if(agev[m][i]==0) agev[m][i]=iagemax+1;
3552: if(agev[m][i]==1) agev[m][i]=iagemax+2;
3553: 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);
3554: if (s[m][i]>0 && s[m][i]<=nlstate) {
3555: /*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]]);*/
3556: prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
3557: prop[s[m][i]][iagemax+3] += weight[i];
3558: } /* end valid statuses */
3559: } /* end selection of dates */
3560: } /* end selection of waves */
3561: } /* end effective waves */
3562: } /* end bool */
3563: }
3564: for(i=iagemin; i <= iagemax+3; i++){
3565: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
3566: posprop += prop[jk][i];
3567: }
3568:
3569: for(jk=1; jk <=nlstate ; jk++){
3570: if( i <= iagemax){
3571: if(posprop>=1.e-5){
3572: probs[i][jk][j1]= prop[jk][i]/posprop;
3573: } else{
3574: if(first==1){
3575: first=0;
3576: 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]);
3577: }
3578: }
3579: }
3580: }/* end jk */
3581: }/* end i */
3582: /*} *//* end i1 */
3583: } /* end j1 */
3584:
3585: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
3586: /*free_vector(pp,1,nlstate);*/
3587: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
3588: } /* End of prevalence */
3589:
3590: /************* Waves Concatenation ***************/
3591:
3592: 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)
3593: {
3594: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
3595: Death is a valid wave (if date is known).
3596: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
3597: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
3598: and mw[mi+1][i]. dh depends on stepm.
3599: */
3600:
3601: int i, mi, m;
3602: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
3603: double sum=0., jmean=0.;*/
3604: int first, firstwo;
3605: int j, k=0,jk, ju, jl;
3606: double sum=0.;
3607: first=0;
3608: firstwo=0;
3609: jmin=100000;
3610: jmax=-1;
3611: jmean=0.;
3612: for(i=1; i<=imx; i++){ /* For simple cases and if state is death */
3613: mi=0;
3614: m=firstpass;
3615: while(s[m][i] <= nlstate){ /* a live state */
3616: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
3617: mw[++mi][i]=m;
3618: if(m >=lastpass)
3619: break;
3620: else
3621: m++;
3622: }/* end while */
3623: if (s[m][i] > nlstate){ /* In a death state */
3624: mi++; /* Death is another wave */
3625: /* if(mi==0) never been interviewed correctly before death */
3626: /* Only death is a correct wave */
3627: mw[mi][i]=m;
3628: }else if (andc[i] != 9999) { /* A death occured after lastpass */
3629: m++;
3630: mi++;
3631: s[m][i]=nlstate+1; /* We are setting the status to the last of non live state */
3632: mw[mi][i]=m;
3633: nbwarn++;
3634: if(firstwo==0){
3635: printf("Warning! Death for individual %ld line=%d occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\nOthers in log file only\n",num[i],i,lastpass,nlstate+1, m);
3636: fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
3637: firstwo=1;
3638: }
3639: if(firstwo==1){
3640: fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred after last wave %d. Since 0.98r4 we considered a status %d at wave %d\n",num[i],i,lastpass,nlstate+1, m);
3641: }
3642: }
3643: wav[i]=mi;
3644: if(mi==0){
3645: nbwarn++;
3646: if(first==0){
3647: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
3648: first=1;
3649: }
3650: if(first==1){
3651: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
3652: }
3653: } /* end mi==0 */
3654: } /* End individuals */
3655: /* wav and mw are no more changed */
3656:
3657:
3658: for(i=1; i<=imx; i++){
3659: for(mi=1; mi<wav[i];mi++){
3660: if (stepm <=0)
3661: dh[mi][i]=1;
3662: else{
3663: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
3664: if (agedc[i] < 2*AGESUP) {
3665: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
3666: if(j==0) j=1; /* Survives at least one month after exam */
3667: else if(j<0){
3668: nberr++;
3669: 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]);
3670: j=1; /* Temporary Dangerous patch */
3671: 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);
3672: 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]);
3673: 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);
3674: }
3675: k=k+1;
3676: if (j >= jmax){
3677: jmax=j;
3678: ijmax=i;
3679: }
3680: if (j <= jmin){
3681: jmin=j;
3682: ijmin=i;
3683: }
3684: sum=sum+j;
3685: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
3686: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
3687: }
3688: }
3689: else{
3690: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
3691: /* 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]); */
3692:
3693: k=k+1;
3694: if (j >= jmax) {
3695: jmax=j;
3696: ijmax=i;
3697: }
3698: else if (j <= jmin){
3699: jmin=j;
3700: ijmin=i;
3701: }
3702: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
3703: /*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]);*/
3704: if(j<0){
3705: nberr++;
3706: 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]);
3707: 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]);
3708: }
3709: sum=sum+j;
3710: }
3711: jk= j/stepm;
3712: jl= j -jk*stepm;
3713: ju= j -(jk+1)*stepm;
3714: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
3715: if(jl==0){
3716: dh[mi][i]=jk;
3717: bh[mi][i]=0;
3718: }else{ /* We want a negative bias in order to only have interpolation ie
3719: * to avoid the price of an extra matrix product in likelihood */
3720: dh[mi][i]=jk+1;
3721: bh[mi][i]=ju;
3722: }
3723: }else{
3724: if(jl <= -ju){
3725: dh[mi][i]=jk;
3726: bh[mi][i]=jl; /* bias is positive if real duration
3727: * is higher than the multiple of stepm and negative otherwise.
3728: */
3729: }
3730: else{
3731: dh[mi][i]=jk+1;
3732: bh[mi][i]=ju;
3733: }
3734: if(dh[mi][i]==0){
3735: dh[mi][i]=1; /* At least one step */
3736: bh[mi][i]=ju; /* At least one step */
3737: /* 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);*/
3738: }
3739: } /* end if mle */
3740: }
3741: } /* end wave */
3742: }
3743: jmean=sum/k;
3744: 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);
3745: 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);
3746: }
3747:
3748: /*********** Tricode ****************************/
3749: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
3750: {
3751: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
3752: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
3753: * Boring subroutine which should only output nbcode[Tvar[j]][k]
3754: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
3755: * nbcode[Tvar[j]][1]=
3756: */
3757:
3758: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
3759: int modmaxcovj=0; /* Modality max of covariates j */
3760: int cptcode=0; /* Modality max of covariates j */
3761: int modmincovj=0; /* Modality min of covariates j */
3762:
3763:
3764: cptcoveff=0;
3765:
3766: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3767:
3768: /* Loop on covariates without age and products */
3769: for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
3770: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3771: for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the
3772: modality of this covariate Vj*/
3773: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3774: * If product of Vn*Vm, still boolean *:
3775: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3776: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3777: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3778: modality of the nth covariate of individual i. */
3779: if (ij > modmaxcovj)
3780: modmaxcovj=ij;
3781: else if (ij < modmincovj)
3782: modmincovj=ij;
3783: if ((ij < -1) && (ij > NCOVMAX)){
3784: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3785: exit(1);
3786: }else
3787: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3788: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3789: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3790: /* getting the maximum value of the modality of the covariate
3791: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3792: female is 1, then modmaxcovj=1.*/
3793: } /* end for loop on individuals i */
3794: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3795: fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3796: cptcode=modmaxcovj;
3797: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3798: /*for (i=0; i<=cptcode; i++) {*/
3799: for (k=modmincovj; k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
3800: printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3801: fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
3802: if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
3803: if( k != -1){
3804: ncodemax[j]++; /* ncodemax[j]= Number of modalities of the j th
3805: covariate for which somebody answered excluding
3806: undefined. Usually 2: 0 and 1. */
3807: }
3808: ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
3809: covariate for which somebody answered including
3810: undefined. Usually 3: -1, 0 and 1. */
3811: }
3812: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3813: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3814: } /* Ndum[-1] number of undefined modalities */
3815:
3816: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3817: /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7.
3818: If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
3819: modmincovj=3; modmaxcovj = 7;
3820: There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
3821: which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
3822: defining two dummy variables: variables V1_1 and V1_2.
3823: nbcode[Tvar[j]][ij]=k;
3824: nbcode[Tvar[j]][1]=0;
3825: nbcode[Tvar[j]][2]=1;
3826: nbcode[Tvar[j]][3]=2;
3827: To be continued (not working yet).
3828: */
3829: ij=0; /* ij is similar to i but can jump over null modalities */
3830: 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*/
3831: if (Ndum[i] == 0) { /* If nobody responded to this modality k */
3832: break;
3833: }
3834: ij++;
3835: 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.*/
3836: cptcode = ij; /* New max modality for covar j */
3837: } /* end of loop on modality i=-1 to 1 or more */
3838:
3839: /* for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
3840: /* /\*recode from 0 *\/ */
3841: /* k is a modality. If we have model=V1+V1*sex */
3842: /* then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3843: /* But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
3844: /* } */
3845: /* /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
3846: /* if (ij > ncodemax[j]) { */
3847: /* printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3848: /* fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
3849: /* break; */
3850: /* } */
3851: /* } /\* end of loop on modality k *\/ */
3852: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3853:
3854: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3855:
3856: for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */
3857: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3858: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3859: Ndum[ij]++; /* Might be supersed V1 + V1*age */
3860: }
3861:
3862: ij=0;
3863: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3864: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3865: if((Ndum[i]!=0) && (i<=ncovcol)){
3866: ij++;
3867: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3868: Tvaraff[ij]=i; /*For printing (unclear) */
3869: }else{
3870: /* Tvaraff[ij]=0; */
3871: }
3872: }
3873: /* ij--; */
3874: cptcoveff=ij; /*Number of total covariates*/
3875:
3876: }
3877:
3878:
3879: /*********** Health Expectancies ****************/
3880:
3881: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3882:
3883: {
3884: /* Health expectancies, no variances */
3885: int i, j, nhstepm, hstepm, h, nstepm;
3886: int nhstepma, nstepma; /* Decreasing with age */
3887: double age, agelim, hf;
3888: double ***p3mat;
3889: double eip;
3890:
3891: pstamp(ficreseij);
3892: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3893: fprintf(ficreseij,"# Age");
3894: for(i=1; i<=nlstate;i++){
3895: for(j=1; j<=nlstate;j++){
3896: fprintf(ficreseij," e%1d%1d ",i,j);
3897: }
3898: fprintf(ficreseij," e%1d. ",i);
3899: }
3900: fprintf(ficreseij,"\n");
3901:
3902:
3903: if(estepm < stepm){
3904: printf ("Problem %d lower than %d\n",estepm, stepm);
3905: }
3906: else hstepm=estepm;
3907: /* We compute the life expectancy from trapezoids spaced every estepm months
3908: * This is mainly to measure the difference between two models: for example
3909: * if stepm=24 months pijx are given only every 2 years and by summing them
3910: * we are calculating an estimate of the Life Expectancy assuming a linear
3911: * progression in between and thus overestimating or underestimating according
3912: * to the curvature of the survival function. If, for the same date, we
3913: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3914: * to compare the new estimate of Life expectancy with the same linear
3915: * hypothesis. A more precise result, taking into account a more precise
3916: * curvature will be obtained if estepm is as small as stepm. */
3917:
3918: /* For example we decided to compute the life expectancy with the smallest unit */
3919: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3920: nhstepm is the number of hstepm from age to agelim
3921: nstepm is the number of stepm from age to agelin.
3922: Look at hpijx to understand the reason of that which relies in memory size
3923: and note for a fixed period like estepm months */
3924: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3925: survival function given by stepm (the optimization length). Unfortunately it
3926: means that if the survival funtion is printed only each two years of age and if
3927: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3928: results. So we changed our mind and took the option of the best precision.
3929: */
3930: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3931:
3932: agelim=AGESUP;
3933: /* If stepm=6 months */
3934: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3935: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3936:
3937: /* nhstepm age range expressed in number of stepm */
3938: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3939: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3940: /* if (stepm >= YEARM) hstepm=1;*/
3941: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3942: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3943:
3944: for (age=bage; age<=fage; age ++){
3945: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3946: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3947: /* if (stepm >= YEARM) hstepm=1;*/
3948: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3949:
3950: /* If stepm=6 months */
3951: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3952: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3953:
3954: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3955:
3956: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3957:
3958: printf("%d|",(int)age);fflush(stdout);
3959: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3960:
3961: /* Computing expectancies */
3962: for(i=1; i<=nlstate;i++)
3963: for(j=1; j<=nlstate;j++)
3964: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3965: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3966:
3967: /* 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]);*/
3968:
3969: }
3970:
3971: fprintf(ficreseij,"%3.0f",age );
3972: for(i=1; i<=nlstate;i++){
3973: eip=0;
3974: for(j=1; j<=nlstate;j++){
3975: eip +=eij[i][j][(int)age];
3976: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3977: }
3978: fprintf(ficreseij,"%9.4f", eip );
3979: }
3980: fprintf(ficreseij,"\n");
3981:
3982: }
3983: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3984: printf("\n");
3985: fprintf(ficlog,"\n");
3986:
3987: }
3988:
3989: 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[] )
3990:
3991: {
3992: /* Covariances of health expectancies eij and of total life expectancies according
3993: to initial status i, ei. .
3994: */
3995: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3996: int nhstepma, nstepma; /* Decreasing with age */
3997: double age, agelim, hf;
3998: double ***p3matp, ***p3matm, ***varhe;
3999: double **dnewm,**doldm;
4000: double *xp, *xm;
4001: double **gp, **gm;
4002: double ***gradg, ***trgradg;
4003: int theta;
4004:
4005: double eip, vip;
4006:
4007: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
4008: xp=vector(1,npar);
4009: xm=vector(1,npar);
4010: dnewm=matrix(1,nlstate*nlstate,1,npar);
4011: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
4012:
4013: pstamp(ficresstdeij);
4014: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
4015: fprintf(ficresstdeij,"# Age");
4016: for(i=1; i<=nlstate;i++){
4017: for(j=1; j<=nlstate;j++)
4018: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
4019: fprintf(ficresstdeij," e%1d. ",i);
4020: }
4021: fprintf(ficresstdeij,"\n");
4022:
4023: pstamp(ficrescveij);
4024: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
4025: fprintf(ficrescveij,"# Age");
4026: for(i=1; i<=nlstate;i++)
4027: for(j=1; j<=nlstate;j++){
4028: cptj= (j-1)*nlstate+i;
4029: for(i2=1; i2<=nlstate;i2++)
4030: for(j2=1; j2<=nlstate;j2++){
4031: cptj2= (j2-1)*nlstate+i2;
4032: if(cptj2 <= cptj)
4033: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
4034: }
4035: }
4036: fprintf(ficrescveij,"\n");
4037:
4038: if(estepm < stepm){
4039: printf ("Problem %d lower than %d\n",estepm, stepm);
4040: }
4041: else hstepm=estepm;
4042: /* We compute the life expectancy from trapezoids spaced every estepm months
4043: * This is mainly to measure the difference between two models: for example
4044: * if stepm=24 months pijx are given only every 2 years and by summing them
4045: * we are calculating an estimate of the Life Expectancy assuming a linear
4046: * progression in between and thus overestimating or underestimating according
4047: * to the curvature of the survival function. If, for the same date, we
4048: * estimate the model with stepm=1 month, we can keep estepm to 24 months
4049: * to compare the new estimate of Life expectancy with the same linear
4050: * hypothesis. A more precise result, taking into account a more precise
4051: * curvature will be obtained if estepm is as small as stepm. */
4052:
4053: /* For example we decided to compute the life expectancy with the smallest unit */
4054: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4055: nhstepm is the number of hstepm from age to agelim
4056: nstepm is the number of stepm from age to agelin.
4057: Look at hpijx to understand the reason of that which relies in memory size
4058: and note for a fixed period like estepm months */
4059: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
4060: survival function given by stepm (the optimization length). Unfortunately it
4061: means that if the survival funtion is printed only each two years of age and if
4062: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4063: results. So we changed our mind and took the option of the best precision.
4064: */
4065: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4066:
4067: /* If stepm=6 months */
4068: /* nhstepm age range expressed in number of stepm */
4069: agelim=AGESUP;
4070: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
4071: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4072: /* if (stepm >= YEARM) hstepm=1;*/
4073: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4074:
4075: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4076: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4077: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
4078: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
4079: gp=matrix(0,nhstepm,1,nlstate*nlstate);
4080: gm=matrix(0,nhstepm,1,nlstate*nlstate);
4081:
4082: for (age=bage; age<=fage; age ++){
4083: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
4084: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
4085: /* if (stepm >= YEARM) hstepm=1;*/
4086: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
4087:
4088: /* If stepm=6 months */
4089: /* Computed by stepm unit matrices, product of hstepma matrices, stored
4090: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
4091:
4092: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4093:
4094: /* Computing Variances of health expectancies */
4095: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
4096: decrease memory allocation */
4097: for(theta=1; theta <=npar; theta++){
4098: for(i=1; i<=npar; i++){
4099: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4100: xm[i] = x[i] - (i==theta ?delti[theta]:0);
4101: }
4102: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
4103: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
4104:
4105: for(j=1; j<= nlstate; j++){
4106: for(i=1; i<=nlstate; i++){
4107: for(h=0; h<=nhstepm-1; h++){
4108: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
4109: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
4110: }
4111: }
4112: }
4113:
4114: for(ij=1; ij<= nlstate*nlstate; ij++)
4115: for(h=0; h<=nhstepm-1; h++){
4116: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
4117: }
4118: }/* End theta */
4119:
4120:
4121: for(h=0; h<=nhstepm-1; h++)
4122: for(j=1; j<=nlstate*nlstate;j++)
4123: for(theta=1; theta <=npar; theta++)
4124: trgradg[h][j][theta]=gradg[h][theta][j];
4125:
4126:
4127: for(ij=1;ij<=nlstate*nlstate;ij++)
4128: for(ji=1;ji<=nlstate*nlstate;ji++)
4129: varhe[ij][ji][(int)age] =0.;
4130:
4131: printf("%d|",(int)age);fflush(stdout);
4132: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
4133: for(h=0;h<=nhstepm-1;h++){
4134: for(k=0;k<=nhstepm-1;k++){
4135: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
4136: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
4137: for(ij=1;ij<=nlstate*nlstate;ij++)
4138: for(ji=1;ji<=nlstate*nlstate;ji++)
4139: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
4140: }
4141: }
4142:
4143: /* Computing expectancies */
4144: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
4145: for(i=1; i<=nlstate;i++)
4146: for(j=1; j<=nlstate;j++)
4147: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
4148: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
4149:
4150: /* 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]);*/
4151:
4152: }
4153:
4154: fprintf(ficresstdeij,"%3.0f",age );
4155: for(i=1; i<=nlstate;i++){
4156: eip=0.;
4157: vip=0.;
4158: for(j=1; j<=nlstate;j++){
4159: eip += eij[i][j][(int)age];
4160: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
4161: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
4162: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
4163: }
4164: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
4165: }
4166: fprintf(ficresstdeij,"\n");
4167:
4168: fprintf(ficrescveij,"%3.0f",age );
4169: for(i=1; i<=nlstate;i++)
4170: for(j=1; j<=nlstate;j++){
4171: cptj= (j-1)*nlstate+i;
4172: for(i2=1; i2<=nlstate;i2++)
4173: for(j2=1; j2<=nlstate;j2++){
4174: cptj2= (j2-1)*nlstate+i2;
4175: if(cptj2 <= cptj)
4176: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
4177: }
4178: }
4179: fprintf(ficrescveij,"\n");
4180:
4181: }
4182: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
4183: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
4184: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
4185: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
4186: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4187: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4188: printf("\n");
4189: fprintf(ficlog,"\n");
4190:
4191: free_vector(xm,1,npar);
4192: free_vector(xp,1,npar);
4193: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
4194: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
4195: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
4196: }
4197:
4198: /************ Variance ******************/
4199: 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[])
4200: {
4201: /* Variance of health expectancies */
4202: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
4203: /* double **newm;*/
4204: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
4205:
4206: int movingaverage();
4207: double **dnewm,**doldm;
4208: double **dnewmp,**doldmp;
4209: int i, j, nhstepm, hstepm, h, nstepm ;
4210: int k;
4211: double *xp;
4212: double **gp, **gm; /* for var eij */
4213: double ***gradg, ***trgradg; /*for var eij */
4214: double **gradgp, **trgradgp; /* for var p point j */
4215: double *gpp, *gmp; /* for var p point j */
4216: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
4217: double ***p3mat;
4218: double age,agelim, hf;
4219: double ***mobaverage;
4220: int theta;
4221: char digit[4];
4222: char digitp[25];
4223:
4224: char fileresprobmorprev[FILENAMELENGTH];
4225:
4226: if(popbased==1){
4227: if(mobilav!=0)
4228: strcpy(digitp,"-POPULBASED-MOBILAV_");
4229: else strcpy(digitp,"-POPULBASED-NOMOBIL_");
4230: }
4231: else
4232: strcpy(digitp,"-STABLBASED_");
4233:
4234: if (mobilav!=0) {
4235: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4236: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
4237: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4238: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4239: }
4240: }
4241:
4242: strcpy(fileresprobmorprev,"PRMORPREV-");
4243: sprintf(digit,"%-d",ij);
4244: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
4245: strcat(fileresprobmorprev,digit); /* Tvar to be done */
4246: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
4247: strcat(fileresprobmorprev,fileresu);
4248: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
4249: printf("Problem with resultfile: %s\n", fileresprobmorprev);
4250: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
4251: }
4252: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4253: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
4254: pstamp(ficresprobmorprev);
4255: 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);
4256: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
4257: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4258: fprintf(ficresprobmorprev," p.%-d SE",j);
4259: for(i=1; i<=nlstate;i++)
4260: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
4261: }
4262: fprintf(ficresprobmorprev,"\n");
4263:
4264: fprintf(ficgp,"\n# Routine varevsij");
4265: fprintf(ficgp,"\nunset title \n");
4266: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
4267: 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");
4268: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
4269: /* } */
4270: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4271: pstamp(ficresvij);
4272: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
4273: if(popbased==1)
4274: 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);
4275: else
4276: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
4277: fprintf(ficresvij,"# Age");
4278: for(i=1; i<=nlstate;i++)
4279: for(j=1; j<=nlstate;j++)
4280: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
4281: fprintf(ficresvij,"\n");
4282:
4283: xp=vector(1,npar);
4284: dnewm=matrix(1,nlstate,1,npar);
4285: doldm=matrix(1,nlstate,1,nlstate);
4286: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
4287: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4288:
4289: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
4290: gpp=vector(nlstate+1,nlstate+ndeath);
4291: gmp=vector(nlstate+1,nlstate+ndeath);
4292: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4293:
4294: if(estepm < stepm){
4295: printf ("Problem %d lower than %d\n",estepm, stepm);
4296: }
4297: else hstepm=estepm;
4298: /* For example we decided to compute the life expectancy with the smallest unit */
4299: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
4300: nhstepm is the number of hstepm from age to agelim
4301: nstepm is the number of stepm from age to agelim.
4302: Look at function hpijx to understand why because of memory size limitations,
4303: we decided (b) to get a life expectancy respecting the most precise curvature of the
4304: survival function given by stepm (the optimization length). Unfortunately it
4305: means that if the survival funtion is printed every two years of age and if
4306: you sum them up and add 1 year (area under the trapezoids) you won't get the same
4307: results. So we changed our mind and took the option of the best precision.
4308: */
4309: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
4310: agelim = AGESUP;
4311: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4312: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4313: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
4314: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4315: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
4316: gp=matrix(0,nhstepm,1,nlstate);
4317: gm=matrix(0,nhstepm,1,nlstate);
4318:
4319:
4320: for(theta=1; theta <=npar; theta++){
4321: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
4322: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4323: }
4324:
4325: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4326:
4327: if (popbased==1) {
4328: if(mobilav ==0){
4329: for(i=1; i<=nlstate;i++)
4330: prlim[i][i]=probs[(int)age][i][ij];
4331: }else{ /* mobilav */
4332: for(i=1; i<=nlstate;i++)
4333: prlim[i][i]=mobaverage[(int)age][i][ij];
4334: }
4335: }
4336:
4337: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); /* Returns p3mat[i][j][h] for h=1 to nhstepm */
4338: for(j=1; j<= nlstate; j++){
4339: for(h=0; h<=nhstepm; h++){
4340: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
4341: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
4342: }
4343: }
4344: /* Next for computing probability of death (h=1 means
4345: computed over hstepm matrices product = hstepm*stepm months)
4346: as a weighted average of prlim.
4347: */
4348: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4349: for(i=1,gpp[j]=0.; i<= nlstate; i++)
4350: gpp[j] += prlim[i][i]*p3mat[i][j][1];
4351: }
4352: /* end probability of death */
4353:
4354: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
4355: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4356:
4357: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
4358:
4359: if (popbased==1) {
4360: if(mobilav ==0){
4361: for(i=1; i<=nlstate;i++)
4362: prlim[i][i]=probs[(int)age][i][ij];
4363: }else{ /* mobilav */
4364: for(i=1; i<=nlstate;i++)
4365: prlim[i][i]=mobaverage[(int)age][i][ij];
4366: }
4367: }
4368:
4369: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
4370:
4371: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
4372: for(h=0; h<=nhstepm; h++){
4373: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
4374: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
4375: }
4376: }
4377: /* This for computing probability of death (h=1 means
4378: computed over hstepm matrices product = hstepm*stepm months)
4379: as a weighted average of prlim.
4380: */
4381: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4382: for(i=1,gmp[j]=0.; i<= nlstate; i++)
4383: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4384: }
4385: /* end probability of death */
4386:
4387: for(j=1; j<= nlstate; j++) /* vareij */
4388: for(h=0; h<=nhstepm; h++){
4389: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
4390: }
4391:
4392: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
4393: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
4394: }
4395:
4396: } /* End theta */
4397:
4398: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
4399:
4400: for(h=0; h<=nhstepm; h++) /* veij */
4401: for(j=1; j<=nlstate;j++)
4402: for(theta=1; theta <=npar; theta++)
4403: trgradg[h][j][theta]=gradg[h][theta][j];
4404:
4405: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
4406: for(theta=1; theta <=npar; theta++)
4407: trgradgp[j][theta]=gradgp[theta][j];
4408:
4409:
4410: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
4411: for(i=1;i<=nlstate;i++)
4412: for(j=1;j<=nlstate;j++)
4413: vareij[i][j][(int)age] =0.;
4414:
4415: for(h=0;h<=nhstepm;h++){
4416: for(k=0;k<=nhstepm;k++){
4417: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
4418: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
4419: for(i=1;i<=nlstate;i++)
4420: for(j=1;j<=nlstate;j++)
4421: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
4422: }
4423: }
4424:
4425: /* pptj */
4426: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
4427: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
4428: for(j=nlstate+1;j<=nlstate+ndeath;j++)
4429: for(i=nlstate+1;i<=nlstate+ndeath;i++)
4430: varppt[j][i]=doldmp[j][i];
4431: /* end ppptj */
4432: /* x centered again */
4433:
4434: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
4435:
4436: if (popbased==1) {
4437: if(mobilav ==0){
4438: for(i=1; i<=nlstate;i++)
4439: prlim[i][i]=probs[(int)age][i][ij];
4440: }else{ /* mobilav */
4441: for(i=1; i<=nlstate;i++)
4442: prlim[i][i]=mobaverage[(int)age][i][ij];
4443: }
4444: }
4445:
4446: /* This for computing probability of death (h=1 means
4447: computed over hstepm (estepm) matrices product = hstepm*stepm months)
4448: as a weighted average of prlim.
4449: */
4450: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
4451: for(j=nlstate+1;j<=nlstate+ndeath;j++){
4452: for(i=1,gmp[j]=0.;i<= nlstate; i++)
4453: gmp[j] += prlim[i][i]*p3mat[i][j][1];
4454: }
4455: /* end probability of death */
4456:
4457: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
4458: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
4459: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
4460: for(i=1; i<=nlstate;i++){
4461: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
4462: }
4463: }
4464: fprintf(ficresprobmorprev,"\n");
4465:
4466: fprintf(ficresvij,"%.0f ",age );
4467: for(i=1; i<=nlstate;i++)
4468: for(j=1; j<=nlstate;j++){
4469: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
4470: }
4471: fprintf(ficresvij,"\n");
4472: free_matrix(gp,0,nhstepm,1,nlstate);
4473: free_matrix(gm,0,nhstepm,1,nlstate);
4474: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
4475: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
4476: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4477: } /* End age */
4478: free_vector(gpp,nlstate+1,nlstate+ndeath);
4479: free_vector(gmp,nlstate+1,nlstate+ndeath);
4480: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
4481: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
4482: /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
4483: fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
4484: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
4485: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
4486: fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4487: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
4488: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
4489: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
4490: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
4491: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
4492: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
4493: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
4494: 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);
4495: /* 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);
4496: */
4497: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
4498: fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
4499:
4500: free_vector(xp,1,npar);
4501: free_matrix(doldm,1,nlstate,1,nlstate);
4502: free_matrix(dnewm,1,nlstate,1,npar);
4503: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4504: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
4505: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
4506: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4507: fclose(ficresprobmorprev);
4508: fflush(ficgp);
4509: fflush(fichtm);
4510: } /* end varevsij */
4511:
4512: /************ Variance of prevlim ******************/
4513: 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[])
4514: {
4515: /* Variance of prevalence limit for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
4516: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
4517:
4518: double **dnewm,**doldm;
4519: int i, j, nhstepm, hstepm;
4520: double *xp;
4521: double *gp, *gm;
4522: double **gradg, **trgradg;
4523: double **mgm, **mgp;
4524: double age,agelim;
4525: int theta;
4526:
4527: pstamp(ficresvpl);
4528: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
4529: fprintf(ficresvpl,"# Age");
4530: for(i=1; i<=nlstate;i++)
4531: fprintf(ficresvpl," %1d-%1d",i,i);
4532: fprintf(ficresvpl,"\n");
4533:
4534: xp=vector(1,npar);
4535: dnewm=matrix(1,nlstate,1,npar);
4536: doldm=matrix(1,nlstate,1,nlstate);
4537:
4538: hstepm=1*YEARM; /* Every year of age */
4539: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
4540: agelim = AGESUP;
4541: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
4542: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
4543: if (stepm >= YEARM) hstepm=1;
4544: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
4545: gradg=matrix(1,npar,1,nlstate);
4546: mgp=matrix(1,npar,1,nlstate);
4547: mgm=matrix(1,npar,1,nlstate);
4548: gp=vector(1,nlstate);
4549: gm=vector(1,nlstate);
4550:
4551: for(theta=1; theta <=npar; theta++){
4552: for(i=1; i<=npar; i++){ /* Computes gradient */
4553: xp[i] = x[i] + (i==theta ?delti[theta]:0);
4554: }
4555: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4556: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4557: else
4558: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4559: for(i=1;i<=nlstate;i++){
4560: gp[i] = prlim[i][i];
4561: mgp[theta][i] = prlim[i][i];
4562: }
4563: for(i=1; i<=npar; i++) /* Computes gradient */
4564: xp[i] = x[i] - (i==theta ?delti[theta]:0);
4565: if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
4566: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4567: else
4568: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
4569: for(i=1;i<=nlstate;i++){
4570: gm[i] = prlim[i][i];
4571: mgm[theta][i] = prlim[i][i];
4572: }
4573: for(i=1;i<=nlstate;i++)
4574: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
4575: /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
4576: } /* End theta */
4577:
4578: trgradg =matrix(1,nlstate,1,npar);
4579:
4580: for(j=1; j<=nlstate;j++)
4581: for(theta=1; theta <=npar; theta++)
4582: trgradg[j][theta]=gradg[theta][j];
4583: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4584: /* printf("\nmgm mgp %d ",(int)age); */
4585: /* for(j=1; j<=nlstate;j++){ */
4586: /* printf(" %d ",j); */
4587: /* for(theta=1; theta <=npar; theta++) */
4588: /* printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
4589: /* printf("\n "); */
4590: /* } */
4591: /* } */
4592: /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
4593: /* printf("\n gradg %d ",(int)age); */
4594: /* for(j=1; j<=nlstate;j++){ */
4595: /* printf("%d ",j); */
4596: /* for(theta=1; theta <=npar; theta++) */
4597: /* printf("%d %lf ",theta,gradg[theta][j]); */
4598: /* printf("\n "); */
4599: /* } */
4600: /* } */
4601:
4602: for(i=1;i<=nlstate;i++)
4603: varpl[i][(int)age] =0.;
4604: if((int)age==79 ||(int)age== 80 ||(int)age== 81){
4605: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4606: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4607: }else{
4608: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
4609: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
4610: }
4611: for(i=1;i<=nlstate;i++)
4612: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
4613:
4614: fprintf(ficresvpl,"%.0f ",age );
4615: for(i=1; i<=nlstate;i++)
4616: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
4617: fprintf(ficresvpl,"\n");
4618: free_vector(gp,1,nlstate);
4619: free_vector(gm,1,nlstate);
4620: free_matrix(mgm,1,npar,1,nlstate);
4621: free_matrix(mgp,1,npar,1,nlstate);
4622: free_matrix(gradg,1,npar,1,nlstate);
4623: free_matrix(trgradg,1,nlstate,1,npar);
4624: } /* End age */
4625:
4626: free_vector(xp,1,npar);
4627: free_matrix(doldm,1,nlstate,1,npar);
4628: free_matrix(dnewm,1,nlstate,1,nlstate);
4629:
4630: }
4631:
4632: /************ Variance of one-step probabilities ******************/
4633: 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[])
4634: {
4635: int i, j=0, k1, l1, tj;
4636: int k2, l2, j1, z1;
4637: int k=0, l;
4638: int first=1, first1, first2;
4639: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
4640: double **dnewm,**doldm;
4641: double *xp;
4642: double *gp, *gm;
4643: double **gradg, **trgradg;
4644: double **mu;
4645: double age, cov[NCOVMAX+1];
4646: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
4647: int theta;
4648: char fileresprob[FILENAMELENGTH];
4649: char fileresprobcov[FILENAMELENGTH];
4650: char fileresprobcor[FILENAMELENGTH];
4651: double ***varpij;
4652:
4653: strcpy(fileresprob,"PROB_");
4654: strcat(fileresprob,fileres);
4655: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
4656: printf("Problem with resultfile: %s\n", fileresprob);
4657: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
4658: }
4659: strcpy(fileresprobcov,"PROBCOV_");
4660: strcat(fileresprobcov,fileresu);
4661: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
4662: printf("Problem with resultfile: %s\n", fileresprobcov);
4663: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
4664: }
4665: strcpy(fileresprobcor,"PROBCOR_");
4666: strcat(fileresprobcor,fileresu);
4667: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
4668: printf("Problem with resultfile: %s\n", fileresprobcor);
4669: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
4670: }
4671: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4672: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
4673: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4674: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
4675: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4676: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
4677: pstamp(ficresprob);
4678: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
4679: fprintf(ficresprob,"# Age");
4680: pstamp(ficresprobcov);
4681: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
4682: fprintf(ficresprobcov,"# Age");
4683: pstamp(ficresprobcor);
4684: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
4685: fprintf(ficresprobcor,"# Age");
4686:
4687:
4688: for(i=1; i<=nlstate;i++)
4689: for(j=1; j<=(nlstate+ndeath);j++){
4690: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
4691: fprintf(ficresprobcov," p%1d-%1d ",i,j);
4692: fprintf(ficresprobcor," p%1d-%1d ",i,j);
4693: }
4694: /* fprintf(ficresprob,"\n");
4695: fprintf(ficresprobcov,"\n");
4696: fprintf(ficresprobcor,"\n");
4697: */
4698: xp=vector(1,npar);
4699: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4700: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4701: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
4702: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
4703: first=1;
4704: fprintf(ficgp,"\n# Routine varprob");
4705: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
4706: fprintf(fichtm,"\n");
4707:
4708: 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);
4709: 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);
4710: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
4711: and drawn. It helps understanding how is the covariance between two incidences.\
4712: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
4713: 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. \
4714: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
4715: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
4716: standard deviations wide on each axis. <br>\
4717: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
4718: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
4719: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
4720:
4721: cov[1]=1;
4722: /* tj=cptcoveff; */
4723: tj = (int) pow(2,cptcoveff);
4724: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
4725: j1=0;
4726: for(j1=1; j1<=tj;j1++){
4727: /*for(i1=1; i1<=ncodemax[t];i1++){ */
4728: /*j1++;*/
4729: if (cptcovn>0) {
4730: fprintf(ficresprob, "\n#********** Variable ");
4731: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4732: fprintf(ficresprob, "**********\n#\n");
4733: fprintf(ficresprobcov, "\n#********** Variable ");
4734: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4735: fprintf(ficresprobcov, "**********\n#\n");
4736:
4737: fprintf(ficgp, "\n#********** Variable ");
4738: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4739: fprintf(ficgp, "**********\n#\n");
4740:
4741:
4742: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
4743: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4744: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
4745:
4746: fprintf(ficresprobcor, "\n#********** Variable ");
4747: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
4748: fprintf(ficresprobcor, "**********\n#");
4749: }
4750:
4751: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
4752: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
4753: gp=vector(1,(nlstate)*(nlstate+ndeath));
4754: gm=vector(1,(nlstate)*(nlstate+ndeath));
4755: for (age=bage; age<=fage; age ++){
4756: cov[2]=age;
4757: if(nagesqr==1)
4758: cov[3]= age*age;
4759: for (k=1; k<=cptcovn;k++) {
4760: cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
4761: /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
4762: * 1 1 1 1 1
4763: * 2 2 1 1 1
4764: * 3 1 2 1 1
4765: */
4766: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
4767: }
4768: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
4769: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
4770: for (k=1; k<=cptcovprod;k++)
4771: cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
4772:
4773:
4774: for(theta=1; theta <=npar; theta++){
4775: for(i=1; i<=npar; i++)
4776: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
4777:
4778: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4779:
4780: k=0;
4781: for(i=1; i<= (nlstate); i++){
4782: for(j=1; j<=(nlstate+ndeath);j++){
4783: k=k+1;
4784: gp[k]=pmmij[i][j];
4785: }
4786: }
4787:
4788: for(i=1; i<=npar; i++)
4789: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
4790:
4791: pmij(pmmij,cov,ncovmodel,xp,nlstate);
4792: k=0;
4793: for(i=1; i<=(nlstate); i++){
4794: for(j=1; j<=(nlstate+ndeath);j++){
4795: k=k+1;
4796: gm[k]=pmmij[i][j];
4797: }
4798: }
4799:
4800: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
4801: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
4802: }
4803:
4804: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
4805: for(theta=1; theta <=npar; theta++)
4806: trgradg[j][theta]=gradg[theta][j];
4807:
4808: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
4809: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
4810:
4811: pmij(pmmij,cov,ncovmodel,x,nlstate);
4812:
4813: k=0;
4814: for(i=1; i<=(nlstate); i++){
4815: for(j=1; j<=(nlstate+ndeath);j++){
4816: k=k+1;
4817: mu[k][(int) age]=pmmij[i][j];
4818: }
4819: }
4820: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
4821: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
4822: varpij[i][j][(int)age] = doldm[i][j];
4823:
4824: /*printf("\n%d ",(int)age);
4825: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4826: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4827: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
4828: }*/
4829:
4830: fprintf(ficresprob,"\n%d ",(int)age);
4831: fprintf(ficresprobcov,"\n%d ",(int)age);
4832: fprintf(ficresprobcor,"\n%d ",(int)age);
4833:
4834: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4835: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4836: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4837: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4838: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4839: }
4840: i=0;
4841: for (k=1; k<=(nlstate);k++){
4842: for (l=1; l<=(nlstate+ndeath);l++){
4843: i++;
4844: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4845: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4846: for (j=1; j<=i;j++){
4847: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4848: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4849: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4850: }
4851: }
4852: }/* end of loop for state */
4853: } /* end of loop for age */
4854: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4855: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4856: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4857: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4858:
4859: /* Confidence intervalle of pij */
4860: /*
4861: fprintf(ficgp,"\nunset parametric;unset label");
4862: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4863: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4864: 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);
4865: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4866: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4867: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4868: */
4869:
4870: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4871: first1=1;first2=2;
4872: for (k2=1; k2<=(nlstate);k2++){
4873: for (l2=1; l2<=(nlstate+ndeath);l2++){
4874: if(l2==k2) continue;
4875: j=(k2-1)*(nlstate+ndeath)+l2;
4876: for (k1=1; k1<=(nlstate);k1++){
4877: for (l1=1; l1<=(nlstate+ndeath);l1++){
4878: if(l1==k1) continue;
4879: i=(k1-1)*(nlstate+ndeath)+l1;
4880: if(i<=j) continue;
4881: for (age=bage; age<=fage; age ++){
4882: if ((int)age %5==0){
4883: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4884: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4885: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4886: mu1=mu[i][(int) age]/stepm*YEARM ;
4887: mu2=mu[j][(int) age]/stepm*YEARM;
4888: c12=cv12/sqrt(v1*v2);
4889: /* Computing eigen value of matrix of covariance */
4890: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4891: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4892: if ((lc2 <0) || (lc1 <0) ){
4893: if(first2==1){
4894: first1=0;
4895: 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);
4896: }
4897: 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);
4898: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4899: /* lc2=fabs(lc2); */
4900: }
4901:
4902: /* Eigen vectors */
4903: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4904: /*v21=sqrt(1.-v11*v11); *//* error */
4905: v21=(lc1-v1)/cv12*v11;
4906: v12=-v21;
4907: v22=v11;
4908: tnalp=v21/v11;
4909: if(first1==1){
4910: first1=0;
4911: 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);
4912: }
4913: 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);
4914: /*printf(fignu*/
4915: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4916: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4917: if(first==1){
4918: first=0;
4919: fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
4920: fprintf(ficgp,"\nset parametric;unset label");
4921: 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);
4922: fprintf(ficgp,"\nset ter svg size 640, 480");
4923: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4924: :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
4925: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
4926: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
4927: subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4928: fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4929: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4930: fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4931: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4932: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4933: 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",\
4934: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4935: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4936: }else{
4937: first=0;
4938: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4939: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4940: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4941: 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",\
4942: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4943: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4944: }/* if first */
4945: } /* age mod 5 */
4946: } /* end loop age */
4947: fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
4948: first=1;
4949: } /*l12 */
4950: } /* k12 */
4951: } /*l1 */
4952: }/* k1 */
4953: /* } */ /* loop covariates */
4954: }
4955: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4956: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4957: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4958: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4959: free_vector(xp,1,npar);
4960: fclose(ficresprob);
4961: fclose(ficresprobcov);
4962: fclose(ficresprobcor);
4963: fflush(ficgp);
4964: fflush(fichtmcov);
4965: }
4966:
4967:
4968: /******************* Printing html file ***********/
4969: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
4970: int lastpass, int stepm, int weightopt, char model[],\
4971: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4972: int popforecast, int prevfcast, int estepm , \
4973: double jprev1, double mprev1,double anprev1, double dateprev1, \
4974: double jprev2, double mprev2,double anprev2, double dateprev2){
4975: int jj1, k1, i1, cpt;
4976:
4977: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4978: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4979: </ul>");
4980: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
4981: fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
4982: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
4983: fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
4984: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
4985: fprintf(fichtm,", <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
4986: fprintf(fichtm,"\
4987: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4988: stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
4989: fprintf(fichtm,"\
4990: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4991: subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
4992: fprintf(fichtm,"\
4993: - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
4994: <a href=\"%s\">%s</a> <br>\n",
4995: estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
4996: if(prevfcast==1){
4997: fprintf(fichtm,"\
4998: - Prevalence projections by age and states: \
4999: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
5000: }
5001:
5002: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
5003:
5004: m=pow(2,cptcoveff);
5005: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5006:
5007: jj1=0;
5008: for(k1=1; k1<=m;k1++){
5009: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5010: jj1++;
5011: if (cptcovn > 0) {
5012: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5013: for (cpt=1; cpt<=cptcoveff;cpt++){
5014: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5015: printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
5016: }
5017: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5018: }
5019: /* aij, bij */
5020: fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
5021: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5022: /* Pij */
5023: fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
5024: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5025: /* Quasi-incidences */
5026: fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
5027: before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
5028: incidence (rates) are the limit when h tends to zero of the ratio of the probability <sub>h</sub>P<sub>ij</sub> \
5029: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
5030: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
5031: /* Survival functions (period) in state j */
5032: for(cpt=1; cpt<=nlstate;cpt++){
5033: 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> \
5034: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
5035: }
5036: /* State specific survival functions (period) */
5037: for(cpt=1; cpt<=nlstate;cpt++){
5038: fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
5039: Or probability to survive in various states (1 to %d) being in state %d at different ages.\
5040: <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);
5041: }
5042: /* Period (stable) prevalence in each health state */
5043: for(cpt=1; cpt<=nlstate;cpt++){
5044: 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> \
5045: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
5046: }
5047: if(prevfcast==1){
5048: /* Projection of prevalence up to period (stable) prevalence in each health state */
5049: for(cpt=1; cpt<=nlstate;cpt++){
5050: fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
5051: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
5052: }
5053: }
5054:
5055: for(cpt=1; cpt<=nlstate;cpt++) {
5056: 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> \
5057: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
5058: }
5059: /* } /\* end i1 *\/ */
5060: }/* End k1 */
5061: fprintf(fichtm,"</ul>");
5062:
5063: fprintf(fichtm,"\
5064: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
5065: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
5066: - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
5067: But because parameters are usually highly correlated (a higher incidence of disability \
5068: and a higher incidence of recovery can give very close observed transition) it might \
5069: be very useful to look not only at linear confidence intervals estimated from the \
5070: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
5071: (parameters) of the logistic regression, it might be more meaningful to visualize the \
5072: covariance matrix of the one-step probabilities. \
5073: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
5074:
5075: fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5076: subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
5077: fprintf(fichtm,"\
5078: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5079: subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
5080:
5081: fprintf(fichtm,"\
5082: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
5083: subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
5084: fprintf(fichtm,"\
5085: - 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): \
5086: <a href=\"%s\">%s</a> <br>\n</li>",
5087: estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
5088: fprintf(fichtm,"\
5089: - (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): \
5090: <a href=\"%s\">%s</a> <br>\n</li>",
5091: estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
5092: fprintf(fichtm,"\
5093: - 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",
5094: estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
5095: fprintf(fichtm,"\
5096: - 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",
5097: estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
5098: fprintf(fichtm,"\
5099: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
5100: subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
5101:
5102: /* if(popforecast==1) fprintf(fichtm,"\n */
5103: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
5104: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
5105: /* <br>",fileres,fileres,fileres,fileres); */
5106: /* else */
5107: /* 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); */
5108: fflush(fichtm);
5109: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
5110:
5111: m=pow(2,cptcoveff);
5112: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
5113:
5114: jj1=0;
5115: for(k1=1; k1<=m;k1++){
5116: /* for(i1=1; i1<=ncodemax[k1];i1++){ */
5117: jj1++;
5118: if (cptcovn > 0) {
5119: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
5120: for (cpt=1; cpt<=cptcoveff;cpt++)
5121: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
5122: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
5123: }
5124: for(cpt=1; cpt<=nlstate;cpt++) {
5125: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
5126: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
5127: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);
5128: }
5129: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
5130: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
5131: true period expectancies (those weighted with period prevalences are also\
5132: drawn in addition to the population based expectancies computed using\
5133: observed and cahotic prevalences: <a href=\"%s_%d.svg\">%s_%d.svg<br>\
5134: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
5135: /* } /\* end i1 *\/ */
5136: }/* End k1 */
5137: fprintf(fichtm,"</ul>");
5138: fflush(fichtm);
5139: }
5140:
5141: /******************* Gnuplot file **************/
5142: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
5143:
5144: char dirfileres[132],optfileres[132];
5145: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
5146: int lv=0, vlv=0, kl=0;
5147: int ng=0;
5148: int vpopbased;
5149: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
5150: /* printf("Problem with file %s",optionfilegnuplot); */
5151: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
5152: /* } */
5153:
5154: /*#ifdef windows */
5155: fprintf(ficgp,"cd \"%s\" \n",pathc);
5156: /*#endif */
5157: m=pow(2,cptcoveff);
5158:
5159: /* Contribution to likelihood */
5160: /* Plot the probability implied in the likelihood */
5161: fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
5162: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
5163: /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
5164: fprintf(ficgp,"\nset ter pngcairo size 640, 480");
5165: /* nice for mle=4 plot by number of matrix products.
5166: replot "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
5167: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)" */
5168: /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
5169: fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
5170: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
5171: fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
5172: fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
5173: for (i=1; i<= nlstate ; i ++) {
5174: fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
5175: fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot \"%s\"",subdirf(fileresilk));
5176: fprintf(ficgp," u 2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
5177: for (j=2; j<= nlstate+ndeath ; j ++) {
5178: fprintf(ficgp,",\\\n \"\" u 2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
5179: }
5180: fprintf(ficgp,";\nset out; unset ylabel;\n");
5181: }
5182: /* 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 */
5183: /* fprintf(ficgp,"\nset log y;plot \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
5184: /* fprintf(ficgp,"\nreplot \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
5185: fprintf(ficgp,"\nset out;unset log\n");
5186: /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
5187:
5188: strcpy(dirfileres,optionfilefiname);
5189: strcpy(optfileres,"vpl");
5190: /* 1eme*/
5191: for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
5192: for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
5193: /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
5194: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
5195: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5196: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5197: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5198: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5199: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5200: vlv= nbcode[Tvaraff[lv]][lv];
5201: fprintf(ficgp," V%d=%d ",k,vlv);
5202: }
5203: fprintf(ficgp,"\n#\n");
5204:
5205: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
5206: fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
5207: fprintf(ficgp,"set xlabel \"Age\" \n\
5208: set ylabel \"Probability\" \n\
5209: set ter svg size 640, 480\n\
5210: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
5211:
5212: for (i=1; i<= nlstate ; i ++) {
5213: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5214: else fprintf(ficgp," %%*lf (%%*lf)");
5215: }
5216: 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);
5217: for (i=1; i<= nlstate ; i ++) {
5218: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5219: else fprintf(ficgp," %%*lf (%%*lf)");
5220: }
5221: 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);
5222: for (i=1; i<= nlstate ; i ++) {
5223: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
5224: else fprintf(ficgp," %%*lf (%%*lf)");
5225: }
5226: 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));
5227: fprintf(ficgp,"\nset out \n");
5228: } /* k1 */
5229: } /* cpt */
5230: /*2 eme*/
5231: for (k1=1; k1<= m ; k1 ++) {
5232: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
5233: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5234: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5235: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5236: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5237: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5238: vlv= nbcode[Tvaraff[lv]][lv];
5239: fprintf(ficgp," V%d=%d ",k,vlv);
5240: }
5241: fprintf(ficgp,"\n#\n");
5242:
5243: fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
5244: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
5245: if(vpopbased==0)
5246: fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
5247: else
5248: fprintf(ficgp,"\nreplot ");
5249: for (i=1; i<= nlstate+1 ; i ++) {
5250: k=2*i;
5251: 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);
5252: for (j=1; j<= nlstate+1 ; j ++) {
5253: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5254: else fprintf(ficgp," %%*lf (%%*lf)");
5255: }
5256: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
5257: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
5258: 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);
5259: for (j=1; j<= nlstate+1 ; j ++) {
5260: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5261: else fprintf(ficgp," %%*lf (%%*lf)");
5262: }
5263: fprintf(ficgp,"\" t\"\" w l lt 0,");
5264: 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);
5265: for (j=1; j<= nlstate+1 ; j ++) {
5266: if (j==i) fprintf(ficgp," %%lf (%%lf)");
5267: else fprintf(ficgp," %%*lf (%%*lf)");
5268: }
5269: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
5270: else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
5271: } /* state */
5272: } /* vpopbased */
5273: fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
5274: } /* k1 */
5275:
5276:
5277: /*3eme*/
5278: for (k1=1; k1<= m ; k1 ++) {
5279: for (cpt=1; cpt<= nlstate ; cpt ++) {
5280: fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files: cov=%d state=%d",k1, cpt);
5281: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5282: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5283: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5284: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5285: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5286: vlv= nbcode[Tvaraff[lv]][lv];
5287: fprintf(ficgp," V%d=%d ",k,vlv);
5288: }
5289: fprintf(ficgp,"\n#\n");
5290:
5291: /* k=2+nlstate*(2*cpt-2); */
5292: k=2+(nlstate+1)*(cpt-1);
5293: fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
5294: fprintf(ficgp,"set ter svg size 640, 480\n\
5295: 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);
5296: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5297: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5298: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5299: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
5300: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
5301: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
5302:
5303: */
5304: for (i=1; i< nlstate ; i ++) {
5305: 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);
5306: /* 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);*/
5307:
5308: }
5309: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
5310: }
5311: }
5312:
5313: /* Survival functions (period) from state i in state j by initial state i */
5314: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
5315: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5316: fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
5317: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5318: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5319: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5320: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5321: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5322: vlv= nbcode[Tvaraff[lv]][lv];
5323: fprintf(ficgp," V%d=%d ",k,vlv);
5324: }
5325: fprintf(ficgp,"\n#\n");
5326:
5327: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
5328: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5329: set ter svg size 640, 480\n\
5330: unset log y\n\
5331: plot [%.f:%.f] ", ageminpar, agemaxpar);
5332: k=3;
5333: for (i=1; i<= nlstate ; i ++){
5334: if(i==1)
5335: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5336: else
5337: fprintf(ficgp,", '' ");
5338: l=(nlstate+ndeath)*(i-1)+1;
5339: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5340: for (j=2; j<= nlstate+ndeath ; j ++)
5341: fprintf(ficgp,"+$%d",k+l+j-1);
5342: fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
5343: } /* nlstate */
5344: fprintf(ficgp,"\nset out\n");
5345: } /* end cpt state*/
5346: } /* end covariate */
5347:
5348: /* Survival functions (period) from state i in state j by final state j */
5349: for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
5350: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state */
5351: 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);
5352: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5353: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5354: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5355: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5356: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5357: vlv= nbcode[Tvaraff[lv]][lv];
5358: fprintf(ficgp," V%d=%d ",k,vlv);
5359: }
5360: fprintf(ficgp,"\n#\n");
5361:
5362: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
5363: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
5364: set ter svg size 640, 480\n\
5365: unset log y\n\
5366: plot [%.f:%.f] ", ageminpar, agemaxpar);
5367: k=3;
5368: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5369: if(j==1)
5370: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5371: else
5372: fprintf(ficgp,", '' ");
5373: l=(nlstate+ndeath)*(cpt-1) +j;
5374: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
5375: /* for (i=2; i<= nlstate+ndeath ; i ++) */
5376: /* fprintf(ficgp,"+$%d",k+l+i-1); */
5377: fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
5378: } /* nlstate */
5379: fprintf(ficgp,", '' ");
5380: fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
5381: for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
5382: l=(nlstate+ndeath)*(cpt-1) +j;
5383: if(j < nlstate)
5384: fprintf(ficgp,"$%d +",k+l);
5385: else
5386: fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
5387: }
5388: fprintf(ficgp,"\nset out\n");
5389: } /* end cpt state*/
5390: } /* end covariate */
5391:
5392: /* CV preval stable (period) for each covariate */
5393: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5394: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5395: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
5396: for (k=1; k<=cptcoveff; k++){ /* For each covariate and each value */
5397: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
5398: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5399: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5400: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5401: vlv= nbcode[Tvaraff[lv]][lv];
5402: fprintf(ficgp," V%d=%d ",k,vlv);
5403: }
5404: fprintf(ficgp,"\n#\n");
5405:
5406: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
5407: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
5408: set ter svg size 640, 480\n\
5409: unset log y\n\
5410: plot [%.f:%.f] ", ageminpar, agemaxpar);
5411: k=3; /* Offset */
5412: for (i=1; i<= nlstate ; i ++){
5413: if(i==1)
5414: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
5415: else
5416: fprintf(ficgp,", '' ");
5417: l=(nlstate+ndeath)*(i-1)+1;
5418: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
5419: for (j=2; j<= nlstate ; j ++)
5420: fprintf(ficgp,"+$%d",k+l+j-1);
5421: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
5422: } /* nlstate */
5423: fprintf(ficgp,"\nset out\n");
5424: } /* end cpt state*/
5425: } /* end covariate */
5426:
5427: if(prevfcast==1){
5428: /* Projection from cross-sectional to stable (period) for each covariate */
5429:
5430: for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
5431: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
5432: fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
5433: for (k=1; k<=cptcoveff; k++){ /* For each correspondig covariate value */
5434: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5435: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5436: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5437: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5438: vlv= nbcode[Tvaraff[lv]][lv];
5439: fprintf(ficgp," V%d=%d ",k,vlv);
5440: }
5441: fprintf(ficgp,"\n#\n");
5442:
5443: fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
5444: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
5445: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
5446: set ter svg size 640, 480\n\
5447: unset log y\n\
5448: plot [%.f:%.f] ", ageminpar, agemaxpar);
5449: for (i=1; i<= nlstate+1 ; i ++){ /* nlstate +1 p11 p21 p.1 */
5450: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5451: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5452: /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5453: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5454: if(i==1){
5455: fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
5456: }else{
5457: fprintf(ficgp,",\\\n '' ");
5458: }
5459: if(cptcoveff ==0){ /* No covariate */
5460: fprintf(ficgp," u 2:("); /* Age is in 2 */
5461: /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
5462: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
5463: if(i==nlstate+1)
5464: fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
5465: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,cpt );
5466: else
5467: fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
5468: 2+(cpt-1)*(nlstate+1)+1+(i-1), 2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5469: }else{
5470: fprintf(ficgp,"u 6:(("); /* Age is in 6 */
5471: /*# V1 = 1 V2 = 0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
5472: /*# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
5473: kl=0;
5474: for (k=1; k<=cptcoveff; k++){ /* For each covariate */
5475: lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
5476: /* decodtabm(1,1,4) = 1 because h=1 k= (1) 1 1 1 */
5477: /* decodtabm(1,2,4) = 1 because h=1 k= 1 (1) 1 1 */
5478: /* decodtabm(13,3,4)= 2 because h=13 k= 1 1 (2) 2 */
5479: vlv= nbcode[Tvaraff[lv]][lv];
5480: kl++;
5481: /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
5482: /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */
5483: /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */
5484: /* '' u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
5485: if(k==cptcoveff)
5486: if(i==nlstate+1)
5487: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5488: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,cpt );
5489: else
5490: fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
5491: 6+(cpt-1)*(nlstate+1)+1+(i-1), 6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
5492: else{
5493: fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
5494: kl++;
5495: }
5496: } /* end covariate */
5497: } /* end if covariate */
5498: } /* nlstate */
5499: fprintf(ficgp,"\nset out\n");
5500: } /* end cpt state*/
5501: } /* end covariate */
5502: } /* End if prevfcast */
5503:
5504:
5505: /* proba elementaires */
5506: fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
5507: for(i=1,jk=1; i <=nlstate; i++){
5508: fprintf(ficgp,"# initial state %d\n",i);
5509: for(k=1; k <=(nlstate+ndeath); k++){
5510: if (k != i) {
5511: fprintf(ficgp,"# current state %d\n",k);
5512: for(j=1; j <=ncovmodel; j++){
5513: fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
5514: jk++;
5515: }
5516: fprintf(ficgp,"\n");
5517: }
5518: }
5519: }
5520: fprintf(ficgp,"##############\n#\n");
5521:
5522: /*goto avoid;*/
5523: fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
5524: fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
5525: fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
5526: fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
5527: fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
5528: fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5529: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5530: fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5531: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
5532: fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
5533: fprintf(ficgp,"# (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
5534: fprintf(ficgp,"# +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
5535: fprintf(ficgp,"# +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
5536: fprintf(ficgp,"#\n");
5537: for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
5538: fprintf(ficgp,"# ng=%d\n",ng);
5539: fprintf(ficgp,"# jk=1 to 2^%d=%d\n",cptcoveff,m);
5540: for(jk=1; jk <=m; jk++) {
5541: fprintf(ficgp,"# jk=%d\n",jk);
5542: fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
5543: fprintf(ficgp,"\nset ter svg size 640, 480 ");
5544: if (ng==1){
5545: fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
5546: fprintf(ficgp,"\nunset log y");
5547: }else if (ng==2){
5548: fprintf(ficgp,"\nset ylabel \"Probability\"\n");
5549: fprintf(ficgp,"\nset log y");
5550: }else if (ng==3){
5551: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
5552: fprintf(ficgp,"\nset log y");
5553: }else
5554: fprintf(ficgp,"\nunset title ");
5555: fprintf(ficgp,"\nplot [%.f:%.f] ",ageminpar,agemaxpar);
5556: i=1;
5557: for(k2=1; k2<=nlstate; k2++) {
5558: k3=i;
5559: for(k=1; k<=(nlstate+ndeath); k++) {
5560: if (k != k2){
5561: switch( ng) {
5562: case 1:
5563: if(nagesqr==0)
5564: fprintf(ficgp," p%d+p%d*x",i,i+1);
5565: else /* nagesqr =1 */
5566: fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5567: break;
5568: case 2: /* ng=2 */
5569: if(nagesqr==0)
5570: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
5571: else /* nagesqr =1 */
5572: fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
5573: break;
5574: case 3:
5575: if(nagesqr==0)
5576: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
5577: else /* nagesqr =1 */
5578: fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
5579: break;
5580: }
5581: ij=1;/* To be checked else nbcode[0][0] wrong */
5582: for(j=3; j <=ncovmodel-nagesqr; j++) {
5583: /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
5584: if(ij <=cptcovage) { /* Bug valgrind */
5585: if((j-2)==Tage[ij]) { /* Bug valgrind */
5586: fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5587: /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5588: ij++;
5589: }
5590: }
5591: else
5592: fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5593: }
5594: if(ng != 1){
5595: fprintf(ficgp,")/(1");
5596:
5597: for(k1=1; k1 <=nlstate; k1++){
5598: if(nagesqr==0)
5599: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
5600: else /* nagesqr =1 */
5601: 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);
5602:
5603: ij=1;
5604: for(j=3; j <=ncovmodel-nagesqr; j++){
5605: if(ij <=cptcovage) { /* Bug valgrind */
5606: if((j-2)==Tage[ij]) { /* Bug valgrind */
5607: fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5608: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
5609: ij++;
5610: }
5611: }
5612: else
5613: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
5614: }
5615: fprintf(ficgp,")");
5616: }
5617: fprintf(ficgp,")");
5618: if(ng ==2)
5619: fprintf(ficgp," t \"p%d%d\" ", k2,k);
5620: else /* ng= 3 */
5621: fprintf(ficgp," t \"i%d%d\" ", k2,k);
5622: }else{ /* end ng <> 1 */
5623: fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
5624: }
5625: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
5626: i=i+ncovmodel;
5627: }
5628: } /* end k */
5629: } /* end k2 */
5630: fprintf(ficgp,"\n set out\n");
5631: } /* end jk */
5632: } /* end ng */
5633: /* avoid: */
5634: fflush(ficgp);
5635: } /* end gnuplot */
5636:
5637:
5638: /*************** Moving average **************/
5639: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
5640:
5641: int i, cpt, cptcod;
5642: int modcovmax =1;
5643: int mobilavrange, mob;
5644: double age;
5645:
5646: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
5647: a covariate has 2 modalities */
5648: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
5649:
5650: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
5651: if(mobilav==1) mobilavrange=5; /* default */
5652: else mobilavrange=mobilav;
5653: for (age=bage; age<=fage; age++)
5654: for (i=1; i<=nlstate;i++)
5655: for (cptcod=1;cptcod<=modcovmax;cptcod++)
5656: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
5657: /* We keep the original values on the extreme ages bage, fage and for
5658: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
5659: we use a 5 terms etc. until the borders are no more concerned.
5660: */
5661: for (mob=3;mob <=mobilavrange;mob=mob+2){
5662: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
5663: for (i=1; i<=nlstate;i++){
5664: for (cptcod=1;cptcod<=modcovmax;cptcod++){
5665: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
5666: for (cpt=1;cpt<=(mob-1)/2;cpt++){
5667: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
5668: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
5669: }
5670: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
5671: }
5672: }
5673: }/* end age */
5674: }/* end mob */
5675: }else return -1;
5676: return 0;
5677: }/* End movingaverage */
5678:
5679:
5680: /************** Forecasting ******************/
5681: 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){
5682: /* proj1, year, month, day of starting projection
5683: agemin, agemax range of age
5684: dateprev1 dateprev2 range of dates during which prevalence is computed
5685: anproj2 year of en of projection (same day and month as proj1).
5686: */
5687: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
5688: double agec; /* generic age */
5689: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
5690: double *popeffectif,*popcount;
5691: double ***p3mat;
5692: double ***mobaverage;
5693: char fileresf[FILENAMELENGTH];
5694:
5695: agelim=AGESUP;
5696: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
5697: in each health status at the date of interview (if between dateprev1 and dateprev2).
5698: We still use firstpass and lastpass as another selection.
5699: */
5700: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
5701: /* firstpass, lastpass, stepm, weightopt, model); */
5702: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5703:
5704: strcpy(fileresf,"F_");
5705: strcat(fileresf,fileresu);
5706: if((ficresf=fopen(fileresf,"w"))==NULL) {
5707: printf("Problem with forecast resultfile: %s\n", fileresf);
5708: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
5709: }
5710: printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
5711: fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
5712:
5713: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5714:
5715: if (mobilav!=0) {
5716: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5717: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5718: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5719: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5720: }
5721: }
5722:
5723: stepsize=(int) (stepm+YEARM-1)/YEARM;
5724: if (stepm<=12) stepsize=1;
5725: if(estepm < stepm){
5726: printf ("Problem %d lower than %d\n",estepm, stepm);
5727: }
5728: else hstepm=estepm;
5729:
5730: hstepm=hstepm/stepm;
5731: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
5732: fractional in yp1 */
5733: anprojmean=yp;
5734: yp2=modf((yp1*12),&yp);
5735: mprojmean=yp;
5736: yp1=modf((yp2*30.5),&yp);
5737: jprojmean=yp;
5738: if(jprojmean==0) jprojmean=1;
5739: if(mprojmean==0) jprojmean=1;
5740:
5741: i1=cptcoveff;
5742: if (cptcovn < 1){i1=1;}
5743:
5744: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
5745:
5746: fprintf(ficresf,"#****** Routine prevforecast **\n");
5747:
5748: /* if (h==(int)(YEARM*yearp)){ */
5749: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
5750: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5751: k=k+1;
5752: fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
5753: for(j=1;j<=cptcoveff;j++) {
5754: fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5755: }
5756: fprintf(ficresf," yearproj age");
5757: for(j=1; j<=nlstate+ndeath;j++){
5758: for(i=1; i<=nlstate;i++)
5759: fprintf(ficresf," p%d%d",i,j);
5760: fprintf(ficresf," p.%d",j);
5761: }
5762: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
5763: fprintf(ficresf,"\n");
5764: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
5765:
5766: for (agec=fage; agec>=(ageminpar-1); agec--){
5767: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
5768: nhstepm = nhstepm/hstepm;
5769: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5770: oldm=oldms;savm=savms;
5771: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
5772:
5773: for (h=0; h<=nhstepm; h++){
5774: if (h*hstepm/YEARM*stepm ==yearp) {
5775: fprintf(ficresf,"\n");
5776: for(j=1;j<=cptcoveff;j++)
5777: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5778: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
5779: }
5780: for(j=1; j<=nlstate+ndeath;j++) {
5781: ppij=0.;
5782: for(i=1; i<=nlstate;i++) {
5783: if (mobilav==1)
5784: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
5785: else {
5786: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
5787: }
5788: if (h*hstepm/YEARM*stepm== yearp) {
5789: fprintf(ficresf," %.3f", p3mat[i][j][h]);
5790: }
5791: } /* end i */
5792: if (h*hstepm/YEARM*stepm==yearp) {
5793: fprintf(ficresf," %.3f", ppij);
5794: }
5795: }/* end j */
5796: } /* end h */
5797: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5798: } /* end agec */
5799: } /* end yearp */
5800: } /* end cptcod */
5801: } /* end cptcov */
5802:
5803: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5804:
5805: fclose(ficresf);
5806: printf("End of Computing forecasting \n");
5807: fprintf(ficlog,"End of Computing forecasting\n");
5808:
5809: }
5810:
5811: /************** Forecasting *****not tested NB*************/
5812: 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){
5813:
5814: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
5815: int *popage;
5816: double calagedatem, agelim, kk1, kk2;
5817: double *popeffectif,*popcount;
5818: double ***p3mat,***tabpop,***tabpopprev;
5819: double ***mobaverage;
5820: char filerespop[FILENAMELENGTH];
5821:
5822: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5823: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5824: agelim=AGESUP;
5825: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
5826:
5827: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
5828:
5829:
5830: strcpy(filerespop,"POP_");
5831: strcat(filerespop,fileresu);
5832: if((ficrespop=fopen(filerespop,"w"))==NULL) {
5833: printf("Problem with forecast resultfile: %s\n", filerespop);
5834: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
5835: }
5836: printf("Computing forecasting: result on file '%s' \n", filerespop);
5837: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
5838:
5839: if (cptcoveff==0) ncodemax[cptcoveff]=1;
5840:
5841: if (mobilav!=0) {
5842: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5843: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
5844: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
5845: printf(" Error in movingaverage mobilav=%d\n",mobilav);
5846: }
5847: }
5848:
5849: stepsize=(int) (stepm+YEARM-1)/YEARM;
5850: if (stepm<=12) stepsize=1;
5851:
5852: agelim=AGESUP;
5853:
5854: hstepm=1;
5855: hstepm=hstepm/stepm;
5856:
5857: if (popforecast==1) {
5858: if((ficpop=fopen(popfile,"r"))==NULL) {
5859: printf("Problem with population file : %s\n",popfile);exit(0);
5860: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
5861: }
5862: popage=ivector(0,AGESUP);
5863: popeffectif=vector(0,AGESUP);
5864: popcount=vector(0,AGESUP);
5865:
5866: i=1;
5867: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
5868:
5869: imx=i;
5870: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
5871: }
5872:
5873: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
5874: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
5875: k=k+1;
5876: fprintf(ficrespop,"\n#******");
5877: for(j=1;j<=cptcoveff;j++) {
5878: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
5879: }
5880: fprintf(ficrespop,"******\n");
5881: fprintf(ficrespop,"# Age");
5882: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
5883: if (popforecast==1) fprintf(ficrespop," [Population]");
5884:
5885: for (cpt=0; cpt<=0;cpt++) {
5886: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5887:
5888: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5889: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5890: nhstepm = nhstepm/hstepm;
5891:
5892: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5893: oldm=oldms;savm=savms;
5894: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5895:
5896: for (h=0; h<=nhstepm; h++){
5897: if (h==(int) (calagedatem+YEARM*cpt)) {
5898: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5899: }
5900: for(j=1; j<=nlstate+ndeath;j++) {
5901: kk1=0.;kk2=0;
5902: for(i=1; i<=nlstate;i++) {
5903: if (mobilav==1)
5904: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
5905: else {
5906: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
5907: }
5908: }
5909: if (h==(int)(calagedatem+12*cpt)){
5910: tabpop[(int)(agedeb)][j][cptcod]=kk1;
5911: /*fprintf(ficrespop," %.3f", kk1);
5912: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
5913: }
5914: }
5915: for(i=1; i<=nlstate;i++){
5916: kk1=0.;
5917: for(j=1; j<=nlstate;j++){
5918: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
5919: }
5920: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
5921: }
5922:
5923: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
5924: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
5925: }
5926: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5927: }
5928: }
5929:
5930: /******/
5931:
5932: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
5933: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
5934: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
5935: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
5936: nhstepm = nhstepm/hstepm;
5937:
5938: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5939: oldm=oldms;savm=savms;
5940: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5941: for (h=0; h<=nhstepm; h++){
5942: if (h==(int) (calagedatem+YEARM*cpt)) {
5943: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
5944: }
5945: for(j=1; j<=nlstate+ndeath;j++) {
5946: kk1=0.;kk2=0;
5947: for(i=1; i<=nlstate;i++) {
5948: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
5949: }
5950: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
5951: }
5952: }
5953: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5954: }
5955: }
5956: }
5957: }
5958:
5959: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5960:
5961: if (popforecast==1) {
5962: free_ivector(popage,0,AGESUP);
5963: free_vector(popeffectif,0,AGESUP);
5964: free_vector(popcount,0,AGESUP);
5965: }
5966: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5967: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
5968: fclose(ficrespop);
5969: } /* End of popforecast */
5970:
5971: int fileappend(FILE *fichier, char *optionfich)
5972: {
5973: if((fichier=fopen(optionfich,"a"))==NULL) {
5974: printf("Problem with file: %s\n", optionfich);
5975: fprintf(ficlog,"Problem with file: %s\n", optionfich);
5976: return (0);
5977: }
5978: fflush(fichier);
5979: return (1);
5980: }
5981:
5982:
5983: /**************** function prwizard **********************/
5984: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
5985: {
5986:
5987: /* Wizard to print covariance matrix template */
5988:
5989: char ca[32], cb[32];
5990: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
5991: int numlinepar;
5992:
5993: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5994: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
5995: for(i=1; i <=nlstate; i++){
5996: jj=0;
5997: for(j=1; j <=nlstate+ndeath; j++){
5998: if(j==i) continue;
5999: jj++;
6000: /*ca[0]= k+'a'-1;ca[1]='\0';*/
6001: printf("%1d%1d",i,j);
6002: fprintf(ficparo,"%1d%1d",i,j);
6003: for(k=1; k<=ncovmodel;k++){
6004: /* printf(" %lf",param[i][j][k]); */
6005: /* fprintf(ficparo," %lf",param[i][j][k]); */
6006: printf(" 0.");
6007: fprintf(ficparo," 0.");
6008: }
6009: printf("\n");
6010: fprintf(ficparo,"\n");
6011: }
6012: }
6013: printf("# Scales (for hessian or gradient estimation)\n");
6014: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
6015: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
6016: for(i=1; i <=nlstate; i++){
6017: jj=0;
6018: for(j=1; j <=nlstate+ndeath; j++){
6019: if(j==i) continue;
6020: jj++;
6021: fprintf(ficparo,"%1d%1d",i,j);
6022: printf("%1d%1d",i,j);
6023: fflush(stdout);
6024: for(k=1; k<=ncovmodel;k++){
6025: /* printf(" %le",delti3[i][j][k]); */
6026: /* fprintf(ficparo," %le",delti3[i][j][k]); */
6027: printf(" 0.");
6028: fprintf(ficparo," 0.");
6029: }
6030: numlinepar++;
6031: printf("\n");
6032: fprintf(ficparo,"\n");
6033: }
6034: }
6035: printf("# Covariance matrix\n");
6036: /* # 121 Var(a12)\n\ */
6037: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6038: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6039: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6040: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6041: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6042: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6043: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6044: fflush(stdout);
6045: fprintf(ficparo,"# Covariance matrix\n");
6046: /* # 121 Var(a12)\n\ */
6047: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6048: /* # ...\n\ */
6049: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6050:
6051: for(itimes=1;itimes<=2;itimes++){
6052: jj=0;
6053: for(i=1; i <=nlstate; i++){
6054: for(j=1; j <=nlstate+ndeath; j++){
6055: if(j==i) continue;
6056: for(k=1; k<=ncovmodel;k++){
6057: jj++;
6058: ca[0]= k+'a'-1;ca[1]='\0';
6059: if(itimes==1){
6060: printf("#%1d%1d%d",i,j,k);
6061: fprintf(ficparo,"#%1d%1d%d",i,j,k);
6062: }else{
6063: printf("%1d%1d%d",i,j,k);
6064: fprintf(ficparo,"%1d%1d%d",i,j,k);
6065: /* printf(" %.5le",matcov[i][j]); */
6066: }
6067: ll=0;
6068: for(li=1;li <=nlstate; li++){
6069: for(lj=1;lj <=nlstate+ndeath; lj++){
6070: if(lj==li) continue;
6071: for(lk=1;lk<=ncovmodel;lk++){
6072: ll++;
6073: if(ll<=jj){
6074: cb[0]= lk +'a'-1;cb[1]='\0';
6075: if(ll<jj){
6076: if(itimes==1){
6077: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6078: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6079: }else{
6080: printf(" 0.");
6081: fprintf(ficparo," 0.");
6082: }
6083: }else{
6084: if(itimes==1){
6085: printf(" Var(%s%1d%1d)",ca,i,j);
6086: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
6087: }else{
6088: printf(" 0.");
6089: fprintf(ficparo," 0.");
6090: }
6091: }
6092: }
6093: } /* end lk */
6094: } /* end lj */
6095: } /* end li */
6096: printf("\n");
6097: fprintf(ficparo,"\n");
6098: numlinepar++;
6099: } /* end k*/
6100: } /*end j */
6101: } /* end i */
6102: } /* end itimes */
6103:
6104: } /* end of prwizard */
6105: /******************* Gompertz Likelihood ******************************/
6106: double gompertz(double x[])
6107: {
6108: double A,B,L=0.0,sump=0.,num=0.;
6109: int i,n=0; /* n is the size of the sample */
6110:
6111: for (i=0;i<=imx-1 ; i++) {
6112: sump=sump+weight[i];
6113: /* sump=sump+1;*/
6114: num=num+1;
6115: }
6116:
6117:
6118: /* for (i=0; i<=imx; i++)
6119: 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]);*/
6120:
6121: for (i=1;i<=imx ; i++)
6122: {
6123: if (cens[i] == 1 && wav[i]>1)
6124: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
6125:
6126: if (cens[i] == 0 && wav[i]>1)
6127: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
6128: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
6129:
6130: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6131: if (wav[i] > 1 ) { /* ??? */
6132: L=L+A*weight[i];
6133: /* 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]);*/
6134: }
6135: }
6136:
6137: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6138:
6139: return -2*L*num/sump;
6140: }
6141:
6142: #ifdef GSL
6143: /******************* Gompertz_f Likelihood ******************************/
6144: double gompertz_f(const gsl_vector *v, void *params)
6145: {
6146: double A,B,LL=0.0,sump=0.,num=0.;
6147: double *x= (double *) v->data;
6148: int i,n=0; /* n is the size of the sample */
6149:
6150: for (i=0;i<=imx-1 ; i++) {
6151: sump=sump+weight[i];
6152: /* sump=sump+1;*/
6153: num=num+1;
6154: }
6155:
6156:
6157: /* for (i=0; i<=imx; i++)
6158: 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]);*/
6159: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
6160: for (i=1;i<=imx ; i++)
6161: {
6162: if (cens[i] == 1 && wav[i]>1)
6163: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
6164:
6165: if (cens[i] == 0 && wav[i]>1)
6166: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
6167: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
6168:
6169: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
6170: if (wav[i] > 1 ) { /* ??? */
6171: LL=LL+A*weight[i];
6172: /* 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]);*/
6173: }
6174: }
6175:
6176: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
6177: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
6178:
6179: return -2*LL*num/sump;
6180: }
6181: #endif
6182:
6183: /******************* Printing html file ***********/
6184: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
6185: int lastpass, int stepm, int weightopt, char model[],\
6186: int imx, double p[],double **matcov,double agemortsup){
6187: int i,k;
6188:
6189: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
6190: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
6191: for (i=1;i<=2;i++)
6192: 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]));
6193: fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
6194: fprintf(fichtm,"</ul>");
6195:
6196: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
6197:
6198: 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>");
6199:
6200: for (k=agegomp;k<(agemortsup-2);k++)
6201: 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]);
6202:
6203:
6204: fflush(fichtm);
6205: }
6206:
6207: /******************* Gnuplot file **************/
6208: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
6209:
6210: char dirfileres[132],optfileres[132];
6211:
6212: int ng;
6213:
6214:
6215: /*#ifdef windows */
6216: fprintf(ficgp,"cd \"%s\" \n",pathc);
6217: /*#endif */
6218:
6219:
6220: strcpy(dirfileres,optionfilefiname);
6221: strcpy(optfileres,"vpl");
6222: fprintf(ficgp,"set out \"graphmort.svg\"\n ");
6223: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
6224: fprintf(ficgp, "set ter svg size 640, 480\n set log y\n");
6225: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
6226: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
6227:
6228: }
6229:
6230: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
6231: {
6232:
6233: /*-------- data file ----------*/
6234: FILE *fic;
6235: char dummy[]=" ";
6236: int i=0, j=0, n=0;
6237: int linei, month, year,iout;
6238: char line[MAXLINE], linetmp[MAXLINE];
6239: char stra[MAXLINE], strb[MAXLINE];
6240: char *stratrunc;
6241: int lstra;
6242:
6243:
6244: if((fic=fopen(datafile,"r"))==NULL) {
6245: printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
6246: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
6247: }
6248:
6249: i=1;
6250: linei=0;
6251: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
6252: linei=linei+1;
6253: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
6254: if(line[j] == '\t')
6255: line[j] = ' ';
6256: }
6257: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
6258: ;
6259: };
6260: line[j+1]=0; /* Trims blanks at end of line */
6261: if(line[0]=='#'){
6262: fprintf(ficlog,"Comment line\n%s\n",line);
6263: printf("Comment line\n%s\n",line);
6264: continue;
6265: }
6266: trimbb(linetmp,line); /* Trims multiple blanks in line */
6267: strcpy(line, linetmp);
6268:
6269:
6270: for (j=maxwav;j>=1;j--){
6271: cutv(stra, strb, line, ' ');
6272: if(strb[0]=='.') { /* Missing status */
6273: lval=-1;
6274: }else{
6275: errno=0;
6276: lval=strtol(strb,&endptr,10);
6277: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
6278: if( strb[0]=='\0' || (*endptr != '\0')){
6279: 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);
6280: 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);
6281: return 1;
6282: }
6283: }
6284: s[j][i]=lval;
6285:
6286: strcpy(line,stra);
6287: cutv(stra, strb,line,' ');
6288: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6289: }
6290: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6291: month=99;
6292: year=9999;
6293: }else{
6294: 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);
6295: 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);
6296: return 1;
6297: }
6298: anint[j][i]= (double) year;
6299: mint[j][i]= (double)month;
6300: strcpy(line,stra);
6301: } /* ENd Waves */
6302:
6303: cutv(stra, strb,line,' ');
6304: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6305: }
6306: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
6307: month=99;
6308: year=9999;
6309: }else{
6310: 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);
6311: 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);
6312: return 1;
6313: }
6314: andc[i]=(double) year;
6315: moisdc[i]=(double) month;
6316: strcpy(line,stra);
6317:
6318: cutv(stra, strb,line,' ');
6319: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
6320: }
6321: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
6322: month=99;
6323: year=9999;
6324: }else{
6325: 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);
6326: 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);
6327: return 1;
6328: }
6329: if (year==9999) {
6330: 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);
6331: 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);
6332: return 1;
6333:
6334: }
6335: annais[i]=(double)(year);
6336: moisnais[i]=(double)(month);
6337: strcpy(line,stra);
6338:
6339: cutv(stra, strb,line,' ');
6340: errno=0;
6341: dval=strtod(strb,&endptr);
6342: if( strb[0]=='\0' || (*endptr != '\0')){
6343: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
6344: 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);
6345: fflush(ficlog);
6346: return 1;
6347: }
6348: weight[i]=dval;
6349: strcpy(line,stra);
6350:
6351: for (j=ncovcol;j>=1;j--){
6352: cutv(stra, strb,line,' ');
6353: if(strb[0]=='.') { /* Missing status */
6354: lval=-1;
6355: }else{
6356: errno=0;
6357: lval=strtol(strb,&endptr,10);
6358: if( strb[0]=='\0' || (*endptr != '\0')){
6359: 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);
6360: 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);
6361: return 1;
6362: }
6363: }
6364: if(lval <-1 || lval >1){
6365: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6366: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6367: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6368: For example, for multinomial values like 1, 2 and 3,\n \
6369: build V1=0 V2=0 for the reference value (1),\n \
6370: V1=1 V2=0 for (2) \n \
6371: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6372: output of IMaCh is often meaningless.\n \
6373: Exiting.\n",lval,linei, i,line,j);
6374: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
6375: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
6376: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
6377: For example, for multinomial values like 1, 2 and 3,\n \
6378: build V1=0 V2=0 for the reference value (1),\n \
6379: V1=1 V2=0 for (2) \n \
6380: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
6381: output of IMaCh is often meaningless.\n \
6382: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
6383: return 1;
6384: }
6385: covar[j][i]=(double)(lval);
6386: strcpy(line,stra);
6387: }
6388: lstra=strlen(stra);
6389:
6390: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
6391: stratrunc = &(stra[lstra-9]);
6392: num[i]=atol(stratrunc);
6393: }
6394: else
6395: num[i]=atol(stra);
6396: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
6397: 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;}*/
6398:
6399: i=i+1;
6400: } /* End loop reading data */
6401:
6402: *imax=i-1; /* Number of individuals */
6403: fclose(fic);
6404:
6405: return (0);
6406: /* endread: */
6407: printf("Exiting readdata: ");
6408: fclose(fic);
6409: return (1);
6410:
6411:
6412:
6413: }
6414: void removespace(char *str) {
6415: char *p1 = str, *p2 = str;
6416: do
6417: while (*p2 == ' ')
6418: p2++;
6419: while (*p1++ == *p2++);
6420: }
6421:
6422: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
6423: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
6424: * - nagesqr = 1 if age*age in the model, otherwise 0.
6425: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
6426: * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
6427: * - cptcovage number of covariates with age*products =2
6428: * - cptcovs number of simple covariates
6429: * - 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
6430: * which is a new column after the 9 (ncovcol) variables.
6431: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
6432: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
6433: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
6434: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
6435: */
6436: {
6437: int i, j, k, ks;
6438: int j1, k1, k2;
6439: char modelsav[80];
6440: char stra[80], strb[80], strc[80], strd[80],stre[80];
6441: char *strpt;
6442:
6443: /*removespace(model);*/
6444: if (strlen(model) >1){ /* If there is at least 1 covariate */
6445: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
6446: if (strstr(model,"AGE") !=0){
6447: printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
6448: fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
6449: return 1;
6450: }
6451: if (strstr(model,"v") !=0){
6452: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
6453: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
6454: return 1;
6455: }
6456: strcpy(modelsav,model);
6457: if ((strpt=strstr(model,"age*age")) !=0){
6458: printf(" strpt=%s, model=%s\n",strpt, model);
6459: if(strpt != model){
6460: printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6461: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6462: corresponding column of parameters.\n",model);
6463: fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
6464: 'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
6465: corresponding column of parameters.\n",model); fflush(ficlog);
6466: return 1;
6467: }
6468:
6469: nagesqr=1;
6470: if (strstr(model,"+age*age") !=0)
6471: substrchaine(modelsav, model, "+age*age");
6472: else if (strstr(model,"age*age+") !=0)
6473: substrchaine(modelsav, model, "age*age+");
6474: else
6475: substrchaine(modelsav, model, "age*age");
6476: }else
6477: nagesqr=0;
6478: if (strlen(modelsav) >1){
6479: j=nbocc(modelsav,'+'); /**< j=Number of '+' */
6480: j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
6481: cptcovs=j+1-j1; /**< Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2 */
6482: cptcovt= j+1; /* Number of total covariates in the model, not including
6483: * cst, age and age*age
6484: * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
6485: /* including age products which are counted in cptcovage.
6486: * but the covariates which are products must be treated
6487: * separately: ncovn=4- 2=2 (V1+V3). */
6488: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
6489: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
6490:
6491:
6492: /* Design
6493: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
6494: * < ncovcol=8 >
6495: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
6496: * k= 1 2 3 4 5 6 7 8
6497: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
6498: * covar[k,i], value of kth covariate if not including age for individual i:
6499: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
6500: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
6501: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
6502: * Tage[++cptcovage]=k
6503: * if products, new covar are created after ncovcol with k1
6504: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
6505: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
6506: * 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
6507: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
6508: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
6509: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
6510: * < ncovcol=8 >
6511: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
6512: * k= 1 2 3 4 5 6 7 8 9 10 11 12
6513: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
6514: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6515: * p Tprod[1]@2={ 6, 5}
6516: *p Tvard[1][1]@4= {7, 8, 5, 6}
6517: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
6518: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
6519: *How to reorganize?
6520: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
6521: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
6522: * {2, 1, 4, 8, 5, 6, 3, 7}
6523: * Struct []
6524: */
6525:
6526: /* This loop fills the array Tvar from the string 'model'.*/
6527: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
6528: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
6529: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
6530: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
6531: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
6532: /* k=1 Tvar[1]=2 (from V2) */
6533: /* k=5 Tvar[5] */
6534: /* for (k=1; k<=cptcovn;k++) { */
6535: /* cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
6536: /* } */
6537: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
6538: /*
6539: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
6540: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
6541: Tvar[k]=0;
6542: cptcovage=0;
6543: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
6544: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
6545: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
6546: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
6547: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
6548: /*scanf("%d",i);*/
6549: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
6550: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
6551: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
6552: /* covar is not filled and then is empty */
6553: cptcovprod--;
6554: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
6555: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
6556: cptcovage++; /* Sums the number of covariates which include age as a product */
6557: Tage[cptcovage]=k; /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
6558: /*printf("stre=%s ", stre);*/
6559: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
6560: cptcovprod--;
6561: cutl(stre,strb,strc,'V');
6562: Tvar[k]=atoi(stre);
6563: cptcovage++;
6564: Tage[cptcovage]=k;
6565: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
6566: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
6567: cptcovn++;
6568: cptcovprodnoage++;k1++;
6569: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
6570: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
6571: because this model-covariate is a construction we invent a new column
6572: ncovcol + k1
6573: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
6574: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
6575: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
6576: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
6577: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
6578: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
6579: k2=k2+2;
6580: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
6581: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
6582: for (i=1; i<=lastobs;i++){
6583: /* Computes the new covariate which is a product of
6584: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
6585: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
6586: }
6587: } /* End age is not in the model */
6588: } /* End if model includes a product */
6589: else { /* no more sum */
6590: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
6591: /* scanf("%d",i);*/
6592: cutl(strd,strc,strb,'V');
6593: ks++; /**< Number of simple covariates */
6594: cptcovn++;
6595: Tvar[k]=atoi(strd);
6596: }
6597: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
6598: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
6599: scanf("%d",i);*/
6600: } /* end of loop + on total covariates */
6601: } /* end if strlen(modelsave == 0) age*age might exist */
6602: } /* end if strlen(model == 0) */
6603:
6604: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
6605: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
6606:
6607: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
6608: printf("cptcovprod=%d ", cptcovprod);
6609: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
6610:
6611: scanf("%d ",i);*/
6612:
6613:
6614: return (0); /* with covar[new additional covariate if product] and Tage if age */
6615: /*endread:*/
6616: printf("Exiting decodemodel: ");
6617: return (1);
6618: }
6619:
6620: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
6621: {
6622: int i, m;
6623:
6624: for (i=1; i<=imx; i++) {
6625: for(m=2; (m<= maxwav); m++) {
6626: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
6627: anint[m][i]=9999;
6628: s[m][i]=-1;
6629: }
6630: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
6631: *nberr = *nberr + 1;
6632: 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);
6633: 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);
6634: s[m][i]=-1;
6635: }
6636: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
6637: (*nberr)++;
6638: 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]);
6639: 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]);
6640: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
6641: }
6642: }
6643: }
6644:
6645: for (i=1; i<=imx; i++) {
6646: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
6647: for(m=firstpass; (m<= lastpass); m++){
6648: if(s[m][i] >0 || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
6649: if (s[m][i] >= nlstate+1) {
6650: if(agedc[i]>0){
6651: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
6652: agev[m][i]=agedc[i];
6653: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
6654: }else {
6655: if ((int)andc[i]!=9999){
6656: nbwarn++;
6657: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
6658: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
6659: agev[m][i]=-1;
6660: }
6661: }
6662: } /* agedc > 0 */
6663: } /* end if */
6664: else if(s[m][i] !=9){ /* Standard case, age in fractional
6665: years but with the precision of a month */
6666: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
6667: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
6668: agev[m][i]=1;
6669: else if(agev[m][i] < *agemin){
6670: *agemin=agev[m][i];
6671: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
6672: }
6673: else if(agev[m][i] >*agemax){
6674: *agemax=agev[m][i];
6675: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
6676: }
6677: /*agev[m][i]=anint[m][i]-annais[i];*/
6678: /* agev[m][i] = age[i]+2*m;*/
6679: } /* en if 9*/
6680: else { /* =9 */
6681: /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
6682: agev[m][i]=1;
6683: s[m][i]=-1;
6684: }
6685: }
6686: else if(s[m][i]==0) /*= 0 Unknown */
6687: agev[m][i]=1;
6688: else{
6689: printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
6690: fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]);
6691: agev[m][i]=0;
6692: }
6693: } /* End for lastpass */
6694: }
6695:
6696: for (i=1; i<=imx; i++) {
6697: for(m=firstpass; (m<=lastpass); m++){
6698: if (s[m][i] > (nlstate+ndeath)) {
6699: (*nberr)++;
6700: 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);
6701: 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);
6702: return 1;
6703: }
6704: }
6705: }
6706:
6707: /*for (i=1; i<=imx; i++){
6708: for (m=firstpass; (m<lastpass); m++){
6709: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
6710: }
6711:
6712: }*/
6713:
6714:
6715: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6716: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
6717:
6718: return (0);
6719: /* endread:*/
6720: printf("Exiting calandcheckages: ");
6721: return (1);
6722: }
6723:
6724: #if defined(_MSC_VER)
6725: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6726: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
6727: //#include "stdafx.h"
6728: //#include <stdio.h>
6729: //#include <tchar.h>
6730: //#include <windows.h>
6731: //#include <iostream>
6732: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
6733:
6734: LPFN_ISWOW64PROCESS fnIsWow64Process;
6735:
6736: BOOL IsWow64()
6737: {
6738: BOOL bIsWow64 = FALSE;
6739:
6740: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
6741: // (HANDLE, PBOOL);
6742:
6743: //LPFN_ISWOW64PROCESS fnIsWow64Process;
6744:
6745: HMODULE module = GetModuleHandle(_T("kernel32"));
6746: const char funcName[] = "IsWow64Process";
6747: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
6748: GetProcAddress(module, funcName);
6749:
6750: if (NULL != fnIsWow64Process)
6751: {
6752: if (!fnIsWow64Process(GetCurrentProcess(),
6753: &bIsWow64))
6754: //throw std::exception("Unknown error");
6755: printf("Unknown error\n");
6756: }
6757: return bIsWow64 != FALSE;
6758: }
6759: #endif
6760:
6761: void syscompilerinfo(int logged)
6762: {
6763: /* #include "syscompilerinfo.h"*/
6764: /* command line Intel compiler 32bit windows, XP compatible:*/
6765: /* /GS /W3 /Gy
6766: /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
6767: "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
6768: "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
6769: /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
6770: */
6771: /* 64 bits */
6772: /*
6773: /GS /W3 /Gy
6774: /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
6775: /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
6776: /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
6777: "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
6778: /* Optimization are useless and O3 is slower than O2 */
6779: /*
6780: /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32"
6781: /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo
6782: /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel
6783: /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch"
6784: */
6785: /* Link is */ /* /OUT:"visual studio
6786: 2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
6787: /PDB:"visual studio
6788: 2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
6789: "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
6790: "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
6791: "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
6792: /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
6793: /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
6794: uiAccess='false'"
6795: /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
6796: /NOLOGO /TLBID:1
6797: */
6798: #if defined __INTEL_COMPILER
6799: #if defined(__GNUC__)
6800: struct utsname sysInfo; /* For Intel on Linux and OS/X */
6801: #endif
6802: #elif defined(__GNUC__)
6803: #ifndef __APPLE__
6804: #include <gnu/libc-version.h> /* Only on gnu */
6805: #endif
6806: struct utsname sysInfo;
6807: int cross = CROSS;
6808: if (cross){
6809: printf("Cross-");
6810: if(logged) fprintf(ficlog, "Cross-");
6811: }
6812: #endif
6813:
6814: #include <stdint.h>
6815:
6816: printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
6817: #if defined(__clang__)
6818: printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
6819: #endif
6820: #if defined(__ICC) || defined(__INTEL_COMPILER)
6821: printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
6822: #endif
6823: #if defined(__GNUC__) || defined(__GNUG__)
6824: printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
6825: #endif
6826: #if defined(__HP_cc) || defined(__HP_aCC)
6827: printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
6828: #endif
6829: #if defined(__IBMC__) || defined(__IBMCPP__)
6830: printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
6831: #endif
6832: #if defined(_MSC_VER)
6833: printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
6834: #endif
6835: #if defined(__PGI)
6836: printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
6837: #endif
6838: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
6839: printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
6840: #endif
6841: printf(" for "); if (logged) fprintf(ficlog, " for ");
6842:
6843: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
6844: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
6845: // Windows (x64 and x86)
6846: printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
6847: #elif __unix__ // all unices, not all compilers
6848: // Unix
6849: printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
6850: #elif __linux__
6851: // linux
6852: printf("linux ");if(logged) fprintf(ficlog,"linux ");
6853: #elif __APPLE__
6854: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
6855: printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
6856: #endif
6857:
6858: /* __MINGW32__ */
6859: /* __CYGWIN__ */
6860: /* __MINGW64__ */
6861: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
6862: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
6863: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
6864: /* _WIN64 // Defined for applications for Win64. */
6865: /* _M_X64 // Defined for compilations that target x64 processors. */
6866: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
6867:
6868: #if UINTPTR_MAX == 0xffffffff
6869: printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
6870: #elif UINTPTR_MAX == 0xffffffffffffffff
6871: printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
6872: #else
6873: printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
6874: #endif
6875:
6876: #if defined(__GNUC__)
6877: # if defined(__GNUC_PATCHLEVEL__)
6878: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6879: + __GNUC_MINOR__ * 100 \
6880: + __GNUC_PATCHLEVEL__)
6881: # else
6882: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
6883: + __GNUC_MINOR__ * 100)
6884: # endif
6885: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
6886: if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
6887:
6888: if (uname(&sysInfo) != -1) {
6889: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6890: if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
6891: }
6892: else
6893: perror("uname() error");
6894: //#ifndef __INTEL_COMPILER
6895: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
6896: printf("GNU libc version: %s\n", gnu_get_libc_version());
6897: if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
6898: #endif
6899: #endif
6900:
6901: // void main()
6902: // {
6903: #if defined(_MSC_VER)
6904: if (IsWow64()){
6905: printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6906: if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
6907: }
6908: else{
6909: printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6910: if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
6911: }
6912: // printf("\nPress Enter to continue...");
6913: // getchar();
6914: // }
6915:
6916: #endif
6917:
6918:
6919: }
6920:
6921: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
6922: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6923: int i, j, k, i1 ;
6924: /* double ftolpl = 1.e-10; */
6925: double age, agebase, agelim;
6926: double tot;
6927:
6928: strcpy(filerespl,"PL_");
6929: strcat(filerespl,fileresu);
6930: if((ficrespl=fopen(filerespl,"w"))==NULL) {
6931: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6932: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
6933: }
6934: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6935: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
6936: pstamp(ficrespl);
6937: fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
6938: fprintf(ficrespl,"#Age ");
6939: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
6940: fprintf(ficrespl,"\n");
6941:
6942: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
6943:
6944: agebase=ageminpar;
6945: agelim=agemaxpar;
6946:
6947: i1=pow(2,cptcoveff);
6948: if (cptcovn < 1){i1=1;}
6949:
6950: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6951: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
6952: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
6953: k=k+1;
6954: /* to clean */
6955: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
6956: fprintf(ficrespl,"#******");
6957: printf("#******");
6958: fprintf(ficlog,"#******");
6959: for(j=1;j<=cptcoveff;j++) {
6960: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6961: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6962: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6963: }
6964: fprintf(ficrespl,"******\n");
6965: printf("******\n");
6966: fprintf(ficlog,"******\n");
6967:
6968: fprintf(ficrespl,"#Age ");
6969: for(j=1;j<=cptcoveff;j++) {
6970: fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6971: }
6972: for(i=1; i<=nlstate;i++) fprintf(ficrespl," %d-%d ",i,i);
6973: fprintf(ficrespl,"Total Years_to_converge\n");
6974:
6975: for (age=agebase; age<=agelim; age++){
6976: /* for (age=agebase; age<=agebase; age++){ */
6977: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
6978: fprintf(ficrespl,"%.0f ",age );
6979: for(j=1;j<=cptcoveff;j++)
6980: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
6981: tot=0.;
6982: for(i=1; i<=nlstate;i++){
6983: tot += prlim[i][i];
6984: fprintf(ficrespl," %.5f", prlim[i][i]);
6985: }
6986: fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
6987: } /* Age */
6988: /* was end of cptcod */
6989: } /* cptcov */
6990: return 0;
6991: }
6992:
6993: int hPijx(double *p, int bage, int fage){
6994: /*------------- h Pij x at various ages ------------*/
6995:
6996: int stepsize;
6997: int agelim;
6998: int hstepm;
6999: int nhstepm;
7000: int h, i, i1, j, k;
7001:
7002: double agedeb;
7003: double ***p3mat;
7004:
7005: strcpy(filerespij,"PIJ_"); strcat(filerespij,fileresu);
7006: if((ficrespij=fopen(filerespij,"w"))==NULL) {
7007: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
7008: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
7009: }
7010: printf("Computing pij: result on file '%s' \n", filerespij);
7011: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
7012:
7013: stepsize=(int) (stepm+YEARM-1)/YEARM;
7014: /*if (stepm<=24) stepsize=2;*/
7015:
7016: agelim=AGESUP;
7017: hstepm=stepsize*YEARM; /* Every year of age */
7018: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
7019:
7020: /* hstepm=1; aff par mois*/
7021: pstamp(ficrespij);
7022: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
7023: i1= pow(2,cptcoveff);
7024: /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
7025: /* /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
7026: /* k=k+1; */
7027: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7028: fprintf(ficrespij,"\n#****** ");
7029: for(j=1;j<=cptcoveff;j++)
7030: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
7031: fprintf(ficrespij,"******\n");
7032:
7033: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
7034: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
7035: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
7036:
7037: /* nhstepm=nhstepm*YEARM; aff par mois*/
7038:
7039: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7040: oldm=oldms;savm=savms;
7041: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
7042: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
7043: for(i=1; i<=nlstate;i++)
7044: for(j=1; j<=nlstate+ndeath;j++)
7045: fprintf(ficrespij," %1d-%1d",i,j);
7046: fprintf(ficrespij,"\n");
7047: for (h=0; h<=nhstepm; h++){
7048: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
7049: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
7050: for(i=1; i<=nlstate;i++)
7051: for(j=1; j<=nlstate+ndeath;j++)
7052: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
7053: fprintf(ficrespij,"\n");
7054: }
7055: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
7056: fprintf(ficrespij,"\n");
7057: }
7058: /*}*/
7059: }
7060: return 0;
7061: }
7062:
7063:
7064: /***********************************************/
7065: /**************** Main Program *****************/
7066: /***********************************************/
7067:
7068: int main(int argc, char *argv[])
7069: {
7070: #ifdef GSL
7071: const gsl_multimin_fminimizer_type *T;
7072: size_t iteri = 0, it;
7073: int rval = GSL_CONTINUE;
7074: int status = GSL_SUCCESS;
7075: double ssval;
7076: #endif
7077: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
7078: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
7079: int ncvyear=0; /* Number of years needed for the period prevalence to converge */
7080: int jj, ll, li, lj, lk;
7081: int numlinepar=0; /* Current linenumber of parameter file */
7082: int num_filled;
7083: int itimes;
7084: int NDIM=2;
7085: int vpopbased=0;
7086:
7087: char ca[32], cb[32];
7088: /* FILE *fichtm; *//* Html File */
7089: /* FILE *ficgp;*/ /*Gnuplot File */
7090: struct stat info;
7091: double agedeb=0.;
7092:
7093: double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
7094:
7095: double fret;
7096: double dum=0.; /* Dummy variable */
7097: double ***p3mat;
7098: double ***mobaverage;
7099:
7100: char line[MAXLINE];
7101: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
7102:
7103: char model[MAXLINE], modeltemp[MAXLINE];
7104: char pathr[MAXLINE], pathimach[MAXLINE];
7105: char *tok, *val; /* pathtot */
7106: int firstobs=1, lastobs=10;
7107: int c, h , cpt, c2;
7108: int jl=0;
7109: int i1, j1, jk, stepsize=0;
7110: int count=0;
7111:
7112: int *tab;
7113: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
7114: int mobilav=0,popforecast=0;
7115: int hstepm=0, nhstepm=0;
7116: int agemortsup;
7117: float sumlpop=0.;
7118: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
7119: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
7120:
7121: double bage=0, fage=110., age, agelim=0., agebase=0.;
7122: double ftolpl=FTOL;
7123: double **prlim;
7124: double ***param; /* Matrix of parameters */
7125: double *p;
7126: double **matcov; /* Matrix of covariance */
7127: double **hess; /* Hessian matrix */
7128: double ***delti3; /* Scale */
7129: double *delti; /* Scale */
7130: double ***eij, ***vareij;
7131: double **varpl; /* Variances of prevalence limits by age */
7132: double *epj, vepp;
7133:
7134: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
7135: double **ximort;
7136: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
7137: int *dcwave;
7138:
7139: char z[1]="c";
7140:
7141: /*char *strt;*/
7142: char strtend[80];
7143:
7144:
7145: /* setlocale (LC_ALL, ""); */
7146: /* bindtextdomain (PACKAGE, LOCALEDIR); */
7147: /* textdomain (PACKAGE); */
7148: /* setlocale (LC_CTYPE, ""); */
7149: /* setlocale (LC_MESSAGES, ""); */
7150:
7151: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
7152: rstart_time = time(NULL);
7153: /* (void) gettimeofday(&start_time,&tzp);*/
7154: start_time = *localtime(&rstart_time);
7155: curr_time=start_time;
7156: /*tml = *localtime(&start_time.tm_sec);*/
7157: /* strcpy(strstart,asctime(&tml)); */
7158: strcpy(strstart,asctime(&start_time));
7159:
7160: /* printf("Localtime (at start)=%s",strstart); */
7161: /* tp.tm_sec = tp.tm_sec +86400; */
7162: /* tm = *localtime(&start_time.tm_sec); */
7163: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
7164: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
7165: /* tmg.tm_hour=tmg.tm_hour + 1; */
7166: /* tp.tm_sec = mktime(&tmg); */
7167: /* strt=asctime(&tmg); */
7168: /* printf("Time(after) =%s",strstart); */
7169: /* (void) time (&time_value);
7170: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
7171: * tm = *localtime(&time_value);
7172: * strstart=asctime(&tm);
7173: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
7174: */
7175:
7176: nberr=0; /* Number of errors and warnings */
7177: nbwarn=0;
7178: #ifdef WIN32
7179: _getcwd(pathcd, size);
7180: #else
7181: getcwd(pathcd, size);
7182: #endif
7183: syscompilerinfo(0);
7184: printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
7185: if(argc <=1){
7186: printf("\nEnter the parameter file name: ");
7187: if(!fgets(pathr,FILENAMELENGTH,stdin)){
7188: printf("ERROR Empty parameter file name\n");
7189: goto end;
7190: }
7191: i=strlen(pathr);
7192: if(pathr[i-1]=='\n')
7193: pathr[i-1]='\0';
7194: i=strlen(pathr);
7195: if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
7196: pathr[i-1]='\0';
7197: }
7198: i=strlen(pathr);
7199: if( i==0 ){
7200: printf("ERROR Empty parameter file name\n");
7201: goto end;
7202: }
7203: for (tok = pathr; tok != NULL; ){
7204: printf("Pathr |%s|\n",pathr);
7205: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
7206: printf("val= |%s| pathr=%s\n",val,pathr);
7207: strcpy (pathtot, val);
7208: if(pathr[0] == '\0') break; /* Dirty */
7209: }
7210: }
7211: else{
7212: strcpy(pathtot,argv[1]);
7213: }
7214: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
7215: /*cygwin_split_path(pathtot,path,optionfile);
7216: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
7217: /* cutv(path,optionfile,pathtot,'\\');*/
7218:
7219: /* Split argv[0], imach program to get pathimach */
7220: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
7221: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7222: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
7223: /* strcpy(pathimach,argv[0]); */
7224: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
7225: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
7226: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
7227: #ifdef WIN32
7228: _chdir(path); /* Can be a relative path */
7229: if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
7230: #else
7231: chdir(path); /* Can be a relative path */
7232: if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
7233: #endif
7234: printf("Current directory %s!\n",pathcd);
7235: strcpy(command,"mkdir ");
7236: strcat(command,optionfilefiname);
7237: if((outcmd=system(command)) != 0){
7238: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
7239: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
7240: /* fclose(ficlog); */
7241: /* exit(1); */
7242: }
7243: /* if((imk=mkdir(optionfilefiname))<0){ */
7244: /* perror("mkdir"); */
7245: /* } */
7246:
7247: /*-------- arguments in the command line --------*/
7248:
7249: /* Main Log file */
7250: strcat(filelog, optionfilefiname);
7251: strcat(filelog,".log"); /* */
7252: if((ficlog=fopen(filelog,"w"))==NULL) {
7253: printf("Problem with logfile %s\n",filelog);
7254: goto end;
7255: }
7256: fprintf(ficlog,"Log filename:%s\n",filelog);
7257: fprintf(ficlog,"Version %s %s",version,fullversion);
7258: fprintf(ficlog,"\nEnter the parameter file name: \n");
7259: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
7260: path=%s \n\
7261: optionfile=%s\n\
7262: optionfilext=%s\n\
7263: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
7264:
7265: syscompilerinfo(1);
7266:
7267: printf("Local time (at start):%s",strstart);
7268: fprintf(ficlog,"Local time (at start): %s",strstart);
7269: fflush(ficlog);
7270: /* (void) gettimeofday(&curr_time,&tzp); */
7271: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
7272:
7273: /* */
7274: strcpy(fileres,"r");
7275: strcat(fileres, optionfilefiname);
7276: strcat(fileresu, optionfilefiname); /* Without r in front */
7277: strcat(fileres,".txt"); /* Other files have txt extension */
7278: strcat(fileresu,".txt"); /* Other files have txt extension */
7279:
7280: /* Main ---------arguments file --------*/
7281:
7282: if((ficpar=fopen(optionfile,"r"))==NULL) {
7283: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7284: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
7285: fflush(ficlog);
7286: /* goto end; */
7287: exit(70);
7288: }
7289:
7290:
7291:
7292: strcpy(filereso,"o");
7293: strcat(filereso,fileresu);
7294: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
7295: printf("Problem with Output resultfile: %s\n", filereso);
7296: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
7297: fflush(ficlog);
7298: goto end;
7299: }
7300:
7301: /* Reads comments: lines beginning with '#' */
7302: numlinepar=0;
7303:
7304: /* First parameter line */
7305: while(fgets(line, MAXLINE, ficpar)) {
7306: /* If line starts with a # it is a comment */
7307: if (line[0] == '#') {
7308: numlinepar++;
7309: fputs(line,stdout);
7310: fputs(line,ficparo);
7311: fputs(line,ficlog);
7312: continue;
7313: }else
7314: break;
7315: }
7316: if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
7317: title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
7318: if (num_filled != 5) {
7319: printf("Should be 5 parameters\n");
7320: }
7321: numlinepar++;
7322: printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
7323: }
7324: /* Second parameter line */
7325: while(fgets(line, MAXLINE, ficpar)) {
7326: /* If line starts with a # it is a comment */
7327: if (line[0] == '#') {
7328: numlinepar++;
7329: fputs(line,stdout);
7330: fputs(line,ficparo);
7331: fputs(line,ficlog);
7332: continue;
7333: }else
7334: break;
7335: }
7336: if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
7337: &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
7338: if (num_filled != 8) {
7339: 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");
7340: printf("but line=%s\n",line);
7341: }
7342: 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);
7343: }
7344: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
7345: /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
7346: /* Third parameter line */
7347: while(fgets(line, MAXLINE, ficpar)) {
7348: /* If line starts with a # it is a comment */
7349: if (line[0] == '#') {
7350: numlinepar++;
7351: fputs(line,stdout);
7352: fputs(line,ficparo);
7353: fputs(line,ficlog);
7354: continue;
7355: }else
7356: break;
7357: }
7358: if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
7359: if (num_filled == 0)
7360: model[0]='\0';
7361: else if (num_filled != 1){
7362: printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7363: fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
7364: model[0]='\0';
7365: goto end;
7366: }
7367: else{
7368: if (model[0]=='+'){
7369: for(i=1; i<=strlen(model);i++)
7370: modeltemp[i-1]=model[i];
7371: strcpy(model,modeltemp);
7372: }
7373: }
7374: /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
7375: printf("model=1+age+%s\n",model);fflush(stdout);
7376: }
7377: /* 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); */
7378: /* numlinepar=numlinepar+3; /\* In general *\/ */
7379: /* 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); */
7380: 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);
7381: 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);
7382: fflush(ficlog);
7383: /* if(model[0]=='#'|| model[0]== '\0'){ */
7384: if(model[0]=='#'){
7385: printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
7386: 'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
7387: 'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n"); \
7388: if(mle != -1){
7389: printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
7390: exit(1);
7391: }
7392: }
7393: while((c=getc(ficpar))=='#' && c!= EOF){
7394: ungetc(c,ficpar);
7395: fgets(line, MAXLINE, ficpar);
7396: numlinepar++;
7397: if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
7398: z[0]=line[1];
7399: }
7400: /* printf("****line [1] = %c \n",line[1]); */
7401: fputs(line, stdout);
7402: //puts(line);
7403: fputs(line,ficparo);
7404: fputs(line,ficlog);
7405: }
7406: ungetc(c,ficpar);
7407:
7408:
7409: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
7410: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
7411: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
7412: v1+v2*age+v2*v3 makes cptcovn = 3
7413: */
7414: if (strlen(model)>1)
7415: 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*/
7416: else
7417: ncovmodel=2; /* Constant and age */
7418: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
7419: npar= nforce*ncovmodel; /* Number of parameters like aij*/
7420: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
7421: 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);
7422: 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);
7423: fflush(stdout);
7424: fclose (ficlog);
7425: goto end;
7426: }
7427: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7428: delti=delti3[1][1];
7429: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
7430: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
7431: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7432: printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7433: fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
7434: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7435: fclose (ficparo);
7436: fclose (ficlog);
7437: goto end;
7438: exit(0);
7439: }
7440: else if(mle==-3) { /* Main Wizard */
7441: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
7442: printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7443: fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
7444: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7445: matcov=matrix(1,npar,1,npar);
7446: hess=matrix(1,npar,1,npar);
7447: }
7448: else{
7449: /* Read guessed parameters */
7450: /* Reads comments: lines beginning with '#' */
7451: while((c=getc(ficpar))=='#' && c!= EOF){
7452: ungetc(c,ficpar);
7453: fgets(line, MAXLINE, ficpar);
7454: numlinepar++;
7455: fputs(line,stdout);
7456: fputs(line,ficparo);
7457: fputs(line,ficlog);
7458: }
7459: ungetc(c,ficpar);
7460:
7461: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
7462: for(i=1; i <=nlstate; i++){
7463: j=0;
7464: for(jj=1; jj <=nlstate+ndeath; jj++){
7465: if(jj==i) continue;
7466: j++;
7467: fscanf(ficpar,"%1d%1d",&i1,&j1);
7468: if ((i1 != i) || (j1 != jj)){
7469: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
7470: It might be a problem of design; if ncovcol and the model are correct\n \
7471: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
7472: exit(1);
7473: }
7474: fprintf(ficparo,"%1d%1d",i1,j1);
7475: if(mle==1)
7476: printf("%1d%1d",i,jj);
7477: fprintf(ficlog,"%1d%1d",i,jj);
7478: for(k=1; k<=ncovmodel;k++){
7479: fscanf(ficpar," %lf",¶m[i][j][k]);
7480: if(mle==1){
7481: printf(" %lf",param[i][j][k]);
7482: fprintf(ficlog," %lf",param[i][j][k]);
7483: }
7484: else
7485: fprintf(ficlog," %lf",param[i][j][k]);
7486: fprintf(ficparo," %lf",param[i][j][k]);
7487: }
7488: fscanf(ficpar,"\n");
7489: numlinepar++;
7490: if(mle==1)
7491: printf("\n");
7492: fprintf(ficlog,"\n");
7493: fprintf(ficparo,"\n");
7494: }
7495: }
7496: fflush(ficlog);
7497:
7498: /* Reads scales values */
7499: p=param[1][1];
7500:
7501: /* Reads comments: lines beginning with '#' */
7502: while((c=getc(ficpar))=='#' && c!= EOF){
7503: ungetc(c,ficpar);
7504: fgets(line, MAXLINE, ficpar);
7505: numlinepar++;
7506: fputs(line,stdout);
7507: fputs(line,ficparo);
7508: fputs(line,ficlog);
7509: }
7510: ungetc(c,ficpar);
7511:
7512: for(i=1; i <=nlstate; i++){
7513: for(j=1; j <=nlstate+ndeath-1; j++){
7514: fscanf(ficpar,"%1d%1d",&i1,&j1);
7515: if ( (i1-i) * (j1-j) != 0){
7516: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
7517: exit(1);
7518: }
7519: printf("%1d%1d",i,j);
7520: fprintf(ficparo,"%1d%1d",i1,j1);
7521: fprintf(ficlog,"%1d%1d",i1,j1);
7522: for(k=1; k<=ncovmodel;k++){
7523: fscanf(ficpar,"%le",&delti3[i][j][k]);
7524: printf(" %le",delti3[i][j][k]);
7525: fprintf(ficparo," %le",delti3[i][j][k]);
7526: fprintf(ficlog," %le",delti3[i][j][k]);
7527: }
7528: fscanf(ficpar,"\n");
7529: numlinepar++;
7530: printf("\n");
7531: fprintf(ficparo,"\n");
7532: fprintf(ficlog,"\n");
7533: }
7534: }
7535: fflush(ficlog);
7536:
7537: /* Reads covariance matrix */
7538: delti=delti3[1][1];
7539:
7540:
7541: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
7542:
7543: /* Reads comments: lines beginning with '#' */
7544: while((c=getc(ficpar))=='#' && c!= EOF){
7545: ungetc(c,ficpar);
7546: fgets(line, MAXLINE, ficpar);
7547: numlinepar++;
7548: fputs(line,stdout);
7549: fputs(line,ficparo);
7550: fputs(line,ficlog);
7551: }
7552: ungetc(c,ficpar);
7553:
7554: matcov=matrix(1,npar,1,npar);
7555: hess=matrix(1,npar,1,npar);
7556: for(i=1; i <=npar; i++)
7557: for(j=1; j <=npar; j++) matcov[i][j]=0.;
7558:
7559: /* Scans npar lines */
7560: for(i=1; i <=npar; i++){
7561: count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
7562: if(count != 3){
7563: printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7564: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7565: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7566: fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
7567: This is probably because your covariance matrix doesn't \n contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
7568: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
7569: exit(1);
7570: }else
7571: if(mle==1)
7572: printf("%1d%1d%1d",i1,j1,jk);
7573: fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
7574: fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
7575: for(j=1; j <=i; j++){
7576: fscanf(ficpar," %le",&matcov[i][j]);
7577: if(mle==1){
7578: printf(" %.5le",matcov[i][j]);
7579: }
7580: fprintf(ficlog," %.5le",matcov[i][j]);
7581: fprintf(ficparo," %.5le",matcov[i][j]);
7582: }
7583: fscanf(ficpar,"\n");
7584: numlinepar++;
7585: if(mle==1)
7586: printf("\n");
7587: fprintf(ficlog,"\n");
7588: fprintf(ficparo,"\n");
7589: }
7590: /* End of read covariance matrix npar lines */
7591: for(i=1; i <=npar; i++)
7592: for(j=i+1;j<=npar;j++)
7593: matcov[i][j]=matcov[j][i];
7594:
7595: if(mle==1)
7596: printf("\n");
7597: fprintf(ficlog,"\n");
7598:
7599: fflush(ficlog);
7600:
7601: /*-------- Rewriting parameter file ----------*/
7602: strcpy(rfileres,"r"); /* "Rparameterfile */
7603: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
7604: strcat(rfileres,"."); /* */
7605: strcat(rfileres,optionfilext); /* Other files have txt extension */
7606: if((ficres =fopen(rfileres,"w"))==NULL) {
7607: printf("Problem writing new parameter file: %s\n", rfileres);goto end;
7608: fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
7609: }
7610: fprintf(ficres,"#%s\n",version);
7611: } /* End of mle != -3 */
7612:
7613: /* Main data
7614: */
7615: n= lastobs;
7616: num=lvector(1,n);
7617: moisnais=vector(1,n);
7618: annais=vector(1,n);
7619: moisdc=vector(1,n);
7620: andc=vector(1,n);
7621: agedc=vector(1,n);
7622: cod=ivector(1,n);
7623: weight=vector(1,n);
7624: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
7625: mint=matrix(1,maxwav,1,n);
7626: anint=matrix(1,maxwav,1,n);
7627: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
7628: tab=ivector(1,NCOVMAX);
7629: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7630: ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
7631:
7632: /* Reads data from file datafile */
7633: if (readdata(datafile, firstobs, lastobs, &imx)==1)
7634: goto end;
7635:
7636: /* Calculation of the number of parameters from char model */
7637: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
7638: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
7639: k=3 V4 Tvar[k=3]= 4 (from V4)
7640: k=2 V1 Tvar[k=2]= 1 (from V1)
7641: k=1 Tvar[1]=2 (from V2)
7642: */
7643: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
7644: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
7645: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
7646: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
7647: */
7648: /* For model-covariate k tells which data-covariate to use but
7649: because this model-covariate is a construction we invent a new column
7650: ncovcol + k1
7651: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
7652: Tvar[3=V1*V4]=4+1 etc */
7653: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
7654: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
7655: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
7656: */
7657: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
7658: 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
7659: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
7660: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
7661: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
7662: 4 covariates (3 plus signs)
7663: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
7664: */
7665:
7666: /* Main decodemodel */
7667:
7668:
7669: if(decodemodel(model, lastobs) == 1)
7670: goto end;
7671:
7672: if((double)(lastobs-imx)/(double)imx > 1.10){
7673: nbwarn++;
7674: 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);
7675: 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);
7676: }
7677: /* if(mle==1){*/
7678: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
7679: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
7680: }
7681:
7682: /*-calculation of age at interview from date of interview and age at death -*/
7683: agev=matrix(1,maxwav,1,imx);
7684:
7685: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
7686: goto end;
7687:
7688:
7689: agegomp=(int)agemin;
7690: free_vector(moisnais,1,n);
7691: free_vector(annais,1,n);
7692: /* free_matrix(mint,1,maxwav,1,n);
7693: free_matrix(anint,1,maxwav,1,n);*/
7694: /* free_vector(moisdc,1,n); */
7695: /* free_vector(andc,1,n); */
7696: /* */
7697:
7698: wav=ivector(1,imx);
7699: /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
7700: /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
7701: /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
7702: dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
7703: bh=imatrix(1,lastpass-firstpass+2,1,imx);
7704: mw=imatrix(1,lastpass-firstpass+2,1,imx);
7705:
7706: /* Concatenates waves */
7707: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
7708: Death is a valid wave (if date is known).
7709: mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
7710: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
7711: and mw[mi+1][i]. dh depends on stepm.
7712: */
7713:
7714: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
7715: /* */
7716:
7717: free_vector(moisdc,1,n);
7718: free_vector(andc,1,n);
7719:
7720: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
7721:
7722: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
7723: ncodemax[1]=1;
7724: Ndum =ivector(-1,NCOVMAX);
7725: if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
7726: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
7727: /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
7728: V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
7729: /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
7730:
7731: /* codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
7732: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
7733: /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
7734: /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j,
7735: * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded
7736: * (currently 0 or 1) in the data.
7737: * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of
7738: * corresponding modality (h,j).
7739: */
7740:
7741: h=0;
7742:
7743:
7744: /*if (cptcovn > 0) */
7745:
7746:
7747: m=pow(2,cptcoveff);
7748:
7749: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
7750: * For k=4 covariates, h goes from 1 to m=2**k
7751: * codtabm(h,k)= (1 & (h-1) >> (k-1)) + 1;
7752: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7753: * h\k 1 2 3 4
7754: *______________________________
7755: * 1 i=1 1 i=1 1 i=1 1 i=1 1
7756: * 2 2 1 1 1
7757: * 3 i=2 1 2 1 1
7758: * 4 2 2 1 1
7759: * 5 i=3 1 i=2 1 2 1
7760: * 6 2 1 2 1
7761: * 7 i=4 1 2 2 1
7762: * 8 2 2 2 1
7763: * 9 i=5 1 i=3 1 i=2 1 2
7764: * 10 2 1 1 2
7765: * 11 i=6 1 2 1 2
7766: * 12 2 2 1 2
7767: * 13 i=7 1 i=4 1 2 2
7768: * 14 2 1 2 2
7769: * 15 i=8 1 2 2 2
7770: * 16 2 2 2 2
7771: */
7772: /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
7773: /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
7774: * and the value of each covariate?
7775: * V1=1, V2=1, V3=2, V4=1 ?
7776: * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
7777: * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
7778: * In order to get the real value in the data, we use nbcode
7779: * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
7780: * We are keeping this crazy system in order to be able (in the future?)
7781: * to have more than 2 values (0 or 1) for a covariate.
7782: * #define codtabm(h,k) (1 & (h-1) >> (k-1))+1
7783: * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
7784: * bbbbbbbb
7785: * 76543210
7786: * h-1 00000101 (6-1=5)
7787: *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
7788: * &
7789: * 1 00000001 (1)
7790: * 00000001 = 1 & ((h-1) >> (k-1))
7791: * +1= 00000010 =2
7792: *
7793: * h=14, k=3 => h'=h-1=13, k'=k-1=2
7794: * h' 1101 =2^3+2^2+0x2^1+2^0
7795: * >>k' 11
7796: * & 00000001
7797: * = 00000001
7798: * +1 = 00000010=2 = codtabm(14,3)
7799: * Reverse h=6 and m=16?
7800: * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
7801: * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
7802: * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1
7803: * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
7804: * V3=decodtabm(14,3,2**4)=2
7805: * h'=13 1101 =2^3+2^2+0x2^1+2^0
7806: *(h-1) >> (j-1) 0011 =13 >> 2
7807: * &1 000000001
7808: * = 000000001
7809: * +1= 000000010 =2
7810: * 2211
7811: * V1=1+1, V2=0+1, V3=1+1, V4=1+1
7812: * V3=2
7813: */
7814:
7815: /* /\* for(h=1; h <=100 ;h++){ *\/ */
7816: /* /\* printf("h=%2d ", h); *\/ */
7817: /* /\* for(k=1; k <=10; k++){ *\/ */
7818: /* /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
7819: /* /\* codtab[h][k]=codtabm(h,k); *\/ */
7820: /* /\* } *\/ */
7821: /* /\* printf("\n"); *\/ */
7822: /* } */
7823: /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
7824: /* 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 *\/ */
7825: /* for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
7826: /* for(cpt=1; cpt <=pow(2,k-1); cpt++){ /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/ */
7827: /* h++; */
7828: /* if (h>m) */
7829: /* h=1; */
7830: /* codtab[h][k]=j; */
7831: /* /\* codtab[12][3]=1; *\/ */
7832: /* /\*codtab[h][Tvar[k]]=j;*\/ */
7833: /* /\* 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]]); *\/ */
7834: /* } */
7835: /* } */
7836: /* } */
7837: /* } */
7838: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
7839: codtab[1][2]=1;codtab[2][2]=2; */
7840: /* for(i=1; i <=m ;i++){ */
7841: /* for(k=1; k <=cptcovn; k++){ */
7842: /* printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
7843: /* } */
7844: /* printf("\n"); */
7845: /* } */
7846: /* scanf("%d",i);*/
7847:
7848: free_ivector(Ndum,-1,NCOVMAX);
7849:
7850:
7851:
7852: /* Initialisation of ----------- gnuplot -------------*/
7853: strcpy(optionfilegnuplot,optionfilefiname);
7854: if(mle==-3)
7855: strcat(optionfilegnuplot,"-MORT_");
7856: strcat(optionfilegnuplot,".gp");
7857:
7858: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
7859: printf("Problem with file %s",optionfilegnuplot);
7860: }
7861: else{
7862: fprintf(ficgp,"\n# IMaCh-%s\n", version);
7863: fprintf(ficgp,"# %s\n", optionfilegnuplot);
7864: //fprintf(ficgp,"set missing 'NaNq'\n");
7865: fprintf(ficgp,"set datafile missing 'NaNq'\n");
7866: }
7867: /* fclose(ficgp);*/
7868:
7869:
7870: /* Initialisation of --------- index.htm --------*/
7871:
7872: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
7873: if(mle==-3)
7874: strcat(optionfilehtm,"-MORT_");
7875: strcat(optionfilehtm,".htm");
7876: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
7877: printf("Problem with %s \n",optionfilehtm);
7878: exit(0);
7879: }
7880:
7881: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
7882: strcat(optionfilehtmcov,"-cov.htm");
7883: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
7884: printf("Problem with %s \n",optionfilehtmcov), exit(0);
7885: }
7886: else{
7887: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
7888: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7889: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
7890: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
7891: }
7892:
7893: fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C) 2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \
7894: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7895: <font size=\"2\">IMaCh-%s <br> %s</font> \
7896: <hr size=\"2\" color=\"#EC5E5E\"> \n\
7897: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
7898: \n\
7899: <hr size=\"2\" color=\"#EC5E5E\">\
7900: <ul><li><h4>Parameter files</h4>\n\
7901: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
7902: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
7903: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
7904: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
7905: - Date and time at start: %s</ul>\n",\
7906: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
7907: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
7908: fileres,fileres,\
7909: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
7910: fflush(fichtm);
7911:
7912: strcpy(pathr,path);
7913: strcat(pathr,optionfilefiname);
7914: #ifdef WIN32
7915: _chdir(optionfilefiname); /* Move to directory named optionfile */
7916: #else
7917: chdir(optionfilefiname); /* Move to directory named optionfile */
7918: #endif
7919:
7920:
7921: /* Calculates basic frequencies. Computes observed prevalence at single age
7922: and prints on file fileres'p'. */
7923: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
7924: firstpass, lastpass, stepm, weightopt, model);
7925:
7926: fprintf(fichtm,"\n");
7927: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
7928: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
7929: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
7930: imx,agemin,agemax,jmin,jmax,jmean);
7931: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7932: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7933: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7934: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
7935: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
7936:
7937:
7938: /* For Powell, parameters are in a vector p[] starting at p[1]
7939: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
7940: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
7941:
7942: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
7943: /* For mortality only */
7944: if (mle==-3){
7945: ximort=matrix(1,NDIM,1,NDIM);
7946: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
7947: cens=ivector(1,n);
7948: ageexmed=vector(1,n);
7949: agecens=vector(1,n);
7950: dcwave=ivector(1,n);
7951:
7952: for (i=1; i<=imx; i++){
7953: dcwave[i]=-1;
7954: for (m=firstpass; m<=lastpass; m++)
7955: if (s[m][i]>nlstate) {
7956: dcwave[i]=m;
7957: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
7958: break;
7959: }
7960: }
7961:
7962: for (i=1; i<=imx; i++) {
7963: if (wav[i]>0){
7964: ageexmed[i]=agev[mw[1][i]][i];
7965: j=wav[i];
7966: agecens[i]=1.;
7967:
7968: if (ageexmed[i]> 1 && wav[i] > 0){
7969: agecens[i]=agev[mw[j][i]][i];
7970: cens[i]= 1;
7971: }else if (ageexmed[i]< 1)
7972: cens[i]= -1;
7973: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
7974: cens[i]=0 ;
7975: }
7976: else cens[i]=-1;
7977: }
7978:
7979: for (i=1;i<=NDIM;i++) {
7980: for (j=1;j<=NDIM;j++)
7981: ximort[i][j]=(i == j ? 1.0 : 0.0);
7982: }
7983:
7984: /*p[1]=0.0268; p[NDIM]=0.083;*/
7985: /*printf("%lf %lf", p[1], p[2]);*/
7986:
7987:
7988: #ifdef GSL
7989: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
7990: #else
7991: printf("Powell\n"); fprintf(ficlog,"Powell\n");
7992: #endif
7993: strcpy(filerespow,"POW-MORT_");
7994: strcat(filerespow,fileresu);
7995: if((ficrespow=fopen(filerespow,"w"))==NULL) {
7996: printf("Problem with resultfile: %s\n", filerespow);
7997: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
7998: }
7999: #ifdef GSL
8000: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
8001: #else
8002: fprintf(ficrespow,"# Powell\n# iter -2*LL");
8003: #endif
8004: /* for (i=1;i<=nlstate;i++)
8005: for(j=1;j<=nlstate+ndeath;j++)
8006: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
8007: */
8008: fprintf(ficrespow,"\n");
8009: #ifdef GSL
8010: /* gsl starts here */
8011: T = gsl_multimin_fminimizer_nmsimplex;
8012: gsl_multimin_fminimizer *sfm = NULL;
8013: gsl_vector *ss, *x;
8014: gsl_multimin_function minex_func;
8015:
8016: /* Initial vertex size vector */
8017: ss = gsl_vector_alloc (NDIM);
8018:
8019: if (ss == NULL){
8020: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
8021: }
8022: /* Set all step sizes to 1 */
8023: gsl_vector_set_all (ss, 0.001);
8024:
8025: /* Starting point */
8026:
8027: x = gsl_vector_alloc (NDIM);
8028:
8029: if (x == NULL){
8030: gsl_vector_free(ss);
8031: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
8032: }
8033:
8034: /* Initialize method and iterate */
8035: /* p[1]=0.0268; p[NDIM]=0.083; */
8036: /* gsl_vector_set(x, 0, 0.0268); */
8037: /* gsl_vector_set(x, 1, 0.083); */
8038: gsl_vector_set(x, 0, p[1]);
8039: gsl_vector_set(x, 1, p[2]);
8040:
8041: minex_func.f = &gompertz_f;
8042: minex_func.n = NDIM;
8043: minex_func.params = (void *)&p; /* ??? */
8044:
8045: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
8046: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
8047:
8048: printf("Iterations beginning .....\n\n");
8049: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
8050:
8051: iteri=0;
8052: while (rval == GSL_CONTINUE){
8053: iteri++;
8054: status = gsl_multimin_fminimizer_iterate(sfm);
8055:
8056: if (status) printf("error: %s\n", gsl_strerror (status));
8057: fflush(0);
8058:
8059: if (status)
8060: break;
8061:
8062: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
8063: ssval = gsl_multimin_fminimizer_size (sfm);
8064:
8065: if (rval == GSL_SUCCESS)
8066: printf ("converged to a local maximum at\n");
8067:
8068: printf("%5d ", iteri);
8069: for (it = 0; it < NDIM; it++){
8070: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
8071: }
8072: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
8073: }
8074:
8075: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
8076:
8077: gsl_vector_free(x); /* initial values */
8078: gsl_vector_free(ss); /* inital step size */
8079: for (it=0; it<NDIM; it++){
8080: p[it+1]=gsl_vector_get(sfm->x,it);
8081: fprintf(ficrespow," %.12lf", p[it]);
8082: }
8083: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
8084: #endif
8085: #ifdef POWELL
8086: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
8087: #endif
8088: fclose(ficrespow);
8089:
8090: hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz);
8091:
8092: for(i=1; i <=NDIM; i++)
8093: for(j=i+1;j<=NDIM;j++)
8094: matcov[i][j]=matcov[j][i];
8095:
8096: printf("\nCovariance matrix\n ");
8097: fprintf(ficlog,"\nCovariance matrix\n ");
8098: for(i=1; i <=NDIM; i++) {
8099: for(j=1;j<=NDIM;j++){
8100: printf("%f ",matcov[i][j]);
8101: fprintf(ficlog,"%f ",matcov[i][j]);
8102: }
8103: printf("\n "); fprintf(ficlog,"\n ");
8104: }
8105:
8106: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
8107: for (i=1;i<=NDIM;i++) {
8108: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
8109: fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
8110: }
8111: lsurv=vector(1,AGESUP);
8112: lpop=vector(1,AGESUP);
8113: tpop=vector(1,AGESUP);
8114: lsurv[agegomp]=100000;
8115:
8116: for (k=agegomp;k<=AGESUP;k++) {
8117: agemortsup=k;
8118: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
8119: }
8120:
8121: for (k=agegomp;k<agemortsup;k++)
8122: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
8123:
8124: for (k=agegomp;k<agemortsup;k++){
8125: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
8126: sumlpop=sumlpop+lpop[k];
8127: }
8128:
8129: tpop[agegomp]=sumlpop;
8130: for (k=agegomp;k<(agemortsup-3);k++){
8131: /* tpop[k+1]=2;*/
8132: tpop[k+1]=tpop[k]-lpop[k];
8133: }
8134:
8135:
8136: printf("\nAge lx qx dx Lx Tx e(x)\n");
8137: for (k=agegomp;k<(agemortsup-2);k++)
8138: 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]);
8139:
8140:
8141: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8142: if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
8143: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8144: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8145: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8146: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8147: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8148: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8149: }else
8150: printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
8151: printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
8152: stepm, weightopt,\
8153: model,imx,p,matcov,agemortsup);
8154:
8155: free_vector(lsurv,1,AGESUP);
8156: free_vector(lpop,1,AGESUP);
8157: free_vector(tpop,1,AGESUP);
8158: #ifdef GSL
8159: free_ivector(cens,1,n);
8160: free_vector(agecens,1,n);
8161: free_ivector(dcwave,1,n);
8162: free_matrix(ximort,1,NDIM,1,NDIM);
8163: #endif
8164: } /* Endof if mle==-3 mortality only */
8165: /* Standard */
8166: else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
8167: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8168: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8169: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8170: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8171: for (k=1; k<=npar;k++)
8172: printf(" %d %8.5f",k,p[k]);
8173: printf("\n");
8174: if(mle>=1){ /* Could be 1 or 2, Real Maximization */
8175: /* mlikeli uses func not funcone */
8176: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
8177: }
8178: if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
8179: globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
8180: /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
8181: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8182: }
8183: globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
8184: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
8185: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
8186: for (k=1; k<=npar;k++)
8187: printf(" %d %8.5f",k,p[k]);
8188: printf("\n");
8189:
8190: /*--------- results files --------------*/
8191: 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);
8192:
8193:
8194: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8195: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8196: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
8197: for(i=1,jk=1; i <=nlstate; i++){
8198: for(k=1; k <=(nlstate+ndeath); k++){
8199: if (k != i) {
8200: printf("%d%d ",i,k);
8201: fprintf(ficlog,"%d%d ",i,k);
8202: fprintf(ficres,"%1d%1d ",i,k);
8203: for(j=1; j <=ncovmodel; j++){
8204: printf("%12.7f ",p[jk]);
8205: fprintf(ficlog,"%12.7f ",p[jk]);
8206: fprintf(ficres,"%12.7f ",p[jk]);
8207: jk++;
8208: }
8209: printf("\n");
8210: fprintf(ficlog,"\n");
8211: fprintf(ficres,"\n");
8212: }
8213: }
8214: }
8215: if(mle != 0){
8216: /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
8217: ftolhess=ftol; /* Usually correct */
8218: hesscov(matcov, hess, p, npar, delti, ftolhess, func);
8219: 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");
8220: 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");
8221: for(i=1,jk=1; i <=nlstate; i++){
8222: for(k=1; k <=(nlstate+ndeath); k++){
8223: if (k != i) {
8224: printf("%d%d ",i,k);
8225: fprintf(ficlog,"%d%d ",i,k);
8226: for(j=1; j <=ncovmodel; j++){
8227: 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]));
8228: 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]));
8229: jk++;
8230: }
8231: printf("\n");
8232: fprintf(ficlog,"\n");
8233: }
8234: }
8235: }
8236: } /* end of hesscov and Wald tests */
8237:
8238: /* */
8239: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
8240: printf("# Scales (for hessian or gradient estimation)\n");
8241: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
8242: for(i=1,jk=1; i <=nlstate; i++){
8243: for(j=1; j <=nlstate+ndeath; j++){
8244: if (j!=i) {
8245: fprintf(ficres,"%1d%1d",i,j);
8246: printf("%1d%1d",i,j);
8247: fprintf(ficlog,"%1d%1d",i,j);
8248: for(k=1; k<=ncovmodel;k++){
8249: printf(" %.5e",delti[jk]);
8250: fprintf(ficlog," %.5e",delti[jk]);
8251: fprintf(ficres," %.5e",delti[jk]);
8252: jk++;
8253: }
8254: printf("\n");
8255: fprintf(ficlog,"\n");
8256: fprintf(ficres,"\n");
8257: }
8258: }
8259: }
8260:
8261: 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");
8262: if(mle >= 1) /* To big for the screen */
8263: 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");
8264: 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");
8265: /* # 121 Var(a12)\n\ */
8266: /* # 122 Cov(b12,a12) Var(b12)\n\ */
8267: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
8268: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
8269: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
8270: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
8271: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
8272: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
8273:
8274:
8275: /* Just to have a covariance matrix which will be more understandable
8276: even is we still don't want to manage dictionary of variables
8277: */
8278: for(itimes=1;itimes<=2;itimes++){
8279: jj=0;
8280: for(i=1; i <=nlstate; i++){
8281: for(j=1; j <=nlstate+ndeath; j++){
8282: if(j==i) continue;
8283: for(k=1; k<=ncovmodel;k++){
8284: jj++;
8285: ca[0]= k+'a'-1;ca[1]='\0';
8286: if(itimes==1){
8287: if(mle>=1)
8288: printf("#%1d%1d%d",i,j,k);
8289: fprintf(ficlog,"#%1d%1d%d",i,j,k);
8290: fprintf(ficres,"#%1d%1d%d",i,j,k);
8291: }else{
8292: if(mle>=1)
8293: printf("%1d%1d%d",i,j,k);
8294: fprintf(ficlog,"%1d%1d%d",i,j,k);
8295: fprintf(ficres,"%1d%1d%d",i,j,k);
8296: }
8297: ll=0;
8298: for(li=1;li <=nlstate; li++){
8299: for(lj=1;lj <=nlstate+ndeath; lj++){
8300: if(lj==li) continue;
8301: for(lk=1;lk<=ncovmodel;lk++){
8302: ll++;
8303: if(ll<=jj){
8304: cb[0]= lk +'a'-1;cb[1]='\0';
8305: if(ll<jj){
8306: if(itimes==1){
8307: if(mle>=1)
8308: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8309: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8310: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
8311: }else{
8312: if(mle>=1)
8313: printf(" %.5e",matcov[jj][ll]);
8314: fprintf(ficlog," %.5e",matcov[jj][ll]);
8315: fprintf(ficres," %.5e",matcov[jj][ll]);
8316: }
8317: }else{
8318: if(itimes==1){
8319: if(mle>=1)
8320: printf(" Var(%s%1d%1d)",ca,i,j);
8321: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
8322: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
8323: }else{
8324: if(mle>=1)
8325: printf(" %.7e",matcov[jj][ll]);
8326: fprintf(ficlog," %.7e",matcov[jj][ll]);
8327: fprintf(ficres," %.7e",matcov[jj][ll]);
8328: }
8329: }
8330: }
8331: } /* end lk */
8332: } /* end lj */
8333: } /* end li */
8334: if(mle>=1)
8335: printf("\n");
8336: fprintf(ficlog,"\n");
8337: fprintf(ficres,"\n");
8338: numlinepar++;
8339: } /* end k*/
8340: } /*end j */
8341: } /* end i */
8342: } /* end itimes */
8343:
8344: fflush(ficlog);
8345: fflush(ficres);
8346: while(fgets(line, MAXLINE, ficpar)) {
8347: /* If line starts with a # it is a comment */
8348: if (line[0] == '#') {
8349: numlinepar++;
8350: fputs(line,stdout);
8351: fputs(line,ficparo);
8352: fputs(line,ficlog);
8353: continue;
8354: }else
8355: break;
8356: }
8357:
8358: /* while((c=getc(ficpar))=='#' && c!= EOF){ */
8359: /* ungetc(c,ficpar); */
8360: /* fgets(line, MAXLINE, ficpar); */
8361: /* fputs(line,stdout); */
8362: /* fputs(line,ficparo); */
8363: /* } */
8364: /* ungetc(c,ficpar); */
8365:
8366: estepm=0;
8367: 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){
8368:
8369: if (num_filled != 6) {
8370: printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
8371: printf("but line=%s\n",line);
8372: goto end;
8373: }
8374: printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
8375: }
8376: /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
8377: /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
8378:
8379: /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
8380: if (estepm==0 || estepm < stepm) estepm=stepm;
8381: if (fage <= 2) {
8382: bage = ageminpar;
8383: fage = agemaxpar;
8384: }
8385:
8386: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
8387: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8388: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
8389:
8390: /* Other stuffs, more or less useful */
8391: while((c=getc(ficpar))=='#' && c!= EOF){
8392: ungetc(c,ficpar);
8393: fgets(line, MAXLINE, ficpar);
8394: fputs(line,stdout);
8395: fputs(line,ficparo);
8396: }
8397: ungetc(c,ficpar);
8398:
8399: 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);
8400: 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);
8401: 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);
8402: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
8403: 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);
8404:
8405: while((c=getc(ficpar))=='#' && c!= EOF){
8406: ungetc(c,ficpar);
8407: fgets(line, MAXLINE, ficpar);
8408: fputs(line,stdout);
8409: fputs(line,ficparo);
8410: }
8411: ungetc(c,ficpar);
8412:
8413:
8414: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
8415: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
8416:
8417: fscanf(ficpar,"pop_based=%d\n",&popbased);
8418: fprintf(ficlog,"pop_based=%d\n",popbased);
8419: fprintf(ficparo,"pop_based=%d\n",popbased);
8420: fprintf(ficres,"pop_based=%d\n",popbased);
8421:
8422: while((c=getc(ficpar))=='#' && c!= EOF){
8423: ungetc(c,ficpar);
8424: fgets(line, MAXLINE, ficpar);
8425: fputs(line,stdout);
8426: fputs(line,ficparo);
8427: }
8428: ungetc(c,ficpar);
8429:
8430: 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);
8431: 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);
8432: 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);
8433: 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);
8434: 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);
8435: /* day and month of proj2 are not used but only year anproj2.*/
8436:
8437:
8438:
8439: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
8440: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
8441:
8442: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
8443: if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
8444: printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8445: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8446: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8447: fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
8448: This is probably because your parameter file doesn't \n contain the exact number of lines (or columns) corresponding to your model line.\n\
8449: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
8450: }else
8451: printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
8452:
8453: printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
8454: model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
8455: jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
8456:
8457: /*------------ free_vector -------------*/
8458: /* chdir(path); */
8459:
8460: /* free_ivector(wav,1,imx); */ /* Moved after last prevalence call */
8461: /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
8462: /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
8463: /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx); */
8464: free_lvector(num,1,n);
8465: free_vector(agedc,1,n);
8466: /*free_matrix(covar,0,NCOVMAX,1,n);*/
8467: /*free_matrix(covar,1,NCOVMAX,1,n);*/
8468: fclose(ficparo);
8469: fclose(ficres);
8470:
8471:
8472: /* Other results (useful)*/
8473:
8474:
8475: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
8476: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
8477: prlim=matrix(1,nlstate,1,nlstate);
8478: prevalence_limit(p, prlim, ageminpar, agemaxpar, ftolpl, &ncvyear);
8479: fclose(ficrespl);
8480:
8481: #ifdef FREEEXIT2
8482: #include "freeexit2.h"
8483: #endif
8484:
8485: /*------------- h Pij x at various ages ------------*/
8486: /*#include "hpijx.h"*/
8487: hPijx(p, bage, fage);
8488: fclose(ficrespij);
8489:
8490: /*-------------- Variance of one-step probabilities---*/
8491: k=1;
8492: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
8493:
8494:
8495: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8496: for(i=1;i<=AGESUP;i++)
8497: for(j=1;j<=NCOVMAX;j++)
8498: for(k=1;k<=NCOVMAX;k++)
8499: probs[i][j][k]=0.;
8500:
8501: /*---------- Forecasting ------------------*/
8502: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
8503: if(prevfcast==1){
8504: /* if(stepm ==1){*/
8505: prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
8506: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
8507: /* } */
8508: /* else{ */
8509: /* erreur=108; */
8510: /* 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); */
8511: /* 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); */
8512: /* } */
8513: }
8514:
8515: /* ------ Other prevalence ratios------------ */
8516:
8517: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
8518:
8519: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
8520: /* 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",\
8521: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
8522: */
8523: free_ivector(wav,1,imx);
8524: free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
8525: free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
8526: free_imatrix(mw,1,lastpass-firstpass+2,1,imx);
8527:
8528:
8529: if (mobilav!=0) {
8530: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8531: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
8532: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
8533: printf(" Error in movingaverage mobilav=%d\n",mobilav);
8534: }
8535: }
8536:
8537:
8538: /*---------- Health expectancies, no variances ------------*/
8539:
8540: strcpy(filerese,"E_");
8541: strcat(filerese,fileresu);
8542: if((ficreseij=fopen(filerese,"w"))==NULL) {
8543: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8544: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
8545: }
8546: printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
8547: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
8548: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8549: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8550:
8551: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8552: fprintf(ficreseij,"\n#****** ");
8553: for(j=1;j<=cptcoveff;j++) {
8554: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8555: }
8556: fprintf(ficreseij,"******\n");
8557:
8558: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8559: oldm=oldms;savm=savms;
8560: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
8561:
8562: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8563: /*}*/
8564: }
8565: fclose(ficreseij);
8566: printf("done evsij\n");fflush(stdout);
8567: fprintf(ficlog,"done evsij\n");fflush(ficlog);
8568:
8569: /*---------- Health expectancies and variances ------------*/
8570:
8571:
8572: strcpy(filerest,"T_");
8573: strcat(filerest,fileresu);
8574: if((ficrest=fopen(filerest,"w"))==NULL) {
8575: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
8576: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
8577: }
8578: printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
8579: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
8580:
8581:
8582: strcpy(fileresstde,"STDE_");
8583: strcat(fileresstde,fileresu);
8584: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
8585: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8586: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
8587: }
8588: printf(" Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8589: fprintf(ficlog," Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
8590:
8591: strcpy(filerescve,"CVE_");
8592: strcat(filerescve,fileresu);
8593: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
8594: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8595: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
8596: }
8597: printf(" Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8598: fprintf(ficlog," Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
8599:
8600: strcpy(fileresv,"V_");
8601: strcat(fileresv,fileresu);
8602: if((ficresvij=fopen(fileresv,"w"))==NULL) {
8603: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
8604: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
8605: }
8606: printf(" Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
8607: fprintf(ficlog," Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
8608:
8609: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8610: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8611:
8612: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8613: fprintf(ficrest,"\n#****** ");
8614: for(j=1;j<=cptcoveff;j++)
8615: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8616: fprintf(ficrest,"******\n");
8617:
8618: fprintf(ficresstdeij,"\n#****** ");
8619: fprintf(ficrescveij,"\n#****** ");
8620: for(j=1;j<=cptcoveff;j++) {
8621: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8622: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8623: }
8624: fprintf(ficresstdeij,"******\n");
8625: fprintf(ficrescveij,"******\n");
8626:
8627: fprintf(ficresvij,"\n#****** ");
8628: for(j=1;j<=cptcoveff;j++)
8629: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8630: fprintf(ficresvij,"******\n");
8631:
8632: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8633: oldm=oldms;savm=savms;
8634: printf(" cvevsij %d, ",k);
8635: fprintf(ficlog, " cvevsij %d, ",k);
8636: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
8637: printf(" end cvevsij \n ");
8638: fprintf(ficlog, " end cvevsij \n ");
8639:
8640: /*
8641: */
8642: /* goto endfree; */
8643:
8644: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
8645: pstamp(ficrest);
8646:
8647:
8648: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
8649: oldm=oldms;savm=savms; /* ZZ Segmentation fault */
8650: cptcod= 0; /* To be deleted */
8651: printf("varevsij %d \n",vpopbased);
8652: fprintf(ficlog, "varevsij %d \n",vpopbased);
8653: 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 */
8654: 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 ");
8655: if(vpopbased==1)
8656: 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);
8657: else
8658: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
8659: fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
8660: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
8661: fprintf(ficrest,"\n");
8662: /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
8663: epj=vector(1,nlstate+1);
8664: printf("Computing age specific period (stable) prevalences in each health state \n");
8665: fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
8666: for(age=bage; age <=fage ;age++){
8667: prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
8668: if (vpopbased==1) {
8669: if(mobilav ==0){
8670: for(i=1; i<=nlstate;i++)
8671: prlim[i][i]=probs[(int)age][i][k];
8672: }else{ /* mobilav */
8673: for(i=1; i<=nlstate;i++)
8674: prlim[i][i]=mobaverage[(int)age][i][k];
8675: }
8676: }
8677:
8678: fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
8679: /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
8680: /* printf(" age %4.0f ",age); */
8681: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
8682: for(i=1, epj[j]=0.;i <=nlstate;i++) {
8683: epj[j] += prlim[i][i]*eij[i][j][(int)age];
8684: /*ZZZ printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
8685: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
8686: }
8687: epj[nlstate+1] +=epj[j];
8688: }
8689: /* printf(" age %4.0f \n",age); */
8690:
8691: for(i=1, vepp=0.;i <=nlstate;i++)
8692: for(j=1;j <=nlstate;j++)
8693: vepp += vareij[i][j][(int)age];
8694: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
8695: for(j=1;j <=nlstate;j++){
8696: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
8697: }
8698: fprintf(ficrest,"\n");
8699: }
8700: } /* End vpopbased */
8701: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8702: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
8703: free_vector(epj,1,nlstate+1);
8704: printf("done \n");fflush(stdout);
8705: fprintf(ficlog,"done\n");fflush(ficlog);
8706:
8707: /*}*/
8708: } /* End k */
8709: free_vector(weight,1,n);
8710: free_imatrix(Tvard,1,NCOVMAX,1,2);
8711: free_imatrix(s,1,maxwav+1,1,n);
8712: free_matrix(anint,1,maxwav,1,n);
8713: free_matrix(mint,1,maxwav,1,n);
8714: free_ivector(cod,1,n);
8715: free_ivector(tab,1,NCOVMAX);
8716: fclose(ficresstdeij);
8717: fclose(ficrescveij);
8718: fclose(ficresvij);
8719: fclose(ficrest);
8720: printf("done Health expectancies\n");fflush(stdout);
8721: fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
8722: fclose(ficpar);
8723:
8724: /*------- Variance of period (stable) prevalence------*/
8725:
8726: strcpy(fileresvpl,"VPL_");
8727: strcat(fileresvpl,fileresu);
8728: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
8729: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
8730: exit(0);
8731: }
8732: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
8733: fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
8734:
8735: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
8736: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
8737:
8738: for (k=1; k <= (int) pow(2,cptcoveff); k++){
8739: fprintf(ficresvpl,"\n#****** ");
8740: for(j=1;j<=cptcoveff;j++)
8741: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
8742: fprintf(ficresvpl,"******\n");
8743:
8744: varpl=matrix(1,nlstate,(int) bage, (int) fage);
8745: oldm=oldms;savm=savms;
8746: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
8747: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
8748: /*}*/
8749: }
8750:
8751: fclose(ficresvpl);
8752: printf("done variance-covariance of period prevalence\n");fflush(stdout);
8753: fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
8754:
8755: /*---------- End : free ----------------*/
8756: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
8757: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
8758: } /* mle==-3 arrives here for freeing */
8759: /* endfree:*/
8760: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
8761: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
8762: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
8763: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
8764: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
8765: free_matrix(covar,0,NCOVMAX,1,n);
8766: free_matrix(matcov,1,npar,1,npar);
8767: free_matrix(hess,1,npar,1,npar);
8768: /*free_vector(delti,1,npar);*/
8769: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8770: free_matrix(agev,1,maxwav,1,imx);
8771: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
8772:
8773: free_ivector(ncodemax,1,NCOVMAX);
8774: free_ivector(ncodemaxwundef,1,NCOVMAX);
8775: free_ivector(Tvar,1,NCOVMAX);
8776: free_ivector(Tprod,1,NCOVMAX);
8777: free_ivector(Tvaraff,1,NCOVMAX);
8778: free_ivector(Tage,1,NCOVMAX);
8779:
8780: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
8781: /* free_imatrix(codtab,1,100,1,10); */
8782: fflush(fichtm);
8783: fflush(ficgp);
8784:
8785:
8786: if((nberr >0) || (nbwarn>0)){
8787: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
8788: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
8789: }else{
8790: printf("End of Imach\n");
8791: fprintf(ficlog,"End of Imach\n");
8792: }
8793: printf("See log file on %s\n",filelog);
8794: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
8795: /*(void) gettimeofday(&end_time,&tzp);*/
8796: rend_time = time(NULL);
8797: end_time = *localtime(&rend_time);
8798: /* tml = *localtime(&end_time.tm_sec); */
8799: strcpy(strtend,asctime(&end_time));
8800: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
8801: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
8802: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8803:
8804: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8805: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
8806: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
8807: /* printf("Total time was %d uSec.\n", total_usecs);*/
8808: /* if(fileappend(fichtm,optionfilehtm)){ */
8809: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8810: fclose(fichtm);
8811: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
8812: fclose(fichtmcov);
8813: fclose(ficgp);
8814: fclose(ficlog);
8815: /*------ End -----------*/
8816:
8817:
8818: printf("Before Current directory %s!\n",pathcd);
8819: #ifdef WIN32
8820: if (_chdir(pathcd) != 0)
8821: printf("Can't move to directory %s!\n",path);
8822: if(_getcwd(pathcd,MAXLINE) > 0)
8823: #else
8824: if(chdir(pathcd) != 0)
8825: printf("Can't move to directory %s!\n", path);
8826: if (getcwd(pathcd, MAXLINE) > 0)
8827: #endif
8828: printf("Current directory %s!\n",pathcd);
8829: /*strcat(plotcmd,CHARSEPARATOR);*/
8830: sprintf(plotcmd,"gnuplot");
8831: #ifdef _WIN32
8832: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
8833: #endif
8834: if(!stat(plotcmd,&info)){
8835: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8836: if(!stat(getenv("GNUPLOTBIN"),&info)){
8837: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
8838: }else
8839: strcpy(pplotcmd,plotcmd);
8840: #ifdef __unix
8841: strcpy(plotcmd,GNUPLOTPROGRAM);
8842: if(!stat(plotcmd,&info)){
8843: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
8844: }else
8845: strcpy(pplotcmd,plotcmd);
8846: #endif
8847: }else
8848: strcpy(pplotcmd,plotcmd);
8849:
8850: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
8851: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
8852:
8853: if((outcmd=system(plotcmd)) != 0){
8854: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
8855: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
8856: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
8857: if((outcmd=system(plotcmd)) != 0)
8858: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
8859: }
8860: printf(" Successful, please wait...");
8861: while (z[0] != 'q') {
8862: /* chdir(path); */
8863: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
8864: scanf("%s",z);
8865: /* if (z[0] == 'c') system("./imach"); */
8866: if (z[0] == 'e') {
8867: #ifdef __APPLE__
8868: sprintf(pplotcmd, "open %s", optionfilehtm);
8869: #elif __linux
8870: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
8871: #else
8872: sprintf(pplotcmd, "%s", optionfilehtm);
8873: #endif
8874: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
8875: system(pplotcmd);
8876: }
8877: else if (z[0] == 'g') system(plotcmd);
8878: else if (z[0] == 'q') exit(0);
8879: }
8880: end:
8881: while (z[0] != 'q') {
8882: printf("\nType q for exiting: "); fflush(stdout);
8883: scanf("%s",z);
8884: }
8885: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>